@dangvv/openclaw-mem0 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts ADDED
@@ -0,0 +1,1600 @@
1
+ /**
2
+ * OpenClaw Memory (Mem0) Plugin
3
+ *
4
+ * Long-term memory via Mem0 — supports both the Mem0 platform
5
+ * and the open-source self-hosted SDK. Uses the official `mem0ai` package.
6
+ *
7
+ * Features:
8
+ * - 5 tools: memory_search, memory_list, memory_store, memory_get, memory_forget
9
+ * (with session/long-term scope support via scope and longTerm parameters)
10
+ * - Short-term (session-scoped) and long-term (user-scoped) memory
11
+ * - Auto-recall: injects relevant memories (both scopes) before each agent turn
12
+ * - Auto-capture: stores key facts scoped to the current session after each agent turn
13
+ * - Per-agent isolation: multi-agent setups write/read from separate userId namespaces
14
+ * automatically via sessionKey routing (zero breaking changes for single-agent setups)
15
+ * - CLI: openclaw mem0 search, openclaw mem0 stats
16
+ * - Dual mode: platform or open-source (self-hosted)
17
+ */
18
+
19
+ import { Type } from "@sinclair/typebox";
20
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
21
+
22
+ // ============================================================================
23
+ // Types
24
+ // ============================================================================
25
+
26
+ type Mem0Mode = "platform" | "open-source";
27
+
28
+ type Mem0Config = {
29
+ mode: Mem0Mode;
30
+ // Platform-specific
31
+ apiKey?: string;
32
+ orgId?: string;
33
+ projectId?: string;
34
+ customInstructions: string;
35
+ customCategories: Record<string, string>;
36
+ enableGraph: boolean;
37
+ // OSS-specific
38
+ customPrompt?: string;
39
+ oss?: {
40
+ embedder?: { provider: string; config: Record<string, unknown> };
41
+ vectorStore?: { provider: string; config: Record<string, unknown> };
42
+ llm?: { provider: string; config: Record<string, unknown> };
43
+ graphStore?: {
44
+ provider: string;
45
+ config: Record<string, unknown>;
46
+ customPrompt?: string;
47
+ custom_prompt?: string;
48
+ threshold?: number;
49
+ };
50
+ historyDbPath?: string;
51
+ };
52
+ // Shared
53
+ userId: string;
54
+ autoCapture: boolean;
55
+ autoRecall: boolean;
56
+ searchThreshold: number;
57
+ topK: number;
58
+ };
59
+
60
+ // Unified types for the provider interface
61
+ interface AddOptions {
62
+ user_id: string;
63
+ run_id?: string;
64
+ custom_instructions?: string;
65
+ custom_categories?: Array<Record<string, string>>;
66
+ enable_graph?: boolean;
67
+ output_format?: string;
68
+ source?: string;
69
+ }
70
+
71
+ interface SearchOptions {
72
+ user_id: string;
73
+ run_id?: string;
74
+ top_k?: number;
75
+ threshold?: number;
76
+ limit?: number;
77
+ keyword_search?: boolean;
78
+ reranking?: boolean;
79
+ enable_graph?: boolean;
80
+ source?: string;
81
+ }
82
+
83
+ interface ListOptions {
84
+ user_id: string;
85
+ run_id?: string;
86
+ page_size?: number;
87
+ enable_graph?: boolean;
88
+ source?: string;
89
+ }
90
+
91
+ interface MemoryItem {
92
+ id: string;
93
+ memory: string;
94
+ user_id?: string;
95
+ score?: number;
96
+ categories?: string[];
97
+ metadata?: Record<string, unknown>;
98
+ created_at?: string;
99
+ updated_at?: string;
100
+ }
101
+
102
+ interface AddResultItem {
103
+ id: string;
104
+ memory: string;
105
+ event: "ADD" | "UPDATE" | "DELETE" | "NOOP";
106
+ }
107
+
108
+ interface AddResult {
109
+ results: AddResultItem[];
110
+ }
111
+
112
+ interface SearchResult {
113
+ items: MemoryItem[];
114
+ relations?: unknown[];
115
+ }
116
+
117
+ // ============================================================================
118
+ // Unified Provider Interface
119
+ // ============================================================================
120
+
121
+ interface Mem0Provider {
122
+ add(
123
+ messages: Array<{ role: string; content: string }>,
124
+ options: AddOptions,
125
+ ): Promise<AddResult>;
126
+ search(query: string, options: SearchOptions): Promise<SearchResult>;
127
+ get(memoryId: string): Promise<MemoryItem>;
128
+ getAll(options: ListOptions): Promise<MemoryItem[]>;
129
+ delete(memoryId: string): Promise<void>;
130
+ }
131
+
132
+ // ============================================================================
133
+ // Platform Provider (Mem0 Cloud)
134
+ // ============================================================================
135
+
136
+ class PlatformProvider implements Mem0Provider {
137
+ private client: any; // MemoryClient from mem0ai
138
+ private initPromise: Promise<void> | null = null;
139
+
140
+ constructor(
141
+ private readonly apiKey: string,
142
+ private readonly orgId?: string,
143
+ private readonly projectId?: string,
144
+ ) { }
145
+
146
+ private async ensureClient(): Promise<void> {
147
+ if (this.client) return;
148
+ if (this.initPromise) return this.initPromise;
149
+ this.initPromise = this._init();
150
+ return this.initPromise;
151
+ }
152
+
153
+ private async _init(): Promise<void> {
154
+ const { default: MemoryClient } = await import("mem0ai");
155
+ const opts: Record<string, string> = { apiKey: this.apiKey };
156
+ if (this.orgId) opts.org_id = this.orgId;
157
+ if (this.projectId) opts.project_id = this.projectId;
158
+ this.client = new MemoryClient(opts);
159
+ }
160
+
161
+ async add(
162
+ messages: Array<{ role: string; content: string }>,
163
+ options: AddOptions,
164
+ ): Promise<AddResult> {
165
+ await this.ensureClient();
166
+ const opts: Record<string, unknown> = { user_id: options.user_id };
167
+ if (options.run_id) opts.run_id = options.run_id;
168
+ if (options.custom_instructions)
169
+ opts.custom_instructions = options.custom_instructions;
170
+ if (options.custom_categories)
171
+ opts.custom_categories = options.custom_categories;
172
+ if (options.enable_graph) opts.enable_graph = options.enable_graph;
173
+ if (options.output_format) opts.output_format = options.output_format;
174
+ if (options.source) opts.source = options.source;
175
+
176
+ const result = await this.client.add(messages, opts);
177
+ return normalizeAddResult(result);
178
+ }
179
+
180
+ async search(query: string, options: SearchOptions): Promise<SearchResult> {
181
+ await this.ensureClient();
182
+ const filters: Record<string, unknown> = { user_id: options.user_id };
183
+ if (options.run_id) filters.run_id = options.run_id;
184
+
185
+ const opts: Record<string, unknown> = {
186
+ api_version: "v2",
187
+ filters,
188
+ };
189
+ if (options.top_k != null) opts.top_k = options.top_k;
190
+ if (options.threshold != null) opts.threshold = options.threshold;
191
+ if (options.keyword_search != null) opts.keyword_search = options.keyword_search;
192
+ if (options.reranking != null) opts.rerank = options.reranking;
193
+ if (options.enable_graph != null) opts.enable_graph = options.enable_graph;
194
+
195
+ const results = await this.client.search(query, opts);
196
+ return normalizeSearchResult(results);
197
+ }
198
+
199
+ async get(memoryId: string): Promise<MemoryItem> {
200
+ await this.ensureClient();
201
+ const result = await this.client.get(memoryId);
202
+ return normalizeMemoryItem(result);
203
+ }
204
+
205
+ async getAll(options: ListOptions): Promise<MemoryItem[]> {
206
+ await this.ensureClient();
207
+ const opts: Record<string, unknown> = { user_id: options.user_id };
208
+ if (options.run_id) opts.run_id = options.run_id;
209
+ if (options.page_size != null) opts.page_size = options.page_size;
210
+ if (options.enable_graph != null) opts.enable_graph = options.enable_graph;
211
+ if (options.source) opts.source = options.source;
212
+
213
+ const results = await this.client.getAll(opts);
214
+ if (Array.isArray(results)) return results.map(normalizeMemoryItem);
215
+ // Some versions return { results: [...] }
216
+ if (results?.results && Array.isArray(results.results))
217
+ return results.results.map(normalizeMemoryItem);
218
+ return [];
219
+ }
220
+
221
+ async delete(memoryId: string): Promise<void> {
222
+ await this.ensureClient();
223
+ await this.client.delete(memoryId);
224
+ }
225
+ }
226
+
227
+ // ============================================================================
228
+ // Open-Source Provider (Self-hosted)
229
+ // ============================================================================
230
+
231
+ class OSSProvider implements Mem0Provider {
232
+ private memory: any; // Memory from mem0ai/oss
233
+ private initPromise: Promise<void> | null = null;
234
+
235
+ constructor(
236
+ private readonly ossConfig?: Mem0Config["oss"],
237
+ private readonly customPrompt?: string,
238
+ private readonly enableGraph?: boolean,
239
+ private readonly resolvePath?: (p: string) => string,
240
+ ) { }
241
+
242
+ private async ensureMemory(): Promise<void> {
243
+ if (this.memory) return;
244
+ if (this.initPromise) return this.initPromise;
245
+ this.initPromise = this._init();
246
+ return this.initPromise;
247
+ }
248
+
249
+ private async _init(): Promise<void> {
250
+ const { Memory } = await import("mem0ai/oss");
251
+
252
+ const config: Record<string, unknown> = { version: "v1.1" };
253
+
254
+ if (this.ossConfig?.embedder) config.embedder = this.ossConfig.embedder;
255
+ if (this.ossConfig?.vectorStore)
256
+ config.vectorStore = this.ossConfig.vectorStore;
257
+ if (this.ossConfig?.llm) config.llm = this.ossConfig.llm;
258
+ if (this.ossConfig?.graphStore)
259
+ config.graphStore = this.ossConfig.graphStore;
260
+ if (this.enableGraph) config.enableGraph = true;
261
+
262
+ if (this.ossConfig?.historyDbPath) {
263
+ const dbPath = this.resolvePath
264
+ ? this.resolvePath(this.ossConfig.historyDbPath)
265
+ : this.ossConfig.historyDbPath;
266
+ config.historyDbPath = dbPath;
267
+ }
268
+
269
+ if (this.customPrompt) config.customPrompt = this.customPrompt;
270
+
271
+ this.memory = new Memory(config);
272
+ }
273
+
274
+ async add(
275
+ messages: Array<{ role: string; content: string }>,
276
+ options: AddOptions,
277
+ ): Promise<AddResult> {
278
+ await this.ensureMemory();
279
+ // OSS SDK uses camelCase: userId/runId, not user_id/run_id
280
+ const addOpts: Record<string, unknown> = { userId: options.user_id };
281
+ if (options.run_id) addOpts.runId = options.run_id;
282
+ if (options.source) addOpts.source = options.source;
283
+ const result = await this.memory.add(messages, addOpts);
284
+ return normalizeAddResult(result);
285
+ }
286
+
287
+ async search(query: string, options: SearchOptions): Promise<SearchResult> {
288
+ await this.ensureMemory();
289
+ // OSS SDK uses camelCase: userId/runId, not user_id/run_id
290
+ const opts: Record<string, unknown> = { userId: options.user_id };
291
+ if (options.run_id) opts.runId = options.run_id;
292
+ if (options.limit != null) opts.limit = options.limit;
293
+ else if (options.top_k != null) opts.limit = options.top_k;
294
+ if (options.keyword_search != null) opts.keyword_search = options.keyword_search;
295
+ if (options.reranking != null) opts.reranking = options.reranking;
296
+ if (options.enable_graph != null) opts.enableGraph = options.enable_graph;
297
+ if (options.source) opts.source = options.source;
298
+ if (options.threshold != null) opts.threshold = options.threshold;
299
+
300
+ const results = await this.memory.search(query, opts);
301
+ const normalized = normalizeSearchResult(results);
302
+
303
+ // Filter results by threshold if specified (client-side filtering as fallback)
304
+ if (options.threshold != null) {
305
+ return {
306
+ ...normalized,
307
+ items: normalized.items.filter(item => (item.score ?? 0) >= options.threshold!),
308
+ };
309
+ }
310
+
311
+ return normalized;
312
+ }
313
+
314
+ async get(memoryId: string): Promise<MemoryItem> {
315
+ await this.ensureMemory();
316
+ const result = await this.memory.get(memoryId);
317
+ return normalizeMemoryItem(result);
318
+ }
319
+
320
+ async getAll(options: ListOptions): Promise<MemoryItem[]> {
321
+ await this.ensureMemory();
322
+ // OSS SDK uses camelCase: userId/runId, not user_id/run_id
323
+ const getAllOpts: Record<string, unknown> = { userId: options.user_id };
324
+ if (options.run_id) getAllOpts.runId = options.run_id;
325
+ if (options.enable_graph != null) getAllOpts.enableGraph = options.enable_graph;
326
+ if (options.source) getAllOpts.source = options.source;
327
+ const results = await this.memory.getAll(getAllOpts);
328
+ if (Array.isArray(results)) return results.map(normalizeMemoryItem);
329
+ if (results?.results && Array.isArray(results.results))
330
+ return results.results.map(normalizeMemoryItem);
331
+ return [];
332
+ }
333
+
334
+ async delete(memoryId: string): Promise<void> {
335
+ await this.ensureMemory();
336
+ await this.memory.delete(memoryId);
337
+ }
338
+ }
339
+
340
+ // ============================================================================
341
+ // Result Normalizers
342
+ // ============================================================================
343
+
344
+ function normalizeMemoryItem(raw: any): MemoryItem {
345
+ return {
346
+ id: raw.id ?? raw.memory_id ?? "",
347
+ memory: raw.memory ?? raw.text ?? raw.content ?? "",
348
+ // Handle both platform (user_id, created_at) and OSS (userId, createdAt) field names
349
+ user_id: raw.user_id ?? raw.userId,
350
+ score: raw.score,
351
+ categories: raw.categories,
352
+ metadata: raw.metadata,
353
+ created_at: raw.created_at ?? raw.createdAt,
354
+ updated_at: raw.updated_at ?? raw.updatedAt,
355
+ };
356
+ }
357
+
358
+ function normalizeSearchResult(raw: any): SearchResult {
359
+ // Platform API may return a flat array, OSS returns { results: [...], relations?: [...] }
360
+ if (Array.isArray(raw)) {
361
+ return { items: raw.map(normalizeMemoryItem) };
362
+ }
363
+ if (raw?.results && Array.isArray(raw.results)) {
364
+ return {
365
+ items: raw.results.map(normalizeMemoryItem),
366
+ relations: Array.isArray(raw.relations) ? raw.relations : undefined,
367
+ };
368
+ }
369
+ return { items: [] };
370
+ }
371
+
372
+ function normalizeAddResult(raw: any): AddResult {
373
+ // Handle { results: [...] } shape (both platform and OSS)
374
+ if (raw?.results && Array.isArray(raw.results)) {
375
+ return {
376
+ results: raw.results.map((r: any) => ({
377
+ id: r.id ?? r.memory_id ?? "",
378
+ memory: r.memory ?? r.text ?? "",
379
+ // Platform API may return PENDING status (async processing)
380
+ // OSS stores event in metadata.event
381
+ event: r.event ?? r.metadata?.event ?? (r.status === "PENDING" ? "ADD" : "ADD"),
382
+ })),
383
+ };
384
+ }
385
+ // Platform API without output_format returns flat array
386
+ if (Array.isArray(raw)) {
387
+ return {
388
+ results: raw.map((r: any) => ({
389
+ id: r.id ?? r.memory_id ?? "",
390
+ memory: r.memory ?? r.text ?? "",
391
+ event: r.event ?? r.metadata?.event ?? (r.status === "PENDING" ? "ADD" : "ADD"),
392
+ })),
393
+ };
394
+ }
395
+ return { results: [] };
396
+ }
397
+
398
+ // ============================================================================
399
+ // Config Parser
400
+ // ============================================================================
401
+
402
+ function resolveEnvVars(value: string): string {
403
+ return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
404
+ const envValue = process.env[envVar];
405
+ if (!envValue) {
406
+ throw new Error(`Environment variable ${envVar} is not set`);
407
+ }
408
+ return envValue;
409
+ });
410
+ }
411
+
412
+ function resolveEnvVarsDeep(obj: Record<string, unknown>): Record<string, unknown> {
413
+ const result: Record<string, unknown> = {};
414
+ for (const [key, value] of Object.entries(obj)) {
415
+ if (typeof value === "string") {
416
+ result[key] = resolveEnvVars(value);
417
+ } else if (value && typeof value === "object" && !Array.isArray(value)) {
418
+ result[key] = resolveEnvVarsDeep(value as Record<string, unknown>);
419
+ } else {
420
+ result[key] = value;
421
+ }
422
+ }
423
+ return result;
424
+ }
425
+
426
+ // ============================================================================
427
+ // Default Custom Instructions & Categories
428
+ // ============================================================================
429
+
430
+ const DEFAULT_CUSTOM_INSTRUCTIONS = `Your Task: Extract and maintain a structured, evolving profile of the user from their conversations with an AI assistant. Capture information that would help the assistant provide personalized, context-aware responses in future interactions.
431
+
432
+ Information to Extract:
433
+
434
+ 1. Identity & Demographics:
435
+ - Name, age, location, timezone, language preferences
436
+ - Occupation, employer, job role, industry
437
+ - Education background
438
+
439
+ 2. Preferences & Opinions:
440
+ - Communication style preferences (formal/casual, verbose/concise)
441
+ - Tool and technology preferences (languages, frameworks, editors, OS)
442
+ - Content preferences (topics of interest, learning style)
443
+ - Strong opinions or values they've expressed
444
+ - Likes and dislikes they've explicitly stated
445
+
446
+ 3. Goals & Projects:
447
+ - Current projects they're working on (name, description, status)
448
+ - Short-term and long-term goals
449
+ - Deadlines and milestones mentioned
450
+ - Problems they're actively trying to solve
451
+
452
+ 4. Technical Context:
453
+ - Tech stack and tools they use
454
+ - Skill level in different areas (beginner/intermediate/expert)
455
+ - Development environment and setup details
456
+ - Recurring technical challenges
457
+
458
+ 5. Relationships & People:
459
+ - Names and roles of people they mention (colleagues, family, friends)
460
+ - Team structure and dynamics
461
+ - Key contacts and their relevance
462
+
463
+ 6. Decisions & Lessons:
464
+ - Important decisions made and their reasoning
465
+ - Lessons learned from past experiences
466
+ - Strategies that worked or failed
467
+ - Changed opinions or updated beliefs
468
+
469
+ 7. Routines & Habits:
470
+ - Daily routines and schedules mentioned
471
+ - Work patterns (when they're productive, how they organize work)
472
+ - Health and wellness habits if voluntarily shared
473
+
474
+ 8. Life Events:
475
+ - Significant events (new job, moving, milestones)
476
+ - Upcoming events or plans
477
+ - Changes in circumstances
478
+
479
+ Guidelines:
480
+ - Store memories as clear, self-contained statements (each memory should make sense on its own)
481
+ - Use third person: "User prefers..." not "I prefer..."
482
+ - Include temporal context when relevant: "As of [date], user is working on..."
483
+ - When information updates, UPDATE the existing memory rather than creating duplicates
484
+ - Merge related facts into single coherent memories when possible
485
+ - Preserve specificity: "User uses Next.js 14 with App Router" is better than "User uses React"
486
+ - Capture the WHY behind preferences when stated: "User prefers Vim because of keyboard-driven workflow"
487
+
488
+ Exclude:
489
+ - Passwords, API keys, tokens, or any authentication credentials
490
+ - Exact financial amounts (account balances, salaries) unless the user explicitly asks to remember them
491
+ - Temporary or ephemeral information (one-time questions, debugging sessions with no lasting insight)
492
+ - Generic small talk with no informational content
493
+ - The assistant's own responses unless they contain a commitment or promise to the user
494
+ - Raw code snippets (capture the intent/decision, not the code itself)
495
+ - Information the user explicitly asks not to remember`;
496
+
497
+ const DEFAULT_CUSTOM_CATEGORIES: Record<string, string> = {
498
+ identity:
499
+ "Personal identity information: name, age, location, timezone, occupation, employer, education, demographics",
500
+ preferences:
501
+ "Explicitly stated likes, dislikes, preferences, opinions, and values across any domain",
502
+ goals:
503
+ "Current and future goals, aspirations, objectives, targets the user is working toward",
504
+ projects:
505
+ "Specific projects, initiatives, or endeavors the user is working on, including status and details",
506
+ technical:
507
+ "Technical skills, tools, tech stack, development environment, programming languages, frameworks",
508
+ decisions:
509
+ "Important decisions made, reasoning behind choices, strategy changes, and their outcomes",
510
+ relationships:
511
+ "People mentioned by the user: colleagues, family, friends, their roles and relevance",
512
+ routines:
513
+ "Daily habits, work patterns, schedules, productivity routines, health and wellness habits",
514
+ life_events:
515
+ "Significant life events, milestones, transitions, upcoming plans and changes",
516
+ lessons:
517
+ "Lessons learned, insights gained, mistakes acknowledged, changed opinions or beliefs",
518
+ work:
519
+ "Work-related context: job responsibilities, workplace dynamics, career progression, professional challenges",
520
+ health:
521
+ "Health-related information voluntarily shared: conditions, medications, fitness, wellness goals",
522
+ };
523
+
524
+ // ============================================================================
525
+ // Config Schema
526
+ // ============================================================================
527
+
528
+ const ALLOWED_KEYS = [
529
+ "mode",
530
+ "apiKey",
531
+ "userId",
532
+ "orgId",
533
+ "projectId",
534
+ "autoCapture",
535
+ "autoRecall",
536
+ "customInstructions",
537
+ "customCategories",
538
+ "customPrompt",
539
+ "enableGraph",
540
+ "searchThreshold",
541
+ "topK",
542
+ "oss",
543
+ ];
544
+
545
+ function assertAllowedKeys(
546
+ value: Record<string, unknown>,
547
+ allowed: string[],
548
+ label: string,
549
+ ) {
550
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
551
+ if (unknown.length === 0) return;
552
+ throw new Error(`${label} has unknown keys: ${unknown.join(", ")}`);
553
+ }
554
+
555
+ const mem0ConfigSchema = {
556
+ parse(value: unknown): Mem0Config {
557
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
558
+ throw new Error("openclaw-mem0 config required");
559
+ }
560
+ const cfg = value as Record<string, unknown>;
561
+ assertAllowedKeys(cfg, ALLOWED_KEYS, "openclaw-mem0 config");
562
+
563
+ // Accept both "open-source" and legacy "oss" as open-source mode; everything else is platform
564
+ const mode: Mem0Mode =
565
+ cfg.mode === "oss" || cfg.mode === "open-source" ? "open-source" : "platform";
566
+
567
+ // Platform mode requires apiKey
568
+ if (mode === "platform") {
569
+ if (typeof cfg.apiKey !== "string" || !cfg.apiKey) {
570
+ throw new Error(
571
+ "apiKey is required for platform mode (set mode: \"open-source\" for self-hosted)",
572
+ );
573
+ }
574
+ }
575
+
576
+ // Resolve env vars in oss config
577
+ let ossConfig: Mem0Config["oss"];
578
+ if (cfg.oss && typeof cfg.oss === "object" && !Array.isArray(cfg.oss)) {
579
+ ossConfig = resolveEnvVarsDeep(
580
+ cfg.oss as Record<string, unknown>,
581
+ ) as unknown as Mem0Config["oss"];
582
+ }
583
+
584
+ return {
585
+ mode,
586
+ apiKey:
587
+ typeof cfg.apiKey === "string" ? resolveEnvVars(cfg.apiKey) : undefined,
588
+ userId:
589
+ typeof cfg.userId === "string" && cfg.userId ? cfg.userId : "default",
590
+ orgId: typeof cfg.orgId === "string" ? cfg.orgId : undefined,
591
+ projectId: typeof cfg.projectId === "string" ? cfg.projectId : undefined,
592
+ autoCapture: cfg.autoCapture !== false,
593
+ autoRecall: cfg.autoRecall !== false,
594
+ customInstructions:
595
+ typeof cfg.customInstructions === "string"
596
+ ? cfg.customInstructions
597
+ : DEFAULT_CUSTOM_INSTRUCTIONS,
598
+ customCategories:
599
+ cfg.customCategories &&
600
+ typeof cfg.customCategories === "object" &&
601
+ !Array.isArray(cfg.customCategories)
602
+ ? (cfg.customCategories as Record<string, string>)
603
+ : DEFAULT_CUSTOM_CATEGORIES,
604
+ customPrompt:
605
+ typeof cfg.customPrompt === "string"
606
+ ? cfg.customPrompt
607
+ : DEFAULT_CUSTOM_INSTRUCTIONS,
608
+ enableGraph: cfg.enableGraph === true,
609
+ searchThreshold:
610
+ typeof cfg.searchThreshold === "number" ? cfg.searchThreshold : 0.5,
611
+ topK: typeof cfg.topK === "number" ? cfg.topK : 5,
612
+ oss: ossConfig,
613
+ };
614
+ },
615
+ };
616
+
617
+ // ============================================================================
618
+ // Provider Factory
619
+ // ============================================================================
620
+
621
+ function createProvider(
622
+ cfg: Mem0Config,
623
+ api: OpenClawPluginApi,
624
+ ): Mem0Provider {
625
+ if (cfg.mode === "open-source") {
626
+ return new OSSProvider(cfg.oss, cfg.customPrompt, cfg.enableGraph, (p) =>
627
+ api.resolvePath(p),
628
+ );
629
+ }
630
+
631
+ return new PlatformProvider(cfg.apiKey!, cfg.orgId, cfg.projectId);
632
+ }
633
+
634
+ function formatRelation(relation: unknown): string | undefined {
635
+ if (typeof relation === "string") return relation;
636
+ if (!relation || typeof relation !== "object") return undefined;
637
+
638
+ const rel = relation as Record<string, unknown>;
639
+ const source =
640
+ rel.source ?? rel.from ?? rel.subject ?? rel.source_node ?? rel.sourceNode;
641
+ const target =
642
+ rel.target ?? rel.to ?? rel.object ?? rel.destination ?? rel.target_node ?? rel.targetNode;
643
+ const type =
644
+ rel.relationship ?? rel.relation ?? rel.type ?? rel.edge ?? rel.label;
645
+
646
+ if (source && target && type) {
647
+ return `${String(source)} -[${String(type)}]-> ${String(target)}`;
648
+ }
649
+
650
+ return rel.fact && typeof rel.fact === "string"
651
+ ? rel.fact
652
+ : undefined;
653
+ }
654
+
655
+ // ============================================================================
656
+ // Helpers
657
+ // ============================================================================
658
+
659
+ /** Convert Record<string, string> categories to the array format mem0ai expects */
660
+ function categoriesToArray(
661
+ cats: Record<string, string>,
662
+ ): Array<Record<string, string>> {
663
+ return Object.entries(cats).map(([key, value]) => ({ [key]: value }));
664
+ }
665
+
666
+ // ============================================================================
667
+ // Per-agent isolation helpers (exported for testability)
668
+ // ============================================================================
669
+
670
+ /**
671
+ * Parse an agent ID from a session key following the pattern `agent:<agentId>:<uuid>`.
672
+ * Returns undefined for non-agent sessions, the "main" sentinel, or malformed keys.
673
+ */
674
+ export function extractAgentId(sessionKey: string | undefined): string | undefined {
675
+ if (!sessionKey) return undefined;
676
+ const match = sessionKey.match(/^agent:([^:]+):/);
677
+ const agentId = match?.[1];
678
+ // "main" is the primary session — fall back to configured userId
679
+ if (!agentId || agentId === "main") return undefined;
680
+ return agentId;
681
+ }
682
+
683
+ /**
684
+ * Derive the effective user_id from a session key, namespacing per-agent.
685
+ * Falls back to baseUserId when the session is not agent-scoped.
686
+ */
687
+ export function effectiveUserId(baseUserId: string, sessionKey?: string): string {
688
+ const agentId = extractAgentId(sessionKey);
689
+ return agentId ? `${baseUserId}:agent:${agentId}` : baseUserId;
690
+ }
691
+
692
+ /** Build a user_id for an explicit agentId (e.g. from tool params). */
693
+ export function agentUserId(baseUserId: string, agentId: string): string {
694
+ return `${baseUserId}:agent:${agentId}`;
695
+ }
696
+
697
+ /**
698
+ * Resolve user_id with priority: explicit agentId > explicit userId > session-derived > configured.
699
+ */
700
+ export function resolveUserId(
701
+ baseUserId: string,
702
+ opts: { agentId?: string; userId?: string },
703
+ currentSessionId?: string,
704
+ ): string {
705
+ if (opts.agentId) return agentUserId(baseUserId, opts.agentId);
706
+ if (opts.userId) return opts.userId;
707
+ return effectiveUserId(baseUserId, currentSessionId);
708
+ }
709
+
710
+ // ============================================================================
711
+ // Plugin Definition
712
+ // ============================================================================
713
+
714
+ const memoryPlugin = {
715
+ id: "openclaw-mem0",
716
+ name: "Memory (Mem0)",
717
+ description:
718
+ "Mem0 memory backend — Mem0 platform or self-hosted open-source",
719
+ kind: "memory" as const,
720
+ configSchema: mem0ConfigSchema,
721
+
722
+ register(api: OpenClawPluginApi) {
723
+ const cfg = mem0ConfigSchema.parse(api.pluginConfig);
724
+ const provider = createProvider(cfg, api);
725
+
726
+ // Track current session ID for tool-level session scoping
727
+ let currentSessionId: string | undefined;
728
+
729
+ // ========================================================================
730
+ // Per-agent isolation helpers (thin wrappers around exported functions)
731
+ // ========================================================================
732
+ const _effectiveUserId = (sessionKey?: string) =>
733
+ effectiveUserId(cfg.userId, sessionKey);
734
+ const _agentUserId = (id: string) => agentUserId(cfg.userId, id);
735
+ const _resolveUserId = (opts: { agentId?: string; userId?: string }) =>
736
+ resolveUserId(cfg.userId, opts, currentSessionId);
737
+
738
+ api.logger.info(
739
+ `openclaw-mem0: registered (mode: ${cfg.mode}, user: ${cfg.userId}, graph: ${cfg.enableGraph}, autoRecall: ${cfg.autoRecall}, autoCapture: ${cfg.autoCapture})`,
740
+ );
741
+
742
+ // Helper: build add options
743
+ function buildAddOptions(userIdOverride?: string, runId?: string, sessionKey?: string): AddOptions {
744
+ const opts: AddOptions = {
745
+ user_id: userIdOverride || _effectiveUserId(sessionKey),
746
+ source: "OPENCLAW",
747
+ };
748
+ if (runId) opts.run_id = runId;
749
+ if (cfg.mode === "platform") {
750
+ opts.custom_instructions = cfg.customInstructions;
751
+ opts.custom_categories = categoriesToArray(cfg.customCategories);
752
+ opts.enable_graph = cfg.enableGraph;
753
+ opts.output_format = "v1.1";
754
+ }
755
+ return opts;
756
+ }
757
+
758
+ // Helper: build search options
759
+ function buildSearchOptions(
760
+ userIdOverride?: string,
761
+ limit?: number,
762
+ runId?: string,
763
+ sessionKey?: string,
764
+ ): SearchOptions {
765
+ const opts: SearchOptions = {
766
+ user_id: userIdOverride || _effectiveUserId(sessionKey),
767
+ top_k: limit ?? cfg.topK,
768
+ limit: limit ?? cfg.topK,
769
+ threshold: cfg.searchThreshold,
770
+ keyword_search: true,
771
+ reranking: true,
772
+ enable_graph: cfg.enableGraph,
773
+ source: "OPENCLAW",
774
+ };
775
+ if (runId) opts.run_id = runId;
776
+ return opts;
777
+ }
778
+
779
+ // ========================================================================
780
+ // Tools
781
+ // ========================================================================
782
+
783
+ api.registerTool(
784
+ {
785
+ name: "memory_search",
786
+ label: "Memory Search",
787
+ description:
788
+ "Search through long-term memories stored in Mem0. Use when you need context about user preferences, past decisions, or previously discussed topics.",
789
+ parameters: Type.Object({
790
+ query: Type.String({ description: "Search query" }),
791
+ limit: Type.Optional(
792
+ Type.Number({
793
+ description: `Max results (default: ${cfg.topK})`,
794
+ }),
795
+ ),
796
+ userId: Type.Optional(
797
+ Type.String({
798
+ description:
799
+ "User ID to scope search (default: configured userId)",
800
+ }),
801
+ ),
802
+ agentId: Type.Optional(
803
+ Type.String({
804
+ description:
805
+ "Agent ID to search memories for a specific agent (e.g. \"researcher\"). Overrides userId.",
806
+ }),
807
+ ),
808
+ scope: Type.Optional(
809
+ Type.Union([
810
+ Type.Literal("session"),
811
+ Type.Literal("long-term"),
812
+ Type.Literal("all"),
813
+ ], {
814
+ description:
815
+ 'Memory scope: "session" (current session only), "long-term" (user-scoped only), or "all" (both). Default: "all"',
816
+ }),
817
+ ),
818
+ }),
819
+ async execute(_toolCallId, params) {
820
+ const { query, limit, userId, agentId, scope = "all" } = params as {
821
+ query: string;
822
+ limit?: number;
823
+ userId?: string;
824
+ agentId?: string;
825
+ scope?: "session" | "long-term" | "all";
826
+ };
827
+
828
+ try {
829
+ let results: SearchResult = { items: [] };
830
+ const uid = _resolveUserId({ agentId, userId });
831
+
832
+ if (scope === "session") {
833
+ if (currentSessionId) {
834
+ results = await provider.search(
835
+ query,
836
+ buildSearchOptions(uid, limit, currentSessionId),
837
+ );
838
+ }
839
+ } else if (scope === "long-term") {
840
+ results = await provider.search(
841
+ query,
842
+ buildSearchOptions(uid, limit),
843
+ );
844
+ } else {
845
+ // "all" — search both scopes and combine
846
+ const longTermResults = await provider.search(
847
+ query,
848
+ buildSearchOptions(uid, limit),
849
+ );
850
+ let sessionResults: SearchResult = { items: [] };
851
+ if (currentSessionId) {
852
+ sessionResults = await provider.search(
853
+ query,
854
+ buildSearchOptions(uid, limit, currentSessionId),
855
+ );
856
+ }
857
+ // Deduplicate by ID, preferring long-term
858
+ const seen = new Set(longTermResults.items.map((r) => r.id));
859
+ results = {
860
+ items: [
861
+ ...longTermResults.items,
862
+ ...sessionResults.items.filter((r) => !seen.has(r.id)),
863
+ ],
864
+ relations: [
865
+ ...(longTermResults.relations ?? []),
866
+ ...(sessionResults.relations ?? []),
867
+ ],
868
+ };
869
+ }
870
+
871
+ const text = results.items
872
+ .map(
873
+ (r, i) =>
874
+ `${i + 1}. ${r.memory} (score: ${((r.score ?? 0) * 100).toFixed(0)}%, id: ${r.id})`,
875
+ )
876
+ .join("\n");
877
+
878
+ const sanitized = results.items.map((r) => ({
879
+ id: r.id,
880
+ memory: r.memory,
881
+ score: r.score,
882
+ categories: r.categories,
883
+ created_at: r.created_at,
884
+ }));
885
+ const relationLines = (results.relations ?? [])
886
+ .map(formatRelation)
887
+ .filter((line): line is string => Boolean(line));
888
+ const hasSignals = results.items.length > 0 || relationLines.length > 0;
889
+ if (!hasSignals) {
890
+ return {
891
+ content: [
892
+ { type: "text", text: "No relevant memories found." },
893
+ ],
894
+ details: { count: 0 },
895
+ };
896
+ }
897
+ const relationText = relationLines.length
898
+ ? `\n\nGraph relations:\n${relationLines.map((line, i) => `${i + 1}. ${line}`).join("\n")}`
899
+ : "";
900
+
901
+ return {
902
+ content: [
903
+ {
904
+ type: "text",
905
+ text: `${results.items.length > 0 ? `Found ${results.items.length} memories:\n\n${text}` : "No vector memories matched."}${relationText}`,
906
+ },
907
+ ],
908
+ details: {
909
+ count: results.items.length,
910
+ memories: sanitized,
911
+ relations: results.relations ?? [],
912
+ },
913
+ };
914
+ } catch (err) {
915
+ return {
916
+ content: [
917
+ {
918
+ type: "text",
919
+ text: `Memory search failed: ${String(err)}`,
920
+ },
921
+ ],
922
+ details: { error: String(err) },
923
+ };
924
+ }
925
+ },
926
+ },
927
+ { name: "memory_search" },
928
+ );
929
+
930
+ api.registerTool(
931
+ {
932
+ name: "memory_store",
933
+ label: "Memory Store",
934
+ description:
935
+ "Save important information in long-term memory via Mem0. Use for preferences, facts, decisions, and anything worth remembering.",
936
+ parameters: Type.Object({
937
+ text: Type.String({ description: "Information to remember" }),
938
+ userId: Type.Optional(
939
+ Type.String({
940
+ description: "User ID to scope this memory",
941
+ }),
942
+ ),
943
+ agentId: Type.Optional(
944
+ Type.String({
945
+ description:
946
+ "Agent ID to store memory under a specific agent's namespace (e.g. \"researcher\"). Overrides userId.",
947
+ }),
948
+ ),
949
+ metadata: Type.Optional(
950
+ Type.Record(Type.String(), Type.Unknown(), {
951
+ description: "Optional metadata to attach to this memory",
952
+ }),
953
+ ),
954
+ longTerm: Type.Optional(
955
+ Type.Boolean({
956
+ description:
957
+ "Store as long-term (user-scoped) memory. Default: true. Set to false for session-scoped memory.",
958
+ }),
959
+ ),
960
+ }),
961
+ async execute(_toolCallId, params) {
962
+ const { text, userId, agentId, longTerm = true } = params as {
963
+ text: string;
964
+ userId?: string;
965
+ agentId?: string;
966
+ metadata?: Record<string, unknown>;
967
+ longTerm?: boolean;
968
+ };
969
+
970
+ try {
971
+ const uid = _resolveUserId({ agentId, userId });
972
+ const runId = !longTerm && currentSessionId ? currentSessionId : undefined;
973
+ const result = await provider.add(
974
+ [{ role: "user", content: text }],
975
+ buildAddOptions(uid, runId, currentSessionId),
976
+ );
977
+
978
+ const added =
979
+ result.results?.filter((r) => r.event === "ADD") ?? [];
980
+ const updated =
981
+ result.results?.filter((r) => r.event === "UPDATE") ?? [];
982
+
983
+ const summary = [];
984
+ if (added.length > 0)
985
+ summary.push(
986
+ `${added.length} new memor${added.length === 1 ? "y" : "ies"} added`,
987
+ );
988
+ if (updated.length > 0)
989
+ summary.push(
990
+ `${updated.length} memor${updated.length === 1 ? "y" : "ies"} updated`,
991
+ );
992
+ if (summary.length === 0)
993
+ summary.push("No new memories extracted");
994
+
995
+ return {
996
+ content: [
997
+ {
998
+ type: "text",
999
+ text: `Stored: ${summary.join(", ")}. ${result.results?.map((r) => `[${r.event}] ${r.memory}`).join("; ") ?? ""}`,
1000
+ },
1001
+ ],
1002
+ details: {
1003
+ action: "stored",
1004
+ results: result.results,
1005
+ },
1006
+ };
1007
+ } catch (err) {
1008
+ return {
1009
+ content: [
1010
+ {
1011
+ type: "text",
1012
+ text: `Memory store failed: ${String(err)}`,
1013
+ },
1014
+ ],
1015
+ details: { error: String(err) },
1016
+ };
1017
+ }
1018
+ },
1019
+ },
1020
+ { name: "memory_store" },
1021
+ );
1022
+
1023
+ api.registerTool(
1024
+ {
1025
+ name: "memory_get",
1026
+ label: "Memory Get",
1027
+ description: "Retrieve a specific memory by its ID from Mem0.",
1028
+ parameters: Type.Object({
1029
+ memoryId: Type.String({ description: "The memory ID to retrieve" }),
1030
+ }),
1031
+ async execute(_toolCallId, params) {
1032
+ const { memoryId } = params as { memoryId: string };
1033
+
1034
+ try {
1035
+ const memory = await provider.get(memoryId);
1036
+
1037
+ return {
1038
+ content: [
1039
+ {
1040
+ type: "text",
1041
+ text: `Memory ${memory.id}:\n${memory.memory}\n\nCreated: ${memory.created_at ?? "unknown"}\nUpdated: ${memory.updated_at ?? "unknown"}`,
1042
+ },
1043
+ ],
1044
+ details: { memory },
1045
+ };
1046
+ } catch (err) {
1047
+ return {
1048
+ content: [
1049
+ {
1050
+ type: "text",
1051
+ text: `Memory get failed: ${String(err)}`,
1052
+ },
1053
+ ],
1054
+ details: { error: String(err) },
1055
+ };
1056
+ }
1057
+ },
1058
+ },
1059
+ { name: "memory_get" },
1060
+ );
1061
+
1062
+ api.registerTool(
1063
+ {
1064
+ name: "memory_list",
1065
+ label: "Memory List",
1066
+ description:
1067
+ "List all stored memories for a user or agent. Use this when you want to see everything that's been remembered, rather than searching for something specific.",
1068
+ parameters: Type.Object({
1069
+ userId: Type.Optional(
1070
+ Type.String({
1071
+ description:
1072
+ "User ID to list memories for (default: configured userId)",
1073
+ }),
1074
+ ),
1075
+ agentId: Type.Optional(
1076
+ Type.String({
1077
+ description:
1078
+ "Agent ID to list memories for a specific agent (e.g. \"researcher\"). Overrides userId.",
1079
+ }),
1080
+ ),
1081
+ scope: Type.Optional(
1082
+ Type.Union([
1083
+ Type.Literal("session"),
1084
+ Type.Literal("long-term"),
1085
+ Type.Literal("all"),
1086
+ ], {
1087
+ description:
1088
+ 'Memory scope: "session" (current session only), "long-term" (user-scoped only), or "all" (both). Default: "all"',
1089
+ }),
1090
+ ),
1091
+ }),
1092
+ async execute(_toolCallId, params) {
1093
+ const { userId, agentId, scope = "all" } = params as { userId?: string; agentId?: string; scope?: "session" | "long-term" | "all" };
1094
+
1095
+ try {
1096
+ let memories: MemoryItem[] = [];
1097
+ const uid = _resolveUserId({ agentId, userId });
1098
+
1099
+ if (scope === "session") {
1100
+ if (currentSessionId) {
1101
+ memories = await provider.getAll({
1102
+ user_id: uid,
1103
+ run_id: currentSessionId,
1104
+ source: "OPENCLAW",
1105
+ });
1106
+ }
1107
+ } else if (scope === "long-term") {
1108
+ memories = await provider.getAll({ user_id: uid, source: "OPENCLAW" });
1109
+ } else {
1110
+ // "all" — combine both scopes
1111
+ const longTerm = await provider.getAll({ user_id: uid, source: "OPENCLAW" });
1112
+ let session: MemoryItem[] = [];
1113
+ if (currentSessionId) {
1114
+ session = await provider.getAll({
1115
+ user_id: uid,
1116
+ run_id: currentSessionId,
1117
+ source: "OPENCLAW",
1118
+ });
1119
+ }
1120
+ const seen = new Set(longTerm.map((r) => r.id));
1121
+ memories = [
1122
+ ...longTerm,
1123
+ ...session.filter((r) => !seen.has(r.id)),
1124
+ ];
1125
+ }
1126
+
1127
+ if (!memories || memories.length === 0) {
1128
+ return {
1129
+ content: [
1130
+ { type: "text", text: "No memories stored yet." },
1131
+ ],
1132
+ details: { count: 0 },
1133
+ };
1134
+ }
1135
+
1136
+ const text = memories
1137
+ .map(
1138
+ (r, i) =>
1139
+ `${i + 1}. ${r.memory} (id: ${r.id})`,
1140
+ )
1141
+ .join("\n");
1142
+
1143
+ const sanitized = memories.map((r) => ({
1144
+ id: r.id,
1145
+ memory: r.memory,
1146
+ categories: r.categories,
1147
+ created_at: r.created_at,
1148
+ }));
1149
+
1150
+ return {
1151
+ content: [
1152
+ {
1153
+ type: "text",
1154
+ text: `${memories.length} memories:\n\n${text}`,
1155
+ },
1156
+ ],
1157
+ details: { count: memories.length, memories: sanitized },
1158
+ };
1159
+ } catch (err) {
1160
+ return {
1161
+ content: [
1162
+ {
1163
+ type: "text",
1164
+ text: `Memory list failed: ${String(err)}`,
1165
+ },
1166
+ ],
1167
+ details: { error: String(err) },
1168
+ };
1169
+ }
1170
+ },
1171
+ },
1172
+ { name: "memory_list" },
1173
+ );
1174
+
1175
+ api.registerTool(
1176
+ {
1177
+ name: "memory_forget",
1178
+ label: "Memory Forget",
1179
+ description:
1180
+ "Delete memories from Mem0. Provide a specific memoryId to delete directly, or a query to search and delete matching memories. Supports agent-scoped deletion. GDPR-compliant.",
1181
+ parameters: Type.Object({
1182
+ query: Type.Optional(
1183
+ Type.String({
1184
+ description: "Search query to find memory to delete",
1185
+ }),
1186
+ ),
1187
+ memoryId: Type.Optional(
1188
+ Type.String({ description: "Specific memory ID to delete" }),
1189
+ ),
1190
+ agentId: Type.Optional(
1191
+ Type.String({
1192
+ description:
1193
+ "Agent ID to scope deletion to a specific agent's memories (e.g. \"researcher\").",
1194
+ }),
1195
+ ),
1196
+ }),
1197
+ async execute(_toolCallId, params) {
1198
+ const { query, memoryId, agentId } = params as {
1199
+ query?: string;
1200
+ memoryId?: string;
1201
+ agentId?: string;
1202
+ };
1203
+
1204
+ try {
1205
+ if (memoryId) {
1206
+ await provider.delete(memoryId);
1207
+ return {
1208
+ content: [
1209
+ { type: "text", text: `Memory ${memoryId} forgotten.` },
1210
+ ],
1211
+ details: { action: "deleted", id: memoryId },
1212
+ };
1213
+ }
1214
+
1215
+ if (query) {
1216
+ const uid = _resolveUserId({ agentId });
1217
+ const results = await provider.search(
1218
+ query,
1219
+ buildSearchOptions(uid, 5),
1220
+ );
1221
+
1222
+ if (!results.items.length) {
1223
+ return {
1224
+ content: [
1225
+ { type: "text", text: "No matching memories found." },
1226
+ ],
1227
+ details: { found: 0 },
1228
+ };
1229
+ }
1230
+
1231
+ // If single high-confidence match, delete directly
1232
+ if (
1233
+ results.items.length === 1 ||
1234
+ (results.items[0].score ?? 0) > 0.9
1235
+ ) {
1236
+ await provider.delete(results.items[0].id);
1237
+ return {
1238
+ content: [
1239
+ {
1240
+ type: "text",
1241
+ text: `Forgotten: "${results.items[0].memory}"`,
1242
+ },
1243
+ ],
1244
+ details: { action: "deleted", id: results.items[0].id },
1245
+ };
1246
+ }
1247
+
1248
+ const list = results.items
1249
+ .map(
1250
+ (r) =>
1251
+ `- [${r.id}] ${r.memory.slice(0, 80)}${r.memory.length > 80 ? "..." : ""} (score: ${((r.score ?? 0) * 100).toFixed(0)}%)`,
1252
+ )
1253
+ .join("\n");
1254
+
1255
+ const candidates = results.items.map((r) => ({
1256
+ id: r.id,
1257
+ memory: r.memory,
1258
+ score: r.score,
1259
+ }));
1260
+
1261
+ return {
1262
+ content: [
1263
+ {
1264
+ type: "text",
1265
+ text: `Found ${results.items.length} candidates. Specify memoryId to delete:\n${list}`,
1266
+ },
1267
+ ],
1268
+ details: { action: "candidates", candidates },
1269
+ };
1270
+ }
1271
+
1272
+ return {
1273
+ content: [
1274
+ { type: "text", text: "Provide a query or memoryId." },
1275
+ ],
1276
+ details: { error: "missing_param" },
1277
+ };
1278
+ } catch (err) {
1279
+ return {
1280
+ content: [
1281
+ {
1282
+ type: "text",
1283
+ text: `Memory forget failed: ${String(err)}`,
1284
+ },
1285
+ ],
1286
+ details: { error: String(err) },
1287
+ };
1288
+ }
1289
+ },
1290
+ },
1291
+ { name: "memory_forget" },
1292
+ );
1293
+
1294
+ // ========================================================================
1295
+ // CLI Commands
1296
+ // ========================================================================
1297
+
1298
+ api.registerCli(
1299
+ ({ program }) => {
1300
+ const mem0 = program
1301
+ .command("mem0")
1302
+ .description("Mem0 memory plugin commands");
1303
+
1304
+ mem0
1305
+ .command("search")
1306
+ .description("Search memories in Mem0")
1307
+ .argument("<query>", "Search query")
1308
+ .option("--limit <n>", "Max results", String(cfg.topK))
1309
+ .option("--scope <scope>", 'Memory scope: "session", "long-term", or "all"', "all")
1310
+ .option("--agent <agentId>", "Search a specific agent's memory namespace")
1311
+ .action(async (query: string, opts: { limit: string; scope: string; agent?: string }) => {
1312
+ try {
1313
+ const limit = parseInt(opts.limit, 10);
1314
+ const scope = opts.scope as "session" | "long-term" | "all";
1315
+ const uid = opts.agent ? _agentUserId(opts.agent) : _effectiveUserId(currentSessionId);
1316
+
1317
+ let allResults: MemoryItem[] = [];
1318
+ let allRelations: unknown[] = [];
1319
+
1320
+ if (scope === "session" || scope === "all") {
1321
+ if (currentSessionId) {
1322
+ const sessionResults = await provider.search(
1323
+ query,
1324
+ buildSearchOptions(uid, limit, currentSessionId),
1325
+ );
1326
+ if (sessionResults.items.length) {
1327
+ allResults.push(...sessionResults.items.map((r) => ({ ...r, _scope: "session" as const })));
1328
+ }
1329
+ if (sessionResults.relations?.length) {
1330
+ allRelations.push(...sessionResults.relations);
1331
+ }
1332
+ } else if (scope === "session") {
1333
+ console.log("No active session ID available for session-scoped search.");
1334
+ return;
1335
+ }
1336
+ }
1337
+
1338
+ if (scope === "long-term" || scope === "all") {
1339
+ const longTermResults = await provider.search(
1340
+ query,
1341
+ buildSearchOptions(uid, limit),
1342
+ );
1343
+ if (longTermResults.items.length) {
1344
+ allResults.push(...longTermResults.items.map((r) => ({ ...r, _scope: "long-term" as const })));
1345
+ }
1346
+ if (longTermResults.relations?.length) {
1347
+ allRelations.push(...longTermResults.relations);
1348
+ }
1349
+ }
1350
+
1351
+ // Deduplicate by ID when searching "all"
1352
+ if (scope === "all") {
1353
+ const seen = new Set<string>();
1354
+ allResults = allResults.filter((r) => {
1355
+ if (seen.has(r.id)) return false;
1356
+ seen.add(r.id);
1357
+ return true;
1358
+ });
1359
+ }
1360
+
1361
+ const relationLines = allRelations
1362
+ .map(formatRelation)
1363
+ .filter((line): line is string => Boolean(line));
1364
+
1365
+ if (!allResults.length && relationLines.length === 0) {
1366
+ console.log("No memories found.");
1367
+ return;
1368
+ }
1369
+
1370
+ const output = {
1371
+ memories: allResults.map((r) => ({
1372
+ id: r.id,
1373
+ memory: r.memory,
1374
+ score: r.score,
1375
+ scope: (r as any)._scope,
1376
+ categories: r.categories,
1377
+ created_at: r.created_at,
1378
+ })),
1379
+ relations: relationLines,
1380
+ };
1381
+ console.log(JSON.stringify(output, null, 2));
1382
+ } catch (err) {
1383
+ console.error(`Search failed: ${String(err)}`);
1384
+ }
1385
+ });
1386
+
1387
+ mem0
1388
+ .command("stats")
1389
+ .description("Show memory statistics from Mem0")
1390
+ .option("--agent <agentId>", "Show stats for a specific agent")
1391
+ .action(async (opts: { agent?: string }) => {
1392
+ try {
1393
+ const uid = opts.agent ? _agentUserId(opts.agent) : cfg.userId;
1394
+ const memories = await provider.getAll({
1395
+ user_id: uid,
1396
+ source: "OPENCLAW",
1397
+ });
1398
+ console.log(`Mode: ${cfg.mode}`);
1399
+ console.log(`User: ${uid}${opts.agent ? ` (agent: ${opts.agent})` : ""}`);
1400
+ console.log(
1401
+ `Total memories: ${Array.isArray(memories) ? memories.length : "unknown"}`,
1402
+ );
1403
+ console.log(`Graph enabled: ${cfg.enableGraph}`);
1404
+ console.log(
1405
+ `Auto-recall: ${cfg.autoRecall}, Auto-capture: ${cfg.autoCapture}`,
1406
+ );
1407
+ } catch (err) {
1408
+ console.error(`Stats failed: ${String(err)}`);
1409
+ }
1410
+ });
1411
+ },
1412
+ { commands: ["mem0"] },
1413
+ );
1414
+
1415
+ // ========================================================================
1416
+ // Lifecycle Hooks
1417
+ // ========================================================================
1418
+
1419
+ // Auto-recall: inject relevant memories before agent starts
1420
+ if (cfg.autoRecall) {
1421
+ api.on("before_agent_start", async (event, ctx) => {
1422
+ if (!event.prompt || event.prompt.length < 5) return;
1423
+
1424
+ // Track session ID
1425
+ const sessionId = (ctx as any)?.sessionKey ?? undefined;
1426
+ if (sessionId) currentSessionId = sessionId;
1427
+
1428
+ try {
1429
+ // Search long-term memories (user-scoped, isolated per agent)
1430
+ const longTermResults = await provider.search(
1431
+ event.prompt,
1432
+ buildSearchOptions(undefined, undefined, undefined, sessionId),
1433
+ );
1434
+
1435
+ // Search session memories (session-scoped) if we have a session ID
1436
+ let sessionResults: SearchResult = { items: [] };
1437
+ if (currentSessionId) {
1438
+ sessionResults = await provider.search(
1439
+ event.prompt,
1440
+ buildSearchOptions(undefined, undefined, currentSessionId, sessionId),
1441
+ );
1442
+ }
1443
+
1444
+ // Deduplicate session results against long-term
1445
+ const longTermIds = new Set(longTermResults.items.map((r) => r.id));
1446
+ const uniqueSessionResults = sessionResults.items.filter(
1447
+ (r) => !longTermIds.has(r.id),
1448
+ );
1449
+
1450
+ const graphRelations = [
1451
+ ...(longTermResults.relations ?? []),
1452
+ ...(sessionResults.relations ?? []),
1453
+ ]
1454
+ .map(formatRelation)
1455
+ .filter((line): line is string => Boolean(line));
1456
+
1457
+ if (
1458
+ longTermResults.items.length === 0 &&
1459
+ uniqueSessionResults.length === 0 &&
1460
+ graphRelations.length === 0
1461
+ ) return;
1462
+
1463
+ // Build context with clear labels
1464
+ let memoryContext = "";
1465
+ if (longTermResults.items.length > 0) {
1466
+ memoryContext += longTermResults.items
1467
+ .map(
1468
+ (r) =>
1469
+ `- ${r.memory}${r.categories?.length ? ` [${r.categories.join(", ")}]` : ""}`,
1470
+ )
1471
+ .join("\n");
1472
+ }
1473
+ if (uniqueSessionResults.length > 0) {
1474
+ if (memoryContext) memoryContext += "\n";
1475
+ memoryContext += "\nSession memories:\n";
1476
+ memoryContext += uniqueSessionResults
1477
+ .map((r) => `- ${r.memory}`)
1478
+ .join("\n");
1479
+ }
1480
+ if (graphRelations.length > 0) {
1481
+ if (memoryContext) memoryContext += "\n";
1482
+ memoryContext += "\nGraph relations:\n";
1483
+ memoryContext += graphRelations.map((line) => `- ${line}`).join("\n");
1484
+ }
1485
+
1486
+ const totalCount =
1487
+ longTermResults.items.length +
1488
+ uniqueSessionResults.length +
1489
+ graphRelations.length;
1490
+ api.logger.info(
1491
+ `openclaw-mem0: injecting ${totalCount} memory signals into context (${longTermResults.items.length} long-term, ${uniqueSessionResults.length} session, ${graphRelations.length} graph relations)`,
1492
+ );
1493
+
1494
+ return {
1495
+ prependContext: `<relevant-memories>\nThe following memories may be relevant to this conversation:\n${memoryContext}\n</relevant-memories>`,
1496
+ };
1497
+ } catch (err) {
1498
+ api.logger.warn(`openclaw-mem0: recall failed: ${String(err)}`);
1499
+ }
1500
+ });
1501
+ }
1502
+
1503
+ // Auto-capture: store conversation context after agent ends
1504
+ if (cfg.autoCapture) {
1505
+ api.on("agent_end", async (event, ctx) => {
1506
+ if (!event.success || !event.messages || event.messages.length === 0) {
1507
+ return;
1508
+ }
1509
+
1510
+ // Track session ID
1511
+ const sessionId = (ctx as any)?.sessionKey ?? undefined;
1512
+ if (sessionId) currentSessionId = sessionId;
1513
+
1514
+ try {
1515
+ // Extract messages, limiting to last 10
1516
+ const recentMessages = event.messages.slice(-10);
1517
+ const formattedMessages: Array<{
1518
+ role: string;
1519
+ content: string;
1520
+ }> = [];
1521
+
1522
+ for (const msg of recentMessages) {
1523
+ if (!msg || typeof msg !== "object") continue;
1524
+ const msgObj = msg as Record<string, unknown>;
1525
+
1526
+ const role = msgObj.role;
1527
+ if (role !== "user" && role !== "assistant") continue;
1528
+
1529
+ let textContent = "";
1530
+ const content = msgObj.content;
1531
+
1532
+ if (typeof content === "string") {
1533
+ textContent = content;
1534
+ } else if (Array.isArray(content)) {
1535
+ for (const block of content) {
1536
+ if (
1537
+ block &&
1538
+ typeof block === "object" &&
1539
+ "text" in block &&
1540
+ typeof (block as Record<string, unknown>).text === "string"
1541
+ ) {
1542
+ textContent +=
1543
+ (textContent ? "\n" : "") +
1544
+ ((block as Record<string, unknown>).text as string);
1545
+ }
1546
+ }
1547
+ }
1548
+
1549
+ if (!textContent) continue;
1550
+ // Strip injected memory context, keep the actual user text
1551
+ if (textContent.includes("<relevant-memories>")) {
1552
+ textContent = textContent.replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>\s*/g, "").trim();
1553
+ if (!textContent) continue;
1554
+ }
1555
+
1556
+ formattedMessages.push({
1557
+ role: role as string,
1558
+ content: textContent,
1559
+ });
1560
+ }
1561
+
1562
+ if (formattedMessages.length === 0) return;
1563
+
1564
+ const addOpts = buildAddOptions(undefined, currentSessionId, sessionId);
1565
+ const result = await provider.add(
1566
+ formattedMessages,
1567
+ addOpts,
1568
+ );
1569
+
1570
+ const capturedCount = result.results?.length ?? 0;
1571
+ if (capturedCount > 0) {
1572
+ api.logger.info(
1573
+ `openclaw-mem0: auto-captured ${capturedCount} memories`,
1574
+ );
1575
+ }
1576
+ } catch (err) {
1577
+ api.logger.warn(`openclaw-mem0: capture failed: ${String(err)}`);
1578
+ }
1579
+ });
1580
+ }
1581
+
1582
+ // ========================================================================
1583
+ // Service
1584
+ // ========================================================================
1585
+
1586
+ api.registerService({
1587
+ id: "openclaw-mem0",
1588
+ start: () => {
1589
+ api.logger.info(
1590
+ `openclaw-mem0: initialized (mode: ${cfg.mode}, user: ${cfg.userId}, autoRecall: ${cfg.autoRecall}, autoCapture: ${cfg.autoCapture})`,
1591
+ );
1592
+ },
1593
+ stop: () => {
1594
+ api.logger.info("openclaw-mem0: stopped");
1595
+ },
1596
+ });
1597
+ },
1598
+ };
1599
+
1600
+ export default memoryPlugin;