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