forked from ob-labs/memory-powermem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
470 lines (431 loc) · 16.8 KB
/
Copy pathindex.ts
File metadata and controls
470 lines (431 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/**
* OpenClaw Memory (PowerMem) Plugin
*
* Long-term memory via PowerMem: intelligent extraction, Ebbinghaus
* forgetting curve, multi-agent isolation. Supports two backends:
* - HTTP: requires a running PowerMem server (e.g. powermem-server --port 8000).
* - CLI: runs pmem locally (no server); set mode to "cli" and optionally envFile/pmemPath.
*/
import { Type } from "@sinclair/typebox";
import type {
OpenClawPluginApi,
OpenClawPluginCliContext,
} from "openclaw/plugin-sdk/memory-core";
import type { OpenClawPluginServiceContext } from "openclaw/plugin-sdk";
import {
powerMemConfigSchema,
resolveUserId,
resolveAgentId,
type PowerMemConfig,
} from "./config.js";
import { PowerMemClient } from "./client.js";
import { PowerMemCLIClient } from "./client-cli.js";
// ============================================================================
// Plugin Definition
// ============================================================================
const memoryPlugin = {
id: "memory-powermem",
name: "Memory (PowerMem)",
description:
"PowerMem-backed long-term memory (intelligent extraction, forgetting curve). Backend: HTTP server or local CLI (pmem).",
kind: "memory" as const,
configSchema: powerMemConfigSchema,
register(api: OpenClawPluginApi) {
const cfg = powerMemConfigSchema.parse(api.pluginConfig) as PowerMemConfig;
const userId = resolveUserId(cfg);
const agentId = resolveAgentId(cfg);
const client =
cfg.mode === "cli"
? PowerMemCLIClient.fromConfig(cfg, userId, agentId)
: PowerMemClient.fromConfig(cfg, userId, agentId);
const modeLabel = cfg.mode === "cli" ? `cli (${cfg.pmemPath ?? "pmem"})` : cfg.baseUrl;
api.logger.info(
`memory-powermem: plugin registered (mode: ${cfg.mode}, ${modeLabel}, user: ${userId}, agent: ${agentId})`,
);
// ========================================================================
// Tools
// ========================================================================
api.registerTool(
{
name: "memory_recall",
label: "Memory Recall",
description:
"Search through long-term memories. Use when you need context about user preferences, past decisions, or previously discussed topics.",
parameters: Type.Object({
query: Type.String({ description: "Search query" }),
limit: Type.Optional(
Type.Number({ description: "Max results (default: plugin recallLimit)" }),
),
scoreThreshold: Type.Optional(
Type.Number({ description: "Min score 0–1 to include (default: plugin recallScoreThreshold)" }),
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
const limit =
typeof (params as { limit?: number }).limit === "number"
? Math.max(1, Math.min(100, Math.floor((params as { limit: number }).limit)))
: cfg.recallLimit ?? 5;
const scoreThreshold =
typeof (params as { scoreThreshold?: number }).scoreThreshold === "number"
? Math.max(0, Math.min(1, (params as { scoreThreshold: number }).scoreThreshold))
: (cfg.recallScoreThreshold ?? 0);
const query = String((params as { query?: string }).query ?? "");
try {
const requestLimit = Math.min(100, Math.max(limit * 2, limit + 10));
const raw = await client.search(query, requestLimit);
const results = raw
.filter((r) => (r.score ?? 0) >= scoreThreshold)
.slice(0, limit);
if (results.length === 0) {
return {
content: [{ type: "text", text: "No relevant memories found." }],
details: { count: 0 },
};
}
const text = results
.map(
(r, i) =>
`${i + 1}. ${r.content} (${((r.score ?? 0) * 100).toFixed(0)}%)`,
)
.join("\n");
const sanitizedResults = results.map((r) => ({
id: String(r.memory_id),
text: r.content,
score: r.score,
}));
return {
content: [
{ type: "text", text: `Found ${results.length} memories:\n\n${text}` },
],
details: { count: results.length, memories: sanitizedResults },
};
} catch (err) {
api.logger.warn(`memory-powermem: recall failed: ${String(err)}`);
return {
content: [
{
type: "text",
text: `Memory search failed: ${err instanceof Error ? err.message : String(err)}`,
},
],
details: { error: String(err) },
};
}
},
},
{ name: "memory_recall" },
);
api.registerTool(
{
name: "memory_store",
label: "Memory Store",
description:
"Save important information in long-term memory. Use for preferences, facts, decisions.",
parameters: Type.Object({
text: Type.String({ description: "Information to remember" }),
importance: Type.Optional(
Type.Number({ description: "Importance 0-1 (default: 0.7)" }),
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
const { text, importance = 0.7 } = params as {
text: string;
importance?: number;
};
try {
const created = await client.add(text, {
infer: cfg.inferOnAdd,
metadata: { importance },
});
if (created.length === 0) {
return {
content: [{ type: "text", text: "Stored (no inferred items)." }],
details: { action: "created" },
};
}
const summary =
created.length === 1
? created[0].content.slice(0, 80)
: `${created.length} items stored`;
return {
content: [
{ type: "text", text: `Stored: ${summary}${summary.length >= 80 ? "..." : ""}` },
],
details: {
action: "created",
count: created.length,
ids: created.map((c) => String(c.memory_id)),
},
};
} catch (err) {
api.logger.warn(`memory-powermem: store failed: ${String(err)}`);
return {
content: [
{
type: "text",
text: `Failed to store memory: ${err instanceof Error ? err.message : String(err)}`,
},
],
details: { error: String(err) },
};
}
},
},
{ name: "memory_store" },
);
api.registerTool(
{
name: "memory_forget",
label: "Memory Forget",
description: "Delete specific memories. GDPR-compliant.",
parameters: Type.Object({
query: Type.Optional(Type.String({ description: "Search to find memory" })),
memoryId: Type.Optional(Type.String({ description: "Specific memory ID" })),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
const { query, memoryId } = params as { query?: string; memoryId?: string };
try {
if (memoryId) {
await client.delete(memoryId);
return {
content: [{ type: "text", text: `Memory ${memoryId} forgotten.` }],
details: { action: "deleted", id: memoryId },
};
}
if (query) {
const results = await client.search(query, 5);
if (results.length === 0) {
return {
content: [{ type: "text", text: "No matching memories found." }],
details: { found: 0 },
};
}
if (results.length === 1 && (results[0].score ?? 0) > 0.9) {
await client.delete(results[0].memory_id);
return {
content: [
{
type: "text",
text: `Forgotten: "${results[0].content.slice(0, 60)}..."`,
},
],
details: { action: "deleted", id: String(results[0].memory_id) },
};
}
const list = results
.map(
(r) =>
`- [${String(r.memory_id).slice(0, 8)}] ${r.content.slice(0, 60)}...`,
)
.join("\n");
return {
content: [
{
type: "text",
text: `Found ${results.length} candidates. Specify memoryId:\n${list}`,
},
],
details: {
action: "candidates",
candidates: results.map((r) => ({
id: String(r.memory_id),
text: r.content,
score: r.score,
})),
},
};
}
return {
content: [{ type: "text", text: "Provide query or memoryId." }],
details: { error: "missing_param" },
};
} catch (err) {
api.logger.warn(`memory-powermem: forget failed: ${String(err)}`);
return {
content: [
{
type: "text",
text: `Failed to forget: ${err instanceof Error ? err.message : String(err)}`,
},
],
details: { error: String(err) },
};
}
},
},
{ name: "memory_forget" },
);
// ========================================================================
// CLI Commands
// ========================================================================
api.registerCli(
({ program }: OpenClawPluginCliContext) => {
const ltm = program
.command("ltm")
.description("PowerMem long-term memory plugin commands");
ltm
.command("search")
.description("Search memories")
.argument("<query>", "Search query")
.option("--limit <n>", "Max results", "5")
.action(async (...args: unknown[]) => {
const query = String(args[0] ?? "");
const opts = (args[1] ?? {}) as { limit?: string };
const limit = parseInt(opts.limit ?? "5", 10);
const results = await client.search(query, limit);
console.log(JSON.stringify(results, null, 2));
});
ltm
.command("health")
.description("Check PowerMem server health")
.action(async () => {
try {
const h = await client.health();
console.log("PowerMem:", h.status);
} catch (err) {
console.error("PowerMem health check failed:", err);
process.exitCode = 1;
}
});
ltm
.command("add")
.description("Manually add a memory (for testing or one-off storage)")
.argument("<text>", "Content to store")
.action(async (...args: unknown[]) => {
const text = String(args[0] ?? "");
try {
const created = await client.add(text.trim(), { infer: cfg.inferOnAdd });
if (created.length === 0) {
console.log("Stored (no inferred items).");
} else {
console.log(`Stored ${created.length} item(s):`, created.map((c) => c.memory_id));
}
} catch (err) {
console.error("PowerMem add failed:", err);
process.exitCode = 1;
}
});
},
{ commands: ["ltm"] },
);
// ========================================================================
// Lifecycle Hooks
// ========================================================================
if (cfg.autoRecall) {
api.on("before_agent_start", async (event: unknown) => {
const e = event as { prompt: string; messages?: unknown[] };
if (!e.prompt || e.prompt.length < 5) return;
const recallLimit = Math.max(1, Math.min(100, cfg.recallLimit ?? 5));
const scoreThreshold = Math.max(0, Math.min(1, cfg.recallScoreThreshold ?? 0));
try {
const requestLimit = Math.min(100, Math.max(recallLimit * 2, recallLimit + 10));
const raw = await client.search(e.prompt, requestLimit);
const results = raw
.filter((r) => (r.score ?? 0) >= scoreThreshold)
.slice(0, recallLimit);
if (results.length === 0) return;
const memoryContext = results.map((r) => `- ${r.content}`).join("\n");
api.logger.info(
`memory-powermem: injecting ${results.length} memories into context`,
);
return {
prependContext: `<relevant-memories>\nThe following memories may be relevant to this conversation:\n${memoryContext}\n</relevant-memories>`,
};
} catch (err) {
api.logger.warn(`memory-powermem: recall failed: ${String(err)}`);
}
});
}
if (cfg.autoCapture) {
api.on("agent_end", async (event: unknown) => {
const e = event as { messages: unknown[]; success: boolean; error?: string };
if (!e.success || !e.messages || e.messages.length === 0) {
return;
}
try {
const texts: string[] = [];
for (const msg of e.messages) {
if (!msg || typeof msg !== "object") continue;
const msgObj = msg as Record<string, unknown>;
const role = msgObj.role;
if (role !== "user" && role !== "assistant") continue;
const content = msgObj.content;
if (typeof content === "string") {
texts.push(content);
continue;
}
if (Array.isArray(content)) {
for (const block of content) {
if (
block &&
typeof block === "object" &&
"type" in block &&
(block as Record<string, unknown>).type === "text" &&
"text" in block &&
typeof (block as Record<string, unknown>).text === "string"
) {
texts.push((block as Record<string, unknown>).text as string);
}
}
}
}
const MIN_LEN = 10;
const MAX_CHUNK_LEN = 6000;
const MAX_CHUNKS_PER_SESSION = 3;
const sanitized = texts
.filter((t): t is string => typeof t === "string" && t.trim().length >= MIN_LEN)
.map((t) => t.trim())
.filter(
(t) =>
!t.includes("<relevant-memories>") &&
!(t.startsWith("<") && t.includes("</")),
);
if (sanitized.length === 0) return;
const combined = sanitized.join("\n\n");
const chunks: string[] = [];
for (let i = 0; i < combined.length; i += MAX_CHUNK_LEN) {
if (chunks.length >= MAX_CHUNKS_PER_SESSION) break;
chunks.push(combined.slice(i, i + MAX_CHUNK_LEN));
}
let stored = 0;
for (const chunk of chunks) {
const created = await client.add(chunk, { infer: cfg.inferOnAdd });
stored += created.length;
}
if (stored > 0) {
api.logger.info(`memory-powermem: auto-captured ${stored} memories from conversation`);
}
} catch (err) {
api.logger.warn(`memory-powermem: capture failed: ${String(err)}`);
}
});
}
// ========================================================================
// Service
// ========================================================================
api.registerService({
id: "memory-powermem",
start: async (_ctx: OpenClawPluginServiceContext) => {
try {
const h = await client.health();
const where = cfg.mode === "cli" ? `cli ${cfg.pmemPath ?? "pmem"}` : cfg.baseUrl;
api.logger.info(
`memory-powermem: initialized (${where}, health: ${h.status})`,
);
} catch (err) {
const hint =
cfg.mode === "cli"
? "is pmem on PATH and POWERMEM_ENV_FILE or --env-file set?"
: "is PowerMem server running?";
api.logger.warn(
`memory-powermem: health check failed (${hint}): ${String(err)}`,
);
}
},
stop: (_ctx: OpenClawPluginServiceContext) => {
api.logger.info("memory-powermem: stopped");
},
});
},
};
export default memoryPlugin;