chore: merge origin/main into mintlify/af82bda4 and resolve conflicts
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
# The DeepSeek Harness SDK (@deepseek-ai/dsh-tools) declares the rest of the
|
||||
# harness runtime (dsh-llm, dsh-agent, dsh-scope, ...) as peer dependencies.
|
||||
# The host harness provides those at runtime; this adapter only needs cordis +
|
||||
# dsh-tools to build and type-check. Auto-installing the full peer graph pulls
|
||||
# unpublished internal packages (e.g. dsh-type-meta), so keep it off.
|
||||
auto-install-peers=false
|
||||
package-manager-strict-version=false
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [2023] [Taranjeet Singh]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,95 @@
|
||||
# deepseek-plugin
|
||||
|
||||
[Mem0](https://mem0.ai) long-term memory as a native [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (Cordis) plugin.
|
||||
|
||||
It gives a Harness agent automatic long-term memory plus two explicit memory tools backed by the Mem0 SDK:
|
||||
|
||||
| Capability | Does |
|
||||
|---|---|
|
||||
| Auto-recall | Searches Mem0 for the latest human prompt and adds unseen results to the model context |
|
||||
| Auto-capture | Stores the human/assistant messages from each completed turn |
|
||||
| `search_memory` | Recall facts from Mem0 relevant to a query |
|
||||
| `add_memory` | Store a fact in Mem0 for future sessions |
|
||||
|
||||
Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and memories that other agents can retrieve when their user and entity filters match.
|
||||
|
||||
Current package version: `0.3.0`.
|
||||
|
||||
Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent).
|
||||
|
||||
## How it works
|
||||
|
||||
A Cordis plugin is a module exporting `apply(ctx, config)`. This one waits for the Harness tool and system-prompt services, then uses the native extension points:
|
||||
|
||||
- `system-prompt/assemble` recalls memory before a model request.
|
||||
- `session/event` captures only completed turns from the durable event stream.
|
||||
- `ctx.tools.register(...)` exposes explicit search and add tools.
|
||||
|
||||
Completed human and assistant text is preserved after secret redaction, without the former 6,000-character per-message cutoff. Recall queries and displayed tool results retain separate size limits. These behaviors use [agent-plugin-core](../agent-plugin-core/README.md); this integration keeps its native tools and user-based scoping.
|
||||
|
||||
Cordis owns listener and tool cleanup when the plugin unmounts. Every automatic path is fail-open: a memory API failure does not block the agent.
|
||||
|
||||
```
|
||||
[ mem0ai SDK ] <-- managed memory, owned by Mem0
|
||||
|
|
||||
[ deepseek-plugin: prompt + session listeners, memory tools ] <-- this package
|
||||
|
|
||||
[ DeepSeek Harness ] <-- the agent, loaded via cordis.yml
|
||||
```
|
||||
|
||||
## Try it locally
|
||||
|
||||
1. Build and pack the plugin:
|
||||
```sh
|
||||
cd integrations/deepseek-plugin
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
mkdir -p /tmp/mem0-deepseek-plugin
|
||||
pnpm pack --pack-destination /tmp/mem0-deepseek-plugin
|
||||
```
|
||||
2. Set your Mem0 key:
|
||||
```sh
|
||||
export MEM0_API_KEY=...
|
||||
```
|
||||
3. Install it into a disposable Harness profile:
|
||||
```sh
|
||||
DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
|
||||
plugin --profile headless add /tmp/mem0-deepseek-plugin/mem0-deepseek-plugin-0.3.0.tgz
|
||||
```
|
||||
4. Copy `cordis.example.yml`, set its installed package path and your `userId`, then run Harness with the same profile:
|
||||
```sh
|
||||
DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
|
||||
web --patch ./integrations/deepseek-plugin/cordis.example.yml
|
||||
```
|
||||
5. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn.
|
||||
|
||||
For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` overrides the Platform base URL. It does not support the self-hosted Mem0 OSS API.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Field | Required | Default | Notes |
|
||||
|---|---|---|---|
|
||||
| `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key |
|
||||
| `userId` | yes | | Entity that owns the memories |
|
||||
| `allowUserOverride` | no | `false` | Permit model-selected access to a different user only in a trusted multi-user deployment |
|
||||
| `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) |
|
||||
| `autoRecall` | no | `true` | Recall relevant memory before model requests |
|
||||
| `autoCapture` | no | `true` | Store completed human/assistant turns |
|
||||
|
||||
## Memory scope
|
||||
|
||||
Automatic capture and recall use the configured `userId` across sessions. Automatic writes do not attach a repository ID or `runId`.
|
||||
|
||||
Both `search_memory` and `add_memory` accept optional `agentId` and `runId`. On search, these narrow the returned memories; on add, they attach those identities to the stored memory. Pass a known `runId` to search memories explicitly saved with that session ID. This does not include automatically captured user-only memories or identify the session making the request.
|
||||
|
||||
Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user.
|
||||
|
||||
## Telemetry
|
||||
|
||||
Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. For it to surface by name (rather than bucketing into `OTHERS`), `DEEPSEEK_HARNESS` must be present in the backend's `KNOWN_EVENT_SOURCES` allowlist, a one-line platform change matching the existing `ZAPIER` / `STRANDS` sources.
|
||||
|
||||
The plugin also sends anonymous usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`.
|
||||
|
||||
## Status
|
||||
|
||||
Developer preview. Tracks the DeepSeek Harness v0.1 plugin API, which is young and moving. Harness capability packages are peer dependencies supplied by the host; this package pins matching release-candidate versions for local typechecking and tests.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Example DeepSeek Harness config that loads deepseek-plugin alongside the built-in
|
||||
# tools plugin. Load with:
|
||||
#
|
||||
# DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
|
||||
# web --patch ./integrations/deepseek-plugin/cordis.example.yml
|
||||
#
|
||||
- insert:
|
||||
- id: mem0
|
||||
# Install the packed plugin into this disposable profile first; loading
|
||||
# raw dist bypasses Harness's peer dependency installation.
|
||||
name: "/tmp/mem0-dsh-dev/profiles/headless/node_modules/@mem0/deepseek-plugin/dist/index.js"
|
||||
config:
|
||||
# apiKey is read from the MEM0_API_KEY env var when omitted here.
|
||||
userId: "your-user-id"
|
||||
# autoRecall: true # optional; enabled by default
|
||||
# autoCapture: true # optional; enabled by default
|
||||
# host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "@mem0/deepseek-plugin",
|
||||
"version": "0.3.0",
|
||||
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
|
||||
"type": "module",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mem0ai/mem0",
|
||||
"directory": "integrations/deepseek-plugin"
|
||||
},
|
||||
"keywords": [
|
||||
"deepseek-harness",
|
||||
"dsh",
|
||||
"dsh-plugin",
|
||||
"cordis",
|
||||
"mem0",
|
||||
"memory",
|
||||
"agent"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"mem0ai": "^3.0.7"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "*",
|
||||
"@deepseek-ai/dsh-agent": "*",
|
||||
"@deepseek-ai/dsh-session": "*",
|
||||
"@deepseek-ai/dsh-system-prompt": "*",
|
||||
"@deepseek-ai/dsh-tools": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "4.0.1",
|
||||
"@deepseek-ai/dsh-agent": "0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-session": "0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-system-prompt": "0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-tools": "0.1.1-rc.2",
|
||||
"@types/node": "^22.15.0",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "^5.6.0",
|
||||
"vitest": "^4.1.7"
|
||||
}
|
||||
}
|
||||
+2150
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
formatAddResult,
|
||||
formatAge,
|
||||
formatMemoryCompact,
|
||||
formatMemoryList,
|
||||
} from "../../agent-plugin-core/typescript/src/formatting.ts";
|
||||
export type { MemoryLike } from "../../agent-plugin-core/typescript/src/formatting.ts";
|
||||
@@ -0,0 +1,309 @@
|
||||
/**
|
||||
* deepseek-plugin: Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.
|
||||
*
|
||||
* Registers two agent-callable tools backed by the Mem0 SDK:
|
||||
* - `search_memory` recalls facts relevant to a query
|
||||
* - `add_memory` stores a fact for future sessions
|
||||
*
|
||||
* A plugin is a Cordis module that exports `apply(ctx, config)`. Declaring
|
||||
* `inject = ['tools', 'systemPrompt']` holds the plugin until the harness services exist;
|
||||
* tools registered via `ctx.tools.register(...)` are auto-unregistered when the
|
||||
* plugin unmounts (Cordis revertible effects).
|
||||
*/
|
||||
import type { Context } from "@deepseek-ai/cordis";
|
||||
import type {} from "@deepseek-ai/dsh-agent";
|
||||
import type { PromptAssembly } from "@deepseek-ai/dsh-system-prompt";
|
||||
import type {} from "@deepseek-ai/dsh-session";
|
||||
import { defineTool } from "@deepseek-ai/dsh-tools";
|
||||
import { MemoryClient } from "mem0ai";
|
||||
import { formatMemoryList, formatAddResult } from "./formatting.ts";
|
||||
import { truncateOutput } from "./output.ts";
|
||||
import { resolveSearchFilters, resolveAddParams } from "./scoping.ts";
|
||||
import { captureEvent, errorKind } from "./telemetry.ts";
|
||||
import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
|
||||
|
||||
export const name = "mem0";
|
||||
export const inject = ["tools", "systemPrompt"];
|
||||
|
||||
// Tags writes so Mem0's backend attributes them to this integration in
|
||||
// telemetry. The backend keeps recognized values via its KNOWN_EVENT_SOURCES
|
||||
// allowlist; unknown values bucket into "OTHERS", so "DEEPSEEK_HARNESS" must be
|
||||
// added to that allowlist for usage to surface by name (a one-line backend PR,
|
||||
// same pattern as the ZAPIER / STRANDS sources).
|
||||
const SOURCE = "DEEPSEEK_HARNESS";
|
||||
|
||||
const DEFAULT_SEARCH_LIMIT = 10;
|
||||
const AUTO_RECALL_LIMIT = 5;
|
||||
|
||||
interface HarnessMessage {
|
||||
role: string;
|
||||
content?: unknown;
|
||||
source?: { kind?: string };
|
||||
}
|
||||
|
||||
interface SessionState {
|
||||
lifecycle: ReturnType<typeof createMemoryLifecycle>;
|
||||
messages: HarnessMessage[];
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
/** Mem0 API key. Defaults to the MEM0_API_KEY env var. */
|
||||
apiKey?: string;
|
||||
/** Default entity that owns the memories (Mem0 user scope). */
|
||||
userId: string;
|
||||
/** Explicitly allow model-selected cross-user access. Defaults to false. */
|
||||
allowUserOverride?: boolean;
|
||||
/** Optional Mem0 Platform base-URL override (on-prem / dedicated); defaults to api.mem0.ai. Not a switch to self-hosted OSS. */
|
||||
host?: string;
|
||||
/** Recall relevant memory before each model request. Defaults to true. */
|
||||
autoRecall?: boolean;
|
||||
/** Store completed turns automatically. Defaults to true. */
|
||||
autoCapture?: boolean;
|
||||
}
|
||||
|
||||
// Both tools return a single text string; the render is identical, so lift it
|
||||
// into one shared declaration instead of repeating the block per tool.
|
||||
const textOutput = {
|
||||
schema: { type: "string" } as const,
|
||||
render: (_args: unknown, value: string) => [
|
||||
{ type: "text" as const, text: value },
|
||||
],
|
||||
};
|
||||
|
||||
// Optional per-call scoping params, shared by both tools. A single harness
|
||||
// install can serve more than one entity, so the model may override the
|
||||
// mount-time default per call (see scoping.ts).
|
||||
const scopeParams = {
|
||||
userId: {
|
||||
type: "string",
|
||||
description:
|
||||
"Entity that owns the memory. Defaults to the plugin's configured userId; cross-user overrides require allowUserOverride in plugin configuration.",
|
||||
},
|
||||
agentId: {
|
||||
type: "string",
|
||||
description: "Optional agent scope, to partition memories by agent.",
|
||||
},
|
||||
runId: {
|
||||
type: "string",
|
||||
description: "Optional run/session scope, to partition memories by session.",
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const apiKey = config.apiKey ?? process.env.MEM0_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("deepseek-plugin: set config.apiKey or the MEM0_API_KEY env var");
|
||||
}
|
||||
const userId = config.userId?.trim();
|
||||
if (!userId || /^\*+$/.test(userId)) {
|
||||
throw new Error("deepseek-plugin: config.userId is required");
|
||||
}
|
||||
|
||||
const client = new MemoryClient({
|
||||
apiKey,
|
||||
...(config.host ? { host: config.host } : {}),
|
||||
});
|
||||
const toolLifecycle = createMemoryLifecycle();
|
||||
const sessionStates = new WeakMap<object, SessionState>();
|
||||
const stateFor = (session: object): SessionState => {
|
||||
let state = sessionStates.get(session);
|
||||
if (!state) {
|
||||
const lifecycle = createMemoryLifecycle();
|
||||
lifecycle.beginSession();
|
||||
state = { lifecycle, messages: [] };
|
||||
sessionStates.set(session, state);
|
||||
}
|
||||
return state;
|
||||
};
|
||||
|
||||
captureEvent("deepseek.plugin.mounted", {
|
||||
has_host: Boolean(config.host),
|
||||
auto_recall: config.autoRecall !== false,
|
||||
auto_capture: config.autoCapture !== false,
|
||||
}, client);
|
||||
|
||||
if (config.autoRecall !== false) {
|
||||
ctx.on("system-prompt/assemble", async (_input, context, next): Promise<PromptAssembly> => {
|
||||
const assembly = await next();
|
||||
const { agent, signal } = context;
|
||||
if (!agent || signal?.aborted) return assembly;
|
||||
|
||||
const state = stateFor(agent.session);
|
||||
const prompt = state.lifecycle.prepareConversation(
|
||||
agent.session
|
||||
.deriveMessages()
|
||||
.filter((message) => message.role === "user" && message.source?.kind === "user"),
|
||||
).at(-1)?.content;
|
||||
if (!prompt) return assembly;
|
||||
|
||||
const memoryContext = await state.lifecycle.recall(prompt, true, async (query) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const result = await client.search(query, {
|
||||
filters: resolveSearchFilters({}, userId),
|
||||
topK: AUTO_RECALL_LIMIT,
|
||||
});
|
||||
captureEvent("deepseek.recall.auto", {
|
||||
success: true,
|
||||
duration_ms: Date.now() - started,
|
||||
result_count: result.results?.length ?? 0,
|
||||
}, client);
|
||||
return result;
|
||||
} catch (err) {
|
||||
captureEvent("deepseek.recall.auto", {
|
||||
success: false,
|
||||
duration_ms: Date.now() - started,
|
||||
error_kind: errorKind(err),
|
||||
}, client);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
if (!memoryContext || signal?.aborted) return assembly;
|
||||
return {
|
||||
...assembly,
|
||||
contexts: [...assembly.contexts, { name: "mem0:recall", text: memoryContext }],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (config.autoCapture !== false) {
|
||||
ctx.on("session/event", (session, event) => {
|
||||
const state = stateFor(session);
|
||||
if (event.type === "turn/start") {
|
||||
state.messages = [];
|
||||
} else if (event.type === "user/message" && event.data.source.kind === "user") {
|
||||
state.messages.push(event.data);
|
||||
} else if (event.type === "assistant/message") {
|
||||
state.messages.push(event.data.message);
|
||||
} else if (event.type === "turn/end") {
|
||||
const conversation = state.lifecycle.prepareConversation(state.messages);
|
||||
state.messages = [];
|
||||
if (event.data.reason.kind !== "completed" || conversation.length === 0) return;
|
||||
void client
|
||||
.add(conversation, { userId, source: SOURCE })
|
||||
.then(() => captureEvent("deepseek.capture.auto", {
|
||||
success: true,
|
||||
message_count: conversation.length,
|
||||
}, client))
|
||||
.catch((err: unknown) => captureEvent("deepseek.capture.auto", {
|
||||
success: false,
|
||||
error_kind: errorKind(err),
|
||||
}, client));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Recall. The platform rejects top-level entity params on search, so scope
|
||||
// goes inside `filters` (unlike add below, which takes them top-level).
|
||||
ctx.tools.register(
|
||||
defineTool({
|
||||
name: "search_memory",
|
||||
description:
|
||||
"Search the user's long-term Mem0 memory for facts relevant to a query. Use proactively before answering anything that may depend on what the user told you earlier.",
|
||||
parameters: {
|
||||
query: { type: "string", description: "What to recall.", required: true },
|
||||
limit: {
|
||||
type: "integer",
|
||||
description: `Max results to return (default ${DEFAULT_SEARCH_LIMIT}).`,
|
||||
},
|
||||
...scopeParams,
|
||||
},
|
||||
output: textOutput,
|
||||
async execute({ query, limit, userId: u, agentId, runId }) {
|
||||
if (u?.trim() && u.trim() !== userId && config.allowUserOverride !== true) {
|
||||
throw new Error("Cross-user access requires allowUserOverride in plugin configuration.");
|
||||
}
|
||||
const safeQuery = toolLifecycle.prepareUserText(query);
|
||||
const filters = resolveSearchFilters({ userId: u, agentId, runId }, userId);
|
||||
const topK = limit && limit > 0 ? limit : DEFAULT_SEARCH_LIMIT;
|
||||
const started = Date.now();
|
||||
try {
|
||||
const { results } = await client.search(safeQuery, { filters, topK });
|
||||
captureEvent(
|
||||
"deepseek.tool.search_memory",
|
||||
{
|
||||
success: true,
|
||||
duration_ms: Date.now() - started,
|
||||
top_k: topK,
|
||||
result_count: results?.length ?? 0,
|
||||
query_chars: query.length,
|
||||
scope_overridden: Boolean(u && u !== userId),
|
||||
has_agent_id: Boolean(agentId),
|
||||
has_run_id: Boolean(runId),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return truncateOutput(formatMemoryList(results ?? []));
|
||||
} catch (err) {
|
||||
captureEvent(
|
||||
"deepseek.tool.search_memory",
|
||||
{
|
||||
success: false,
|
||||
duration_ms: Date.now() - started,
|
||||
top_k: topK,
|
||||
error_kind: errorKind(err),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return `search_memory failed: ${err instanceof Error ? err.message : String(err)}`;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Write. `source` tags the memory for telemetry attribution.
|
||||
ctx.tools.register(
|
||||
defineTool({
|
||||
name: "add_memory",
|
||||
description:
|
||||
"Store a fact in the user's long-term Mem0 memory for later sessions. Extraction runs asynchronously server-side, so a stored fact may take a moment to become searchable; do not immediately search to confirm the write.",
|
||||
parameters: {
|
||||
text: { type: "string", description: "The fact to remember.", required: true },
|
||||
...scopeParams,
|
||||
},
|
||||
output: textOutput,
|
||||
async execute({ text, userId: u, agentId, runId }) {
|
||||
if (u?.trim() && u.trim() !== userId && config.allowUserOverride !== true) {
|
||||
throw new Error("Cross-user access requires allowUserOverride in plugin configuration.");
|
||||
}
|
||||
const addParams = resolveAddParams({ userId: u, agentId, runId }, userId);
|
||||
const started = Date.now();
|
||||
try {
|
||||
const result = await client.add(
|
||||
[{ role: "user", content: toolLifecycle.prepareUserText(text) }],
|
||||
{
|
||||
...addParams,
|
||||
source: SOURCE,
|
||||
},
|
||||
);
|
||||
captureEvent(
|
||||
"deepseek.tool.add_memory",
|
||||
{
|
||||
success: true,
|
||||
duration_ms: Date.now() - started,
|
||||
text_chars: text.length,
|
||||
memory_count: Array.isArray(result) ? result.length : 0,
|
||||
scope_overridden: Boolean(u && u !== userId),
|
||||
has_agent_id: Boolean(agentId),
|
||||
has_run_id: Boolean(runId),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return truncateOutput(formatAddResult(result));
|
||||
} catch (err) {
|
||||
captureEvent(
|
||||
"deepseek.tool.add_memory",
|
||||
{
|
||||
success: false,
|
||||
duration_ms: Date.now() - started,
|
||||
text_chars: text.length,
|
||||
error_kind: errorKind(err),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return `add_memory failed: ${err instanceof Error ? err.message : String(err)}`;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
MAX_OUTPUT_BYTES,
|
||||
MAX_OUTPUT_LINES,
|
||||
truncateOutput,
|
||||
} from "../../agent-plugin-core/typescript/src/formatting.ts";
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
entityAddParams as resolveAddParams,
|
||||
entitySearchFilters as resolveSearchFilters,
|
||||
} from "../../agent-plugin-core/typescript/src/identity.ts";
|
||||
export type { EntityParams } from "../../agent-plugin-core/typescript/src/identity.ts";
|
||||
@@ -0,0 +1,98 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
createTelemetry,
|
||||
errorKind,
|
||||
isTelemetryEnabled,
|
||||
} from "../../agent-plugin-core/typescript/src/telemetry.ts";
|
||||
|
||||
export { errorKind, isTelemetryEnabled };
|
||||
|
||||
const PLUGIN_VERSION = (() => {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8")).version;
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
})();
|
||||
|
||||
export interface TelemetryIdentity {
|
||||
telemetryId?: string;
|
||||
}
|
||||
|
||||
let cachedAnonymousId: string | undefined;
|
||||
let identified = false;
|
||||
let currentDistinctId = "";
|
||||
|
||||
function identityPath(): string {
|
||||
return path.join(os.homedir(), ".mem0", "deepseek-plugin-telemetry.json");
|
||||
}
|
||||
|
||||
function anonymousId(): string {
|
||||
if (cachedAnonymousId) return cachedAnonymousId;
|
||||
try {
|
||||
const stored = JSON.parse(fs.readFileSync(identityPath(), "utf-8"));
|
||||
if (typeof stored.anonymousId === "string" && stored.anonymousId) {
|
||||
return (cachedAnonymousId = stored.anonymousId);
|
||||
}
|
||||
} catch {
|
||||
// First run or unreadable identity file.
|
||||
}
|
||||
const created = `deepseek-anon-${randomUUID().replace(/-/g, "")}`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(identityPath()), { recursive: true });
|
||||
fs.writeFileSync(identityPath(), JSON.stringify({ anonymousId: created }), "utf-8");
|
||||
} catch {
|
||||
// An unwritable home directory must not break the plugin.
|
||||
}
|
||||
return (cachedAnonymousId = created);
|
||||
}
|
||||
|
||||
function previousAnonymousId(distinctId: string): string | undefined {
|
||||
if (identified || distinctId.startsWith("deepseek-anon-")) return undefined;
|
||||
identified = true;
|
||||
try {
|
||||
const stored = JSON.parse(fs.readFileSync(identityPath(), "utf-8")).anonymousId;
|
||||
fs.unlinkSync(identityPath());
|
||||
cachedAnonymousId = undefined;
|
||||
return typeof stored === "string" && stored ? stored : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const telemetry = createTelemetry({
|
||||
host: "deepseek",
|
||||
source: "DEEPSEEK_HARNESS",
|
||||
version: PLUGIN_VERSION,
|
||||
distinctId: () => currentDistinctId,
|
||||
});
|
||||
|
||||
export function captureEvent(
|
||||
event: string,
|
||||
properties: Record<string, unknown>,
|
||||
client: TelemetryIdentity,
|
||||
): void {
|
||||
currentDistinctId = client.telemetryId || anonymousId();
|
||||
const anonymous = previousAnonymousId(currentDistinctId);
|
||||
if (anonymous) telemetry.capture("$identify", { $anon_distinct_id: anonymous });
|
||||
telemetry.capture(event, properties);
|
||||
}
|
||||
|
||||
export function flushEvents(): void {
|
||||
void telemetry.flush();
|
||||
}
|
||||
|
||||
export function _queueForTesting(): Record<string, unknown>[] {
|
||||
return telemetry.queueForTesting();
|
||||
}
|
||||
|
||||
export function _resetForTesting(): void {
|
||||
telemetry.resetForTesting();
|
||||
cachedAnonymousId = undefined;
|
||||
currentDistinctId = "";
|
||||
identified = false;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
// Offline mock of the Mem0 SDK so these tests never touch the network.
|
||||
const mockSearch = vi.fn();
|
||||
const mockAdd = vi.fn();
|
||||
vi.mock("mem0ai", () => ({
|
||||
MemoryClient: class {
|
||||
search = mockSearch;
|
||||
add = mockAdd;
|
||||
},
|
||||
}));
|
||||
|
||||
// The real `@deepseek-ai/dsh-tools` runtime transitively imports harness peer
|
||||
// packages the host provides at runtime but which aren't installed here. For
|
||||
// these unit tests we only need `defineTool` to hand back the definition it was
|
||||
// given, so the registered tool's `execute`/`name` can be exercised directly.
|
||||
vi.mock("@deepseek-ai/dsh-tools", () => ({
|
||||
defineTool: (options: unknown) => options,
|
||||
}));
|
||||
|
||||
import { apply, type Config } from "../src/index.ts";
|
||||
|
||||
interface RegisteredTool {
|
||||
name: string;
|
||||
execute(args: unknown, exec: unknown): Promise<unknown>;
|
||||
}
|
||||
|
||||
type HarnessListener = (...args: any[]) => unknown;
|
||||
|
||||
function applyAndCollect(config: Config): Map<string, RegisteredTool> {
|
||||
const tools = new Map<string, RegisteredTool>();
|
||||
const ctx = {
|
||||
tools: { register: (t: RegisteredTool) => tools.set(t.name, t) },
|
||||
on: vi.fn(),
|
||||
};
|
||||
apply(ctx as never, config);
|
||||
return tools;
|
||||
}
|
||||
|
||||
function applyAndCollectListeners(config: Config): Map<string, HarnessListener> {
|
||||
const listeners = new Map<string, HarnessListener>();
|
||||
const ctx = {
|
||||
tools: { register: vi.fn() },
|
||||
on: (event: string, listener: HarnessListener) => listeners.set(event, listener),
|
||||
};
|
||||
apply(ctx as never, config);
|
||||
return listeners;
|
||||
}
|
||||
|
||||
let savedKey: string | undefined;
|
||||
let savedTelemetry: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
savedKey = process.env.MEM0_API_KEY;
|
||||
savedTelemetry = process.env.MEM0_TELEMETRY;
|
||||
process.env.MEM0_TELEMETRY = "false";
|
||||
mockSearch.mockReset();
|
||||
mockAdd.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (savedKey === undefined) delete process.env.MEM0_API_KEY;
|
||||
else process.env.MEM0_API_KEY = savedKey;
|
||||
if (savedTelemetry === undefined) delete process.env.MEM0_TELEMETRY;
|
||||
else process.env.MEM0_TELEMETRY = savedTelemetry;
|
||||
});
|
||||
|
||||
describe("apply() config validation", () => {
|
||||
it("throws when no apiKey is set and MEM0_API_KEY is absent", () => {
|
||||
delete process.env.MEM0_API_KEY;
|
||||
expect(() => applyAndCollect({ userId: "u" } as Config)).toThrow(/apiKey|MEM0_API_KEY/);
|
||||
});
|
||||
|
||||
it("throws when userId is missing", () => {
|
||||
expect(() => applyAndCollect({ apiKey: "k", userId: "" } as Config)).toThrow(/userId/);
|
||||
});
|
||||
|
||||
it("registers both memory tools", () => {
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
expect([...tools.keys()].sort()).toEqual(["add_memory", "search_memory"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Harness lifecycle", () => {
|
||||
it("automatically recalls memory into the prompt for the latest human message", async () => {
|
||||
mockSearch.mockResolvedValue({
|
||||
results: [{ id: "m1", memory: "Likes tea" }],
|
||||
});
|
||||
const listeners = applyAndCollectListeners({ apiKey: "k", userId: "u" });
|
||||
const assemble = listeners.get("system-prompt/assemble")!;
|
||||
const base = { sections: [], contexts: [], tools: [], variables: {} };
|
||||
|
||||
const result = await assemble(
|
||||
base,
|
||||
{
|
||||
agent: {
|
||||
session: {
|
||||
deriveMessages: () => [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "What do I drink?" }],
|
||||
source: { kind: "user" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
async () => base,
|
||||
);
|
||||
|
||||
expect(mockSearch).toHaveBeenCalledWith("What do I drink?", {
|
||||
filters: { user_id: "u" },
|
||||
topK: 5,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
contexts: [{ name: "mem0:recall", text: expect.stringContaining("Likes tea") }],
|
||||
});
|
||||
});
|
||||
|
||||
it("automatically captures a completed human and assistant turn", async () => {
|
||||
mockAdd.mockResolvedValue({ eventId: "evt-1", status: "PENDING" });
|
||||
const listeners = applyAndCollectListeners({ apiKey: "k", userId: "u" });
|
||||
const onSessionEvent = listeners.get("session/event")!;
|
||||
const session = {};
|
||||
|
||||
onSessionEvent(session, { type: "turn/start", data: { turn: 1 } });
|
||||
onSessionEvent(session, {
|
||||
type: "user/message",
|
||||
data: {
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Remember I like tea" }],
|
||||
source: { kind: "user" },
|
||||
},
|
||||
});
|
||||
onSessionEvent(session, {
|
||||
type: "assistant/message",
|
||||
data: {
|
||||
turn: 1,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "I will remember that." }],
|
||||
source: { kind: "model" },
|
||||
},
|
||||
},
|
||||
});
|
||||
onSessionEvent(session, {
|
||||
type: "turn/end",
|
||||
data: { turn: 1, reason: { kind: "completed" } },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockAdd).toHaveBeenCalledWith(
|
||||
[
|
||||
{ role: "user", content: "Remember I like tea" },
|
||||
{ role: "assistant", content: "I will remember that." },
|
||||
],
|
||||
{ userId: "u", source: "DEEPSEEK_HARNESS" },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("can disable automatic recall and capture without removing the memory tools", () => {
|
||||
const listeners = applyAndCollectListeners({
|
||||
apiKey: "k",
|
||||
userId: "u",
|
||||
autoRecall: false,
|
||||
autoCapture: false,
|
||||
});
|
||||
|
||||
expect(listeners.has("system-prompt/assemble")).toBe(false);
|
||||
expect(listeners.has("session/event")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("search_memory tool", () => {
|
||||
it("returns a formatted list scoped to the configured user", async () => {
|
||||
mockSearch.mockResolvedValue({
|
||||
results: [{ id: "m1", memory: "Likes tea", categories: ["preference"] }],
|
||||
});
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("search_memory")!.execute({ query: "drink" }, {});
|
||||
|
||||
expect(out).toContain("Likes tea");
|
||||
expect(out).toContain("[mem0:m1]");
|
||||
expect(mockSearch).toHaveBeenCalledWith("drink", {
|
||||
filters: { user_id: "u" },
|
||||
topK: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it("honors a per-call userId override and limit", async () => {
|
||||
mockSearch.mockResolvedValue({ results: [] });
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u", allowUserOverride: true });
|
||||
|
||||
await tools.get("search_memory")!.execute({ query: "x", userId: "alice", limit: 3 }, {});
|
||||
|
||||
expect(mockSearch).toHaveBeenCalledWith("x", {
|
||||
filters: { user_id: "alice" },
|
||||
topK: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a graceful failure line instead of rejecting on error", async () => {
|
||||
mockSearch.mockRejectedValue(new Error("network down"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("search_memory")!.execute({ query: "x" }, {});
|
||||
|
||||
expect(out).toContain("search_memory failed");
|
||||
expect(out).toContain("network down");
|
||||
});
|
||||
});
|
||||
|
||||
describe("add_memory tool", () => {
|
||||
it("reports the write as queued on the async PENDING response, with camelCase scope + source", async () => {
|
||||
// The real /v3/memories/add/ response — not an array of memories. The SDK
|
||||
// camel-cases response keys, so it surfaces as `eventId`, not `event_id`.
|
||||
mockAdd.mockResolvedValue({ eventId: "evt-123", status: "PENDING" });
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "remember this" }, {});
|
||||
|
||||
expect(out).toContain("queued");
|
||||
expect(out).toContain("evt-123");
|
||||
expect(out).not.toContain("No new distinct memory");
|
||||
expect(mockAdd).toHaveBeenCalledWith(
|
||||
[{ role: "user", content: "remember this" }],
|
||||
{ userId: "u", source: "DEEPSEEK_HARNESS" },
|
||||
);
|
||||
});
|
||||
|
||||
it("renders a list when the backend returns memories", async () => {
|
||||
mockAdd.mockResolvedValue([{ id: "m1", memory: "Fact" }]);
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "x" }, {});
|
||||
|
||||
expect(out).toContain("Stored 1 memory");
|
||||
expect(out).toContain("[mem0:m1]");
|
||||
});
|
||||
|
||||
it("redacts credentials before storing explicit memory", async () => {
|
||||
mockAdd.mockResolvedValue([]);
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
await tools.get("add_memory")!.execute({ text: "api_key=do-not-store-this" }, {});
|
||||
|
||||
expect(mockAdd).toHaveBeenCalledWith(
|
||||
[{ role: "user", content: "api_key=[REDACTED]" }],
|
||||
{ userId: "u", source: "DEEPSEEK_HARNESS" },
|
||||
);
|
||||
});
|
||||
|
||||
it("returns a graceful failure line on error", async () => {
|
||||
mockAdd.mockRejectedValue(new Error("boom"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "x" }, {});
|
||||
|
||||
expect(out).toContain("add_memory failed");
|
||||
expect(out).toContain("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool user ownership", () => {
|
||||
it("rejects cross-user reads and writes before contacting Mem0", async () => {
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
await expect(tools.get("search_memory")!.execute({ query: "x", userId: "other" }, {})).rejects.toThrow(/allowUserOverride/);
|
||||
await expect(tools.get("add_memory")!.execute({ text: "x", userId: "other" }, {})).rejects.toThrow(/allowUserOverride/);
|
||||
expect(mockSearch).not.toHaveBeenCalled();
|
||||
expect(mockAdd).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
formatAge,
|
||||
formatMemoryCompact,
|
||||
formatMemoryList,
|
||||
formatAddResult,
|
||||
} from "../src/formatting.ts";
|
||||
|
||||
describe("formatAge", () => {
|
||||
it("formats minutes, hours, and days", () => {
|
||||
expect(formatAge(new Date(Date.now() - 30 * 60_000))).toBe("30m ago");
|
||||
expect(formatAge(new Date(Date.now() - 3 * 3_600_000))).toBe("3h ago");
|
||||
expect(formatAge(new Date(Date.now() - 5 * 86_400_000))).toBe("5d ago");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMemoryCompact", () => {
|
||||
it("renders one line with category, text, and id", () => {
|
||||
const line = formatMemoryCompact({
|
||||
id: "abc-123",
|
||||
memory: "User prefers dark mode",
|
||||
categories: ["preference"],
|
||||
createdAt: new Date(),
|
||||
});
|
||||
expect(line).toContain("[preference]");
|
||||
expect(line).toContain("User prefers dark mode");
|
||||
expect(line).toContain("[mem0:abc-123]");
|
||||
});
|
||||
|
||||
it("falls back to uncategorized and (empty)", () => {
|
||||
expect(formatMemoryCompact({ id: "x" })).toContain("[uncategorized]");
|
||||
expect(formatMemoryCompact({ id: "x" })).toContain("(empty)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMemoryList", () => {
|
||||
it("numbers multiple memories", () => {
|
||||
const output = formatMemoryList([
|
||||
{ id: "id-1", memory: "Fact one", categories: ["insight"] },
|
||||
{ id: "id-2", memory: "Fact two", categories: ["convention"] },
|
||||
]);
|
||||
expect(output).toContain("1.");
|
||||
expect(output).toContain("2.");
|
||||
});
|
||||
|
||||
it("returns a plain message when there are no memories", () => {
|
||||
expect(formatMemoryList([])).toBe("No memories found.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatAddResult", () => {
|
||||
it("reports queued for the async PENDING response, with the event id", () => {
|
||||
// SDK camel-cases response keys, so the real shape is `eventId`.
|
||||
const out = formatAddResult({ eventId: "evt-9", status: "PENDING" });
|
||||
expect(out).toContain("queued");
|
||||
expect(out).toContain("evt-9");
|
||||
});
|
||||
|
||||
it("reports the stored count when the backend returns memories", () => {
|
||||
expect(formatAddResult([{ id: "1", memory: "A" }])).toContain("Stored 1 memory");
|
||||
expect(formatAddResult([{ id: "1" }, { id: "2" }])).toContain("Stored 2 memories");
|
||||
});
|
||||
|
||||
it("unwraps a { results: [...] } envelope", () => {
|
||||
expect(formatAddResult({ results: [{ id: "1", memory: "A" }] })).toContain("Stored 1 memory");
|
||||
});
|
||||
|
||||
it("handles an empty result", () => {
|
||||
expect(formatAddResult([])).toBe("Memory stored.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { truncateOutput, MAX_OUTPUT_LINES } from "../src/output.ts";
|
||||
|
||||
describe("truncateOutput", () => {
|
||||
it("passes small output through untouched", () => {
|
||||
expect(truncateOutput("a\nb\nc")).toBe("a\nb\nc");
|
||||
});
|
||||
|
||||
it("caps output at MAX_OUTPUT_LINES and appends a notice", () => {
|
||||
const many = Array.from({ length: MAX_OUTPUT_LINES + 50 }, (_, i) => `line ${i}`).join("\n");
|
||||
const out = truncateOutput(many);
|
||||
expect(out.split("\n").length).toBeLessThanOrEqual(MAX_OUTPUT_LINES + 3);
|
||||
expect(out).toContain("[Output truncated:");
|
||||
expect(out).toContain(`of ${MAX_OUTPUT_LINES + 50} lines`);
|
||||
});
|
||||
|
||||
it("caps output that is few lines but very large by bytes", () => {
|
||||
const huge = "x".repeat(60_000);
|
||||
const out = truncateOutput(huge);
|
||||
expect(out.length).toBeLessThan(huge.length);
|
||||
expect(out).toContain("[Output truncated:");
|
||||
});
|
||||
|
||||
it("reports both reasons when the line cap and the byte cap fire together", () => {
|
||||
const wide = Array.from({ length: MAX_OUTPUT_LINES + 50 }, () => "x".repeat(300)).join("\n");
|
||||
const out = truncateOutput(wide);
|
||||
expect(out).toContain(`of ${MAX_OUTPUT_LINES + 50} lines`);
|
||||
expect(out).toContain("cut at 50KB");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { resolveSearchFilters, resolveAddParams } from "../src/scoping.ts";
|
||||
|
||||
describe("resolveSearchFilters (snake_case, for filters)", () => {
|
||||
it("falls back to the configured default userId", () => {
|
||||
expect(resolveSearchFilters({}, "default-user")).toEqual({ user_id: "default-user" });
|
||||
});
|
||||
|
||||
it("lets a per-call userId override the default", () => {
|
||||
expect(resolveSearchFilters({ userId: "alice" }, "default-user")).toEqual({
|
||||
user_id: "alice",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a blank/whitespace userId as absent and falls back", () => {
|
||||
expect(resolveSearchFilters({ userId: " " }, "default-user")).toEqual({
|
||||
user_id: "default-user",
|
||||
});
|
||||
});
|
||||
|
||||
it("includes snake_case agent/run scope only when provided", () => {
|
||||
expect(
|
||||
resolveSearchFilters({ userId: "alice", agentId: "agent-1", runId: "run-9" }, "d"),
|
||||
).toEqual({ user_id: "alice", agent_id: "agent-1", run_id: "run-9" });
|
||||
});
|
||||
|
||||
it("omits blank agent/run scope", () => {
|
||||
const f = resolveSearchFilters({ agentId: " ", runId: "run-9" }, "default");
|
||||
expect(f).toEqual({ user_id: "default", run_id: "run-9" });
|
||||
expect(f).not.toHaveProperty("agent_id");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAddParams (camelCase, for top-level add params)", () => {
|
||||
it("uses camelCase keys and falls back to the default userId", () => {
|
||||
expect(resolveAddParams({}, "default-user")).toEqual({ userId: "default-user" });
|
||||
});
|
||||
|
||||
it("includes camelCase agent/run scope only when provided", () => {
|
||||
expect(
|
||||
resolveAddParams({ userId: "alice", agentId: "agent-1", runId: "run-9" }, "d"),
|
||||
).toEqual({ userId: "alice", agentId: "agent-1", runId: "run-9" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
const mockSearch = vi.fn();
|
||||
const mockAdd = vi.fn();
|
||||
vi.mock("mem0ai", () => ({
|
||||
MemoryClient: class {
|
||||
telemetryId = "dev@example.com";
|
||||
search = mockSearch;
|
||||
add = mockAdd;
|
||||
},
|
||||
}));
|
||||
vi.mock("@deepseek-ai/dsh-tools", () => ({ defineTool: (options: unknown) => options }));
|
||||
|
||||
import { apply, type Config } from "../src/index.ts";
|
||||
import {
|
||||
captureEvent,
|
||||
errorKind,
|
||||
flushEvents,
|
||||
isTelemetryEnabled,
|
||||
_queueForTesting,
|
||||
_resetForTesting,
|
||||
} from "../src/telemetry.ts";
|
||||
|
||||
interface RegisteredTool {
|
||||
name: string;
|
||||
execute(args: unknown, exec: unknown): Promise<unknown>;
|
||||
}
|
||||
|
||||
function applyAndCollect(config: Config): Map<string, RegisteredTool> {
|
||||
const tools = new Map<string, RegisteredTool>();
|
||||
apply({
|
||||
tools: { register: (t: RegisteredTool) => tools.set(t.name, t) },
|
||||
on: vi.fn(),
|
||||
} as never, config);
|
||||
return tools;
|
||||
}
|
||||
|
||||
function queued(): Record<string, any>[] {
|
||||
return _queueForTesting() as Record<string, any>[];
|
||||
}
|
||||
|
||||
let home: string;
|
||||
let savedHome: string | undefined;
|
||||
let savedTelemetry: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
savedHome = process.env.HOME;
|
||||
savedTelemetry = process.env.MEM0_TELEMETRY;
|
||||
delete process.env.MEM0_TELEMETRY;
|
||||
home = fs.mkdtempSync(path.join(os.tmpdir(), "mem0-deepseek-"));
|
||||
process.env.HOME = home;
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true }));
|
||||
mockSearch.mockReset();
|
||||
mockAdd.mockReset();
|
||||
_resetForTesting();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
_resetForTesting();
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
if (savedHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = savedHome;
|
||||
if (savedTelemetry === undefined) delete process.env.MEM0_TELEMETRY;
|
||||
else process.env.MEM0_TELEMETRY = savedTelemetry;
|
||||
});
|
||||
|
||||
describe("opt-out", () => {
|
||||
it("queues nothing for every documented off value", () => {
|
||||
for (const value of ["false", "0", "no", "OFF"]) {
|
||||
process.env.MEM0_TELEMETRY = value;
|
||||
expect(isTelemetryEnabled()).toBe(false);
|
||||
captureEvent("deepseek.tool.search_memory", {}, { telemetryId: "dev@example.com" });
|
||||
}
|
||||
expect(queued()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("is on by default", () => {
|
||||
expect(isTelemetryEnabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("identity", () => {
|
||||
it("keys events on the account email the SDK resolved", () => {
|
||||
captureEvent("deepseek.tool.add_memory", {}, { telemetryId: "dev@example.com" });
|
||||
expect(queued()[0].distinct_id).toBe("dev@example.com");
|
||||
});
|
||||
|
||||
it("falls back to a persisted anonymous id before the SDK has pinged", () => {
|
||||
captureEvent("deepseek.tool.add_memory", {}, {});
|
||||
const first = queued()[0].distinct_id as string;
|
||||
expect(first).toMatch(/^deepseek-anon-/);
|
||||
|
||||
_resetForTesting();
|
||||
captureEvent("deepseek.tool.add_memory", {}, {});
|
||||
expect(queued()[0].distinct_id).toBe(first);
|
||||
});
|
||||
|
||||
it("aliases the anonymous history onto the email exactly once", () => {
|
||||
captureEvent("deepseek.tool.add_memory", {}, {});
|
||||
const anonymous = queued()[0].distinct_id;
|
||||
_resetForTesting();
|
||||
|
||||
captureEvent("deepseek.tool.add_memory", {}, { telemetryId: "dev@example.com" });
|
||||
const [identify, event] = queued();
|
||||
expect(identify.event).toBe("$identify");
|
||||
expect(identify.distinct_id).toBe("dev@example.com");
|
||||
expect(identify.properties.$anon_distinct_id).toBe(anonymous);
|
||||
expect(event.distinct_id).toBe("dev@example.com");
|
||||
|
||||
captureEvent("deepseek.tool.add_memory", {}, { telemetryId: "dev@example.com" });
|
||||
expect(queued().filter((e) => e.event === "$identify")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event shape", () => {
|
||||
it("stamps every event with the integration source and runtime baseline", () => {
|
||||
captureEvent("deepseek.tool.search_memory", { success: true }, { telemetryId: "d@e.com" });
|
||||
const { properties } = queued()[0];
|
||||
expect(properties.source).toBe("DEEPSEEK_HARNESS");
|
||||
expect(properties.language).toBe("node");
|
||||
expect(properties.$process_person_profile).toBe(false);
|
||||
expect(properties.os).toBe(process.platform);
|
||||
expect(properties.plugin_version).not.toBe("unknown");
|
||||
expect(properties.success).toBe(true);
|
||||
});
|
||||
|
||||
it("flushes one batch to PostHog and empties the queue", async () => {
|
||||
captureEvent("deepseek.tool.search_memory", {}, { telemetryId: "d@e.com" });
|
||||
flushEvents();
|
||||
|
||||
const [url, init] = (fetch as unknown as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(url).toContain("posthog.com");
|
||||
expect(JSON.parse(init.body).batch).toHaveLength(1);
|
||||
expect(queued()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("never throws when the network is gone", () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("fetch failed")));
|
||||
captureEvent("deepseek.tool.search_memory", {}, { telemetryId: "d@e.com" });
|
||||
expect(() => flushEvents()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("errorKind", () => {
|
||||
it("buckets failures without leaking the message", () => {
|
||||
expect(errorKind(new Error("Request failed with status 429"))).toBe("rate-limited");
|
||||
expect(errorKind(new Error("401 Unauthorized"))).toBe("auth");
|
||||
expect(errorKind(new Error("503 Service Unavailable"))).toBe("server-error");
|
||||
expect(errorKind(new Error("The operation was aborted due to timeout"))).toBe("timeout");
|
||||
expect(errorKind(new Error("fetch failed"))).toBe("network");
|
||||
expect(errorKind(new Error("token sk-abcdef is invalid"))).toBe("Error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool instrumentation", () => {
|
||||
it("records a mount, then a successful search with its shape but not its query", async () => {
|
||||
mockSearch.mockResolvedValue({ results: [{ id: "m1", memory: "Likes tea" }] });
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
await tools.get("search_memory")!.execute({ query: "what drink", limit: 3 }, {});
|
||||
|
||||
const [mounted, search] = queued();
|
||||
expect(mounted.event).toBe("deepseek.plugin.mounted");
|
||||
expect(mounted.properties.has_host).toBe(false);
|
||||
expect(search.event).toBe("deepseek.tool.search_memory");
|
||||
expect(search.properties).toMatchObject({
|
||||
success: true,
|
||||
top_k: 3,
|
||||
result_count: 1,
|
||||
query_chars: 10,
|
||||
scope_overridden: false,
|
||||
has_agent_id: false,
|
||||
has_run_id: false,
|
||||
});
|
||||
expect(typeof search.properties.duration_ms).toBe("number");
|
||||
expect(JSON.stringify(search)).not.toContain("what drink");
|
||||
expect(JSON.stringify(search)).not.toContain("Likes tea");
|
||||
});
|
||||
|
||||
it("records a failed search with a coarse error kind", async () => {
|
||||
mockSearch.mockRejectedValue(new Error("429 rate limit exceeded"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
await tools.get("search_memory")!.execute({ query: "x" }, {});
|
||||
|
||||
const search = queued().at(-1)!;
|
||||
expect(search.properties).toMatchObject({ success: false, error_kind: "rate-limited" });
|
||||
});
|
||||
|
||||
it("records a write with its size but not its text", async () => {
|
||||
mockAdd.mockResolvedValue([{ id: "m1", memory: "Fact" }]);
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u", allowUserOverride: true });
|
||||
|
||||
await tools.get("add_memory")!.execute({ text: "secret fact", userId: "alice" }, {});
|
||||
|
||||
const add = queued().at(-1)!;
|
||||
expect(add.event).toBe("deepseek.tool.add_memory");
|
||||
expect(add.properties).toMatchObject({
|
||||
success: true,
|
||||
text_chars: 11,
|
||||
memory_count: 1,
|
||||
scope_overridden: true,
|
||||
});
|
||||
expect(JSON.stringify(add)).not.toContain("secret fact");
|
||||
expect(JSON.stringify(add)).not.toContain("alice");
|
||||
});
|
||||
|
||||
it("records a failed write and still returns the graceful failure line", async () => {
|
||||
mockAdd.mockRejectedValue(new Error("boom"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "x" }, {});
|
||||
|
||||
expect(out).toContain("add_memory failed");
|
||||
expect(queued().at(-1)!.properties).toMatchObject({ success: false, error_kind: "Error" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022"],
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"types": ["node"],
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
// The harness runtime and the Mem0 SDK are provided by the host / installed
|
||||
// separately; keep them out of the bundle.
|
||||
external: [/^node:/, /^@deepseek-ai\//, "mem0ai", /^mem0ai\//],
|
||||
});
|
||||
Reference in New Issue
Block a user