@jokab1074/rememberme 0.0.0-stage → 0.22.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/ARCHITECTURE.md +787 -0
- package/LICENSE +201 -0
- package/README.en.md +441 -0
- package/README.md +459 -2
- package/dist/mcp/index.js +37287 -0
- package/package.json +67 -4
- package/server.json +38 -0
- package/settings.json.example +7 -0
- package/src/bigfive.ts +163 -0
- package/src/bootstrap.ts +104 -0
- package/src/classify.ts +186 -0
- package/src/compact.ts +225 -0
- package/src/context-file.ts +305 -0
- package/src/embedded-proactive.ts +214 -0
- package/src/evolution/access-tracker.ts +118 -0
- package/src/evolution/curator.ts +220 -0
- package/src/evolution/lifecycle.ts +175 -0
- package/src/feedback-detector.ts +177 -0
- package/src/i18n.ts +89 -0
- package/src/index.ts +1479 -0
- package/src/loop.ts +396 -0
- package/src/mcp/build.ts +64 -0
- package/src/mcp/config.ts +108 -0
- package/src/mcp/index.ts +66 -0
- package/src/mcp/instructions.ts +43 -0
- package/src/mcp/logger.ts +32 -0
- package/src/mcp/provider.ts +142 -0
- package/src/mcp/server.ts +52 -0
- package/src/mcp/tools/memory.ts +126 -0
- package/src/mcp/tools/profile.ts +67 -0
- package/src/mcp/tools/record-turn.ts +239 -0
- package/src/memory-extract.ts +390 -0
- package/src/memory.ts +790 -0
- package/src/persona-init.ts +153 -0
- package/src/persona-learner.ts +349 -0
- package/src/proactive.ts +557 -0
- package/src/profile.ts +1008 -0
- package/src/prompt.ts +288 -0
- package/src/provider.ts +292 -0
- package/src/reflection.ts +552 -0
- package/src/sessions.ts +140 -0
- package/src/timeline.ts +208 -0
- package/src/utils.ts +91 -0
- package/src/web.ts +624 -0
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
// src/memory-extract.ts
|
|
2
|
+
// 从对话中抽取值得记忆的事实(情绪 + 事件 双主类)。
|
|
3
|
+
//
|
|
4
|
+
// 设计原则(来自用户反馈):
|
|
5
|
+
// 1. 模拟朋友面对用户时的思维方式
|
|
6
|
+
// 2. 只识别两类:emotion(≥2 次证据的情绪模式)+ event(有情感意义的生活事件)
|
|
7
|
+
// 3. 不写数字记忆("今天 mood 0.7")
|
|
8
|
+
// 4. 不写日常活动("今天吃了碗面")
|
|
9
|
+
// 5. 两类互相印证:保存时自动 link
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
scanMemory,
|
|
13
|
+
writeMemoryFile,
|
|
14
|
+
appendIndexEntry,
|
|
15
|
+
appendToMemoryFile,
|
|
16
|
+
findSimilarMemory,
|
|
17
|
+
formatManifest,
|
|
18
|
+
findRelatedEmotions,
|
|
19
|
+
findRelatedEvents,
|
|
20
|
+
type MemoryFile,
|
|
21
|
+
type MemoryType,
|
|
22
|
+
type AnyMemoryCandidate,
|
|
23
|
+
type EmotionMemoryFields,
|
|
24
|
+
type EventMemoryFields,
|
|
25
|
+
} from "./memory.ts";
|
|
26
|
+
import type { ModelProvider } from "./provider.ts";
|
|
27
|
+
|
|
28
|
+
// =====================================================================
|
|
29
|
+
// LLM 抽取 prompt
|
|
30
|
+
// =====================================================================
|
|
31
|
+
|
|
32
|
+
const EXTRACT_SYSTEM_PROMPT = `你是情感陪伴对话的记忆抽取助手。下面是一段对话历史。
|
|
33
|
+
|
|
34
|
+
**核心原则**:模拟朋友面对用户时的思维方式。朋友不会机械地记录每句话,但会记住那些改变理解的瞬间。
|
|
35
|
+
|
|
36
|
+
**只识别两类值得长期记忆的内容**:
|
|
37
|
+
|
|
38
|
+
1. **情绪模式 (emotion)** —— 反复出现的情绪反应
|
|
39
|
+
- 必须有 **≥2 次证据**(不同对话、不同时间)
|
|
40
|
+
- 例:用户每次提到工作 deadline 都焦虑,连续 3 次对话观察到
|
|
41
|
+
- **不写**:单次的"今天心情不好"
|
|
42
|
+
- **不写**:纯数字("今天 mood 0.7")
|
|
43
|
+
|
|
44
|
+
2. **生活事件 (event)** —— 对用户有情感意义的事件
|
|
45
|
+
- 例:亲人去世、拿到 offer、和家人吵架、重大健康问题
|
|
46
|
+
- **不写**:日常活动("今天吃了什么"、"今天开了个会")
|
|
47
|
+
- **不写**:工作事务(除非影响情感)
|
|
48
|
+
|
|
49
|
+
两类互相印证:事件解释情绪,情绪模式暗示未说出口的事件。
|
|
50
|
+
|
|
51
|
+
**严格按 JSON 数组输出**(没有就输出 []):
|
|
52
|
+
|
|
53
|
+
情绪模式条目:
|
|
54
|
+
{
|
|
55
|
+
"type": "emotion",
|
|
56
|
+
"name": "kebab-case slug(如 deadline-anxiety-spike)",
|
|
57
|
+
"description": "一句话模式描述",
|
|
58
|
+
"trigger": "触发条件",
|
|
59
|
+
"manifestation": "表现(情绪类型 + 强度描述 + 行为反应)",
|
|
60
|
+
"evidence": ["证据1", "证据2", ...] // 必须 ≥2 条
|
|
61
|
+
"confidence": 0.0-1.0
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
事件条目:
|
|
65
|
+
{
|
|
66
|
+
"type": "event",
|
|
67
|
+
"name": "kebab-case slug(如 cat-passed-away)",
|
|
68
|
+
"description": "一句话事件",
|
|
69
|
+
"occurred_at": "YYYY-MM-DD 或 '约 3 天前' 等",
|
|
70
|
+
"emotional_impact": "对用户的情感影响",
|
|
71
|
+
"significance": "high | medium | low",
|
|
72
|
+
"confidence": 0.0-1.0
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
要求:
|
|
76
|
+
1. **宁缺毋滥**:没观察到就不输出
|
|
77
|
+
2. **emotion 必须有 ≥2 条 evidence**,否则不输出
|
|
78
|
+
3. **event 要有情感意义**,日常活动不算
|
|
79
|
+
4. **不写数字记忆**:不输出"mood 0.7"
|
|
80
|
+
5. **保留用户原话片段**(≤30 字)作为 evidence
|
|
81
|
+
6. 严格 JSON 输出,不要 Markdown 代码块
|
|
82
|
+
|
|
83
|
+
对话如下:
|
|
84
|
+
|
|
85
|
+
{conversation}
|
|
86
|
+
|
|
87
|
+
已有记忆(用来去重):
|
|
88
|
+
{manifest}`;
|
|
89
|
+
|
|
90
|
+
function buildConversationText(
|
|
91
|
+
messages: { role: string; content: string }[],
|
|
92
|
+
maxMessages = 12,
|
|
93
|
+
): string {
|
|
94
|
+
return messages
|
|
95
|
+
.slice(-maxMessages)
|
|
96
|
+
.map((m, i) => `${i + 1}. [${m.role}] ${m.content}`)
|
|
97
|
+
.join("\n\n");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// =====================================================================
|
|
101
|
+
// 抽取
|
|
102
|
+
// =====================================================================
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 从对话中识别候选记忆(emotion / event)。
|
|
106
|
+
* 失败容错:返回空数组。
|
|
107
|
+
*/
|
|
108
|
+
export async function extractMemoryCandidates(
|
|
109
|
+
provider: ModelProvider,
|
|
110
|
+
recentMessages: { role: string; content: string }[],
|
|
111
|
+
existingFiles: MemoryFile[] = [],
|
|
112
|
+
): Promise<AnyMemoryCandidate[]> {
|
|
113
|
+
if (recentMessages.length === 0) return [];
|
|
114
|
+
|
|
115
|
+
const conversation = buildConversationText(recentMessages);
|
|
116
|
+
const manifest = formatManifest(existingFiles);
|
|
117
|
+
const prompt = EXTRACT_SYSTEM_PROMPT
|
|
118
|
+
.replace("{conversation}", conversation)
|
|
119
|
+
.replace("{manifest}", manifest || "(暂无)");
|
|
120
|
+
|
|
121
|
+
let raw: string;
|
|
122
|
+
try {
|
|
123
|
+
raw = await provider.complete({
|
|
124
|
+
model: provider.model,
|
|
125
|
+
params: {
|
|
126
|
+
system: "你是结构化信息抽取助手,严格输出 JSON 数组。",
|
|
127
|
+
messages: [{ role: "user", content: prompt }],
|
|
128
|
+
maxTokens: 1500,
|
|
129
|
+
temperature: 0.2,
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const cleaned = raw
|
|
137
|
+
.trim()
|
|
138
|
+
.replace(/^```(?:json)?\n?/, "")
|
|
139
|
+
.replace(/\n?```$/, "");
|
|
140
|
+
|
|
141
|
+
let parsed: unknown;
|
|
142
|
+
try {
|
|
143
|
+
parsed = JSON.parse(cleaned);
|
|
144
|
+
} catch {
|
|
145
|
+
return [];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!Array.isArray(parsed)) return [];
|
|
149
|
+
|
|
150
|
+
const valid: AnyMemoryCandidate[] = [];
|
|
151
|
+
for (const item of parsed) {
|
|
152
|
+
if (!item || typeof item !== "object") continue;
|
|
153
|
+
const c = item as Record<string, unknown>;
|
|
154
|
+
|
|
155
|
+
const type = c.type as string;
|
|
156
|
+
if (type !== "emotion" && type !== "event") continue;
|
|
157
|
+
|
|
158
|
+
const name = String(c.name ?? "").trim();
|
|
159
|
+
const description = String(c.description ?? "").trim();
|
|
160
|
+
const confidence = Number(c.confidence ?? 0);
|
|
161
|
+
|
|
162
|
+
if (!name || !description) continue;
|
|
163
|
+
if (!Number.isFinite(confidence) || confidence < 0.5) continue;
|
|
164
|
+
if (!/^[a-z0-9_-]{2,40}$/i.test(name)) continue;
|
|
165
|
+
|
|
166
|
+
if (type === "emotion") {
|
|
167
|
+
const fields: EmotionMemoryFields = {
|
|
168
|
+
trigger: String(c.trigger ?? "").trim(),
|
|
169
|
+
manifestation: String(c.manifestation ?? "").trim(),
|
|
170
|
+
evidence: Array.isArray(c.evidence)
|
|
171
|
+
? c.evidence.map((e) => String(e).trim()).filter(Boolean)
|
|
172
|
+
: [],
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// 关键校验:emotion 必须有 ≥2 条 evidence
|
|
176
|
+
if (fields.evidence!.length < 2) continue;
|
|
177
|
+
if (!fields.trigger || !fields.manifestation) continue;
|
|
178
|
+
|
|
179
|
+
valid.push({
|
|
180
|
+
type: "emotion",
|
|
181
|
+
name,
|
|
182
|
+
description: description.slice(0, 120),
|
|
183
|
+
body: String(c.body ?? formatEmotionBody(fields, description)).slice(0, 2000),
|
|
184
|
+
confidence: Math.max(0, Math.min(1, confidence)),
|
|
185
|
+
fields,
|
|
186
|
+
});
|
|
187
|
+
} else {
|
|
188
|
+
// event
|
|
189
|
+
const fields: EventMemoryFields = {
|
|
190
|
+
occurred_at: String(c.occurred_at ?? "").trim(),
|
|
191
|
+
emotional_impact: String(c.emotional_impact ?? "").trim(),
|
|
192
|
+
significance: String(c.significance ?? "medium").trim(),
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// event 必须有 occurred_at 和 emotional_impact
|
|
196
|
+
if (!fields.occurred_at || !fields.emotional_impact) continue;
|
|
197
|
+
|
|
198
|
+
valid.push({
|
|
199
|
+
type: "event",
|
|
200
|
+
name,
|
|
201
|
+
description: description.slice(0, 120),
|
|
202
|
+
body: String(c.body ?? formatEventBody(fields, description)).slice(0, 2000),
|
|
203
|
+
confidence: Math.max(0, Math.min(1, confidence)),
|
|
204
|
+
fields,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return valid;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function formatEmotionBody(
|
|
213
|
+
fields: EmotionMemoryFields,
|
|
214
|
+
description: string,
|
|
215
|
+
): string {
|
|
216
|
+
return [
|
|
217
|
+
description,
|
|
218
|
+
"",
|
|
219
|
+
`**触发**:${fields.trigger ?? ""}`,
|
|
220
|
+
`**表现**:${fields.manifestation ?? ""}`,
|
|
221
|
+
`**证据**:`,
|
|
222
|
+
...((fields.evidence ?? []).map((e) => `- ${e}`)),
|
|
223
|
+
].join("\n");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function formatEventBody(
|
|
227
|
+
fields: EventMemoryFields,
|
|
228
|
+
description: string,
|
|
229
|
+
): string {
|
|
230
|
+
return [
|
|
231
|
+
description,
|
|
232
|
+
"",
|
|
233
|
+
`**发生时间**:${fields.occurred_at ?? ""}`,
|
|
234
|
+
`**情感影响**:${fields.emotional_impact ?? ""}`,
|
|
235
|
+
`**重要程度**:${fields.significance ?? "medium"}`,
|
|
236
|
+
].join("\n");
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// =====================================================================
|
|
240
|
+
// 落盘(带去重 + 跨印证)
|
|
241
|
+
// =====================================================================
|
|
242
|
+
|
|
243
|
+
export type SaveResult = {
|
|
244
|
+
candidate: AnyMemoryCandidate;
|
|
245
|
+
/** "new" = 新建文件;"merged" = 追加到已有文件;"skipped" = 跳过 */
|
|
246
|
+
action: "new" | "merged" | "skipped";
|
|
247
|
+
existingFile?: MemoryFile;
|
|
248
|
+
path?: string;
|
|
249
|
+
/** 自动 link 的关联(v0.5 新增) */
|
|
250
|
+
linkedTo?: string[];
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 把候选记忆落盘(带去重 + 跨印证)。
|
|
255
|
+
*/
|
|
256
|
+
export async function saveMemoryCandidate(
|
|
257
|
+
memoryDir: string,
|
|
258
|
+
candidate: AnyMemoryCandidate,
|
|
259
|
+
): Promise<SaveResult> {
|
|
260
|
+
// 1. 找相似的(去重)
|
|
261
|
+
let similar: MemoryFile | null = null;
|
|
262
|
+
try {
|
|
263
|
+
similar = await findSimilarMemory(memoryDir, {
|
|
264
|
+
subtype: candidate.type,
|
|
265
|
+
name: candidate.name,
|
|
266
|
+
description: candidate.description,
|
|
267
|
+
});
|
|
268
|
+
} catch {
|
|
269
|
+
similar = null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (similar) {
|
|
273
|
+
// 合并到已有文件
|
|
274
|
+
try {
|
|
275
|
+
const addition = `**${candidate.description}**\n\n${candidate.body}`;
|
|
276
|
+
const result = await appendToMemoryFile(
|
|
277
|
+
memoryDir,
|
|
278
|
+
candidate.type,
|
|
279
|
+
similar.filename,
|
|
280
|
+
addition,
|
|
281
|
+
);
|
|
282
|
+
return {
|
|
283
|
+
candidate,
|
|
284
|
+
action: result.appended ? "merged" : "skipped",
|
|
285
|
+
existingFile: similar,
|
|
286
|
+
path: result.path,
|
|
287
|
+
};
|
|
288
|
+
} catch {
|
|
289
|
+
return { candidate, action: "skipped" };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// 2. 跨印证:自动 link
|
|
294
|
+
const linkedTo: string[] = [];
|
|
295
|
+
try {
|
|
296
|
+
if (candidate.type === "event") {
|
|
297
|
+
const emotions = await findRelatedEmotions(
|
|
298
|
+
memoryDir,
|
|
299
|
+
candidate.fields,
|
|
300
|
+
candidate.fields.occurred_at ?? "",
|
|
301
|
+
);
|
|
302
|
+
linkedTo.push(...emotions);
|
|
303
|
+
candidate.fields.linked_emotions = emotions;
|
|
304
|
+
} else if (candidate.type === "emotion") {
|
|
305
|
+
const events = await findRelatedEvents(memoryDir, candidate.fields);
|
|
306
|
+
linkedTo.push(...events);
|
|
307
|
+
candidate.fields.linked_events = events;
|
|
308
|
+
}
|
|
309
|
+
} catch {
|
|
310
|
+
// 跨印证失败不阻断保存
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 3. 新建文件
|
|
314
|
+
const filename = `${candidate.name}.md`;
|
|
315
|
+
try {
|
|
316
|
+
const path = await writeMemoryFile(
|
|
317
|
+
memoryDir,
|
|
318
|
+
{
|
|
319
|
+
name: candidate.name,
|
|
320
|
+
description: candidate.description,
|
|
321
|
+
subtype: candidate.type,
|
|
322
|
+
body: candidate.body,
|
|
323
|
+
fields: candidate.fields,
|
|
324
|
+
},
|
|
325
|
+
filename,
|
|
326
|
+
);
|
|
327
|
+
// 索引去重
|
|
328
|
+
const alreadyIndexed = await import("./memory.ts").then((m) =>
|
|
329
|
+
m.hasIndexEntry(memoryDir, candidate.type, candidate.name),
|
|
330
|
+
);
|
|
331
|
+
if (!alreadyIndexed) {
|
|
332
|
+
await appendIndexEntry(memoryDir, {
|
|
333
|
+
title: candidate.name,
|
|
334
|
+
subtype: candidate.type,
|
|
335
|
+
filename: candidate.name,
|
|
336
|
+
hook: candidate.description,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
candidate,
|
|
341
|
+
action: "new",
|
|
342
|
+
path,
|
|
343
|
+
linkedTo: linkedTo.length > 0 ? linkedTo : undefined,
|
|
344
|
+
};
|
|
345
|
+
} catch (e) {
|
|
346
|
+
console.error(`[memory-extract] 写入失败:`, (e as Error).message);
|
|
347
|
+
return { candidate, action: "skipped" };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// =====================================================================
|
|
352
|
+
// 一站式入口
|
|
353
|
+
// =====================================================================
|
|
354
|
+
|
|
355
|
+
export type AutoExtractConfig = {
|
|
356
|
+
minConfidence?: number;
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* 完整链路:抽取 → 过滤(置信度) → 落盘(去重 + 跨印证)。
|
|
361
|
+
*/
|
|
362
|
+
export async function maybeAutoExtract(
|
|
363
|
+
memoryDir: string,
|
|
364
|
+
provider: ModelProvider,
|
|
365
|
+
recentMessages: { role: string; content: string }[],
|
|
366
|
+
config: AutoExtractConfig = {},
|
|
367
|
+
): Promise<SaveResult[]> {
|
|
368
|
+
try {
|
|
369
|
+
const existing = await scanMemory(memoryDir);
|
|
370
|
+
const candidates = await extractMemoryCandidates(
|
|
371
|
+
provider,
|
|
372
|
+
recentMessages,
|
|
373
|
+
existing,
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
const minConfidence = config.minConfidence ?? 0.7;
|
|
377
|
+
const filtered = candidates.filter((c) => c.confidence >= minConfidence);
|
|
378
|
+
if (filtered.length === 0) return [];
|
|
379
|
+
|
|
380
|
+
const results: SaveResult[] = [];
|
|
381
|
+
for (const c of filtered) {
|
|
382
|
+
const r = await saveMemoryCandidate(memoryDir, c);
|
|
383
|
+
results.push(r);
|
|
384
|
+
}
|
|
385
|
+
return results;
|
|
386
|
+
} catch (e) {
|
|
387
|
+
console.error(`[memory-extract] 失败:`, (e as Error).message);
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
}
|