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