@jokab1074/rememberme 0.0.0-stage → 0.22.1
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 +202 -0
- package/README.en.md +459 -0
- package/README.md +477 -2
- package/dist/mcp/index.js +37334 -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 +44 -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 +284 -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 +1095 -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-security.ts +43 -0
- package/src/web.ts +724 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// src/mcp/tools/record-turn.ts
|
|
2
|
+
//
|
|
3
|
+
// record_turn —— 唯一的写工具。
|
|
4
|
+
//
|
|
5
|
+
// 设计要点(来自 experiments/mcp-probe 的实测结论):
|
|
6
|
+
//
|
|
7
|
+
// 1. 宿主只判断「这轮值不值得记」,**条件式调用**。
|
|
8
|
+
// 实测证明「每轮都调一个工具」对 LLM 不可靠 —— 模型漏调时意识不到自己漏了。
|
|
9
|
+
//
|
|
10
|
+
// 2. 「记成什么」由 server 决定:缓冲攒够 → server 调自己的 LLM 做抽取,
|
|
11
|
+
// 用的是 RememberMe 原版的 extractMemoryCandidates()(prompt、JSON 解析、
|
|
12
|
+
// ≥2 证据校验全部零改动)。
|
|
13
|
+
// —— 这也是 MCP 官方 SEP-2577 废弃 sampling 后推荐的迁移方向。
|
|
14
|
+
//
|
|
15
|
+
// 3. 画像更新复用现有的 maybeUpdateProfile()(和 Web/CLI 完全同一条路径),
|
|
16
|
+
// 所以宿主不需要额外学一套「怎么写画像段」的规则。
|
|
17
|
+
//
|
|
18
|
+
// 4. 没写出时**保留缓冲** —— 一次出现可能是某个模式的第 1 次,
|
|
19
|
+
// 清掉就永远等不到第 2 次了。
|
|
20
|
+
|
|
21
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
import {
|
|
24
|
+
extractMemoryCandidates,
|
|
25
|
+
saveMemoryCandidate,
|
|
26
|
+
} from "../../memory-extract.ts";
|
|
27
|
+
import { maybeUpdateProfile } from "../../profile.ts";
|
|
28
|
+
// AnyMemoryCandidate 定义在 memory.ts(memory-extract.ts 只是 import 它,没有再导出)
|
|
29
|
+
import { scanMemory, type AnyMemoryCandidate } from "../../memory.ts";
|
|
30
|
+
import { paths } from "../config.ts";
|
|
31
|
+
import { getProvider, providerStatus } from "../provider.ts";
|
|
32
|
+
import { log } from "../logger.ts";
|
|
33
|
+
|
|
34
|
+
/** 缓冲里攒够几条"值得记"的记录就抽取(够 2 条证据才能归纳成模式) */
|
|
35
|
+
const EXTRACT_BUFFER_THRESHOLD = 2;
|
|
36
|
+
/** 缓冲上限(没写出时保留,防止无限增长) */
|
|
37
|
+
const MAX_BUFFER = 10;
|
|
38
|
+
|
|
39
|
+
export type PendingTurn = {
|
|
40
|
+
userMessage: string;
|
|
41
|
+
assistantReply?: string;
|
|
42
|
+
emotion?: string;
|
|
43
|
+
intensity?: number;
|
|
44
|
+
trigger?: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 把宿主已经判断过的情绪信息格式化成一行上下文。
|
|
49
|
+
*
|
|
50
|
+
* 这三个字段原本收了却**从头到尾没被用过** —— 抽取器完全不知道宿主已经判断过一次
|
|
51
|
+
* 情绪,只能自己从原文重新猜一遍。而抽取 rubric 要的字段恰好就是它们:
|
|
52
|
+
* - emotion → emotion 条目的「manifestation」(情绪类型 + 强度描述)
|
|
53
|
+
* - trigger → emotion 条目的「trigger」(触发条件)
|
|
54
|
+
* - intensity → 强度描述
|
|
55
|
+
* 宿主判断一次、抽取器直接用,不用重复劳动(v0.22.1)。
|
|
56
|
+
*
|
|
57
|
+
* 单独放一条 [system] 消息,而不是拼进用户原话 ——
|
|
58
|
+
* 用户原话要保持原样,抽取 rubric 要求「保留用户原话片段」当证据,
|
|
59
|
+
* 拼进去容易被当成用户说的话。
|
|
60
|
+
*/
|
|
61
|
+
export function formatEmotionHints(p: PendingTurn): string | null {
|
|
62
|
+
const parts: string[] = [];
|
|
63
|
+
if (p.emotion?.trim()) parts.push(`情绪=${p.emotion.trim()}`);
|
|
64
|
+
if (typeof p.intensity === "number" && Number.isFinite(p.intensity)) {
|
|
65
|
+
parts.push(`强度=${p.intensity.toFixed(1)}`);
|
|
66
|
+
}
|
|
67
|
+
if (p.trigger?.trim()) parts.push(`触发=${p.trigger.trim()}`);
|
|
68
|
+
if (parts.length === 0) return null;
|
|
69
|
+
return `[宿主已判断本轮情绪] ${parts.join(",")}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 把缓冲里的轮次拼成抽取用的对话。
|
|
74
|
+
*
|
|
75
|
+
* 宿主判断过的情绪信息作为独立的 [system] 一行插在对应用户消息之前,
|
|
76
|
+
* 用户原话保持原样。
|
|
77
|
+
*/
|
|
78
|
+
export function buildExtractionConvo(
|
|
79
|
+
pending: PendingTurn[],
|
|
80
|
+
): { role: string; content: string }[] {
|
|
81
|
+
const convo: { role: string; content: string }[] = [];
|
|
82
|
+
for (const p of pending) {
|
|
83
|
+
const hints = formatEmotionHints(p);
|
|
84
|
+
if (hints) {
|
|
85
|
+
convo.push({ role: "system", content: hints });
|
|
86
|
+
}
|
|
87
|
+
convo.push({ role: "user", content: p.userMessage });
|
|
88
|
+
if (p.assistantReply) {
|
|
89
|
+
convo.push({ role: "assistant", content: p.assistantReply });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return convo;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function registerRecordTurnTool(server: McpServer): void {
|
|
96
|
+
const pending: PendingTurn[] = [];
|
|
97
|
+
|
|
98
|
+
server.registerTool(
|
|
99
|
+
"record_turn",
|
|
100
|
+
{
|
|
101
|
+
title: "记录这一轮值得记住的内容",
|
|
102
|
+
description:
|
|
103
|
+
"当这一轮有值得长期记住的内容时调用:用户明确要求记住、出现重大生活事件、" +
|
|
104
|
+
"或又一次出现同类情绪反应。" +
|
|
105
|
+
"你只负责判断「值不值得记」并如实转达;具体记成什么、归纳成什么模式," +
|
|
106
|
+
"由记忆系统按它自己的规则决定,你不需要自己写记忆内容。",
|
|
107
|
+
inputSchema: {
|
|
108
|
+
user_message: z.string().describe("用户这轮说的话(原文)"),
|
|
109
|
+
assistant_reply: z
|
|
110
|
+
.string()
|
|
111
|
+
.optional()
|
|
112
|
+
.describe("你这轮的回复(如果有)"),
|
|
113
|
+
emotion: z
|
|
114
|
+
.string()
|
|
115
|
+
.optional()
|
|
116
|
+
.describe("你这轮判断出的用户情绪类别(可选)。记忆系统会直接用它来写情绪模式的表现字段,不用再从原文猜一遍"),
|
|
117
|
+
intensity: z
|
|
118
|
+
.number()
|
|
119
|
+
.min(0)
|
|
120
|
+
.max(1)
|
|
121
|
+
.optional()
|
|
122
|
+
.describe("情绪强度 0-1(可选)。同上,会被直接采用"),
|
|
123
|
+
trigger: z
|
|
124
|
+
.string()
|
|
125
|
+
.optional()
|
|
126
|
+
.describe("情绪触发原因(可选)。会直接写进情绪模式的「触发条件」字段"),
|
|
127
|
+
definite: z
|
|
128
|
+
.boolean()
|
|
129
|
+
.optional()
|
|
130
|
+
.describe(
|
|
131
|
+
"true = 用户明确要求记住,或发生了明确的重大事件(立即抽取并落盘);" +
|
|
132
|
+
"false 或不填 = 只是又一次出现同类情绪(先攒着,攒够了再归纳成模式)。",
|
|
133
|
+
),
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
async (args) => {
|
|
137
|
+
try {
|
|
138
|
+
pending.push({
|
|
139
|
+
userMessage: args.user_message,
|
|
140
|
+
assistantReply: args.assistant_reply,
|
|
141
|
+
emotion: args.emotion,
|
|
142
|
+
intensity: args.intensity,
|
|
143
|
+
trigger: args.trigger,
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const buffered = pending.length;
|
|
147
|
+
// 抽取时机:
|
|
148
|
+
// definite=true(用户明确要求 / 重大事件)→ 立即抽
|
|
149
|
+
// 攒够 2 次同类出现 → 抽(够 2 条证据才能归纳成模式)
|
|
150
|
+
//
|
|
151
|
+
// 不用「情绪强度 ≥ 0.7」单独触发:缓冲里装的都是宿主已判定为「值得记」的
|
|
152
|
+
// 轮次,只有一条时抽了必然凑不够证据、白白消耗一次 LLM 调用,还会把它冲掉。
|
|
153
|
+
const shouldExtract =
|
|
154
|
+
args.definite === true || buffered >= EXTRACT_BUFFER_THRESHOLD;
|
|
155
|
+
|
|
156
|
+
if (!shouldExtract) {
|
|
157
|
+
// 画像更新:复用现有实现,fire-and-forget(和 Web/CLI 同一条路径)
|
|
158
|
+
void updateProfileInBackground();
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
content: [
|
|
162
|
+
{
|
|
163
|
+
type: "text",
|
|
164
|
+
text: `已记录(缓冲 ${buffered} 条,攒够 ${EXTRACT_BUFFER_THRESHOLD} 条或用户明确要求时抽取)。`,
|
|
165
|
+
},
|
|
166
|
+
],
|
|
167
|
+
structuredContent: {
|
|
168
|
+
buffered,
|
|
169
|
+
willExtract: false,
|
|
170
|
+
written: [],
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---- server 调自己的 LLM 做抽取 ----
|
|
176
|
+
const provider = getProvider();
|
|
177
|
+
if (!provider) {
|
|
178
|
+
const status = providerStatus();
|
|
179
|
+
return {
|
|
180
|
+
content: [
|
|
181
|
+
{
|
|
182
|
+
type: "text",
|
|
183
|
+
text:
|
|
184
|
+
`无法抽取记忆:没有可用的 LLM 配置。\n${status.error ?? ""}\n` +
|
|
185
|
+
`(缓冲已保留,配置好 key 后下一轮会重试。)`,
|
|
186
|
+
},
|
|
187
|
+
],
|
|
188
|
+
isError: true,
|
|
189
|
+
structuredContent: { buffered, willExtract: true, written: [] },
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const existing = await scanMemory(paths.memory);
|
|
194
|
+
const convo = buildExtractionConvo(pending);
|
|
195
|
+
|
|
196
|
+
let candidates: AnyMemoryCandidate[] = [];
|
|
197
|
+
try {
|
|
198
|
+
candidates = await extractMemoryCandidates(provider, convo, existing);
|
|
199
|
+
} catch (e) {
|
|
200
|
+
// LLM 调用失败 → 不丢缓冲,下轮再试
|
|
201
|
+
log.error("抽取失败:", (e as Error).message);
|
|
202
|
+
return {
|
|
203
|
+
content: [
|
|
204
|
+
{
|
|
205
|
+
type: "text",
|
|
206
|
+
text: `抽取失败(${(e as Error).message})。缓冲已保留,下轮再试。`,
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
isError: true,
|
|
210
|
+
structuredContent: { buffered, willExtract: true, written: [] },
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const written: { type: string; name: string; action: string }[] = [];
|
|
215
|
+
for (const c of candidates) {
|
|
216
|
+
const r = await saveMemoryCandidate(paths.memory, c);
|
|
217
|
+
written.push({
|
|
218
|
+
type: c.type,
|
|
219
|
+
name:
|
|
220
|
+
r.action === "new" ? c.name : (r.existingFile?.name ?? c.name),
|
|
221
|
+
action: r.action,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (written.length > 0) {
|
|
226
|
+
pending.length = 0;
|
|
227
|
+
} else {
|
|
228
|
+
// 宁缺毋滥 → 没写出。**保留缓冲**:这一条可能是某个模式的第 1 次出现,
|
|
229
|
+
// 清掉就永远等不到第 2 次了。上限兜底,防止无限增长。
|
|
230
|
+
if (pending.length > MAX_BUFFER) {
|
|
231
|
+
pending.splice(0, pending.length - MAX_BUFFER);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
void updateProfileInBackground();
|
|
236
|
+
|
|
237
|
+
return {
|
|
238
|
+
content: [
|
|
239
|
+
{
|
|
240
|
+
type: "text",
|
|
241
|
+
text:
|
|
242
|
+
written.length > 0
|
|
243
|
+
? `已抽取并写入 ${written.length} 条记忆:${written
|
|
244
|
+
.map((w) => `${w.type}/${w.name}(${w.action})`)
|
|
245
|
+
.join(", ")}`
|
|
246
|
+
: `已回顾 ${buffered} 条记录,暂不足以归纳成模式(已保留,等下一次出现)。`,
|
|
247
|
+
},
|
|
248
|
+
],
|
|
249
|
+
structuredContent: { buffered, willExtract: true, written },
|
|
250
|
+
};
|
|
251
|
+
} catch (e) {
|
|
252
|
+
log.error("record_turn 失败:", (e as Error).message);
|
|
253
|
+
return {
|
|
254
|
+
content: [
|
|
255
|
+
{ type: "text", text: `记录失败:${(e as Error).message}` },
|
|
256
|
+
],
|
|
257
|
+
isError: true,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 画像更新 —— 复用现有的 maybeUpdateProfile()。
|
|
265
|
+
*
|
|
266
|
+
* 和 Web/CLI 是同一条代码路径(段1/2/6 由 LLM 抽取,段3/4/5 派生重算)。
|
|
267
|
+
* fire-and-forget:不阻塞宿主这一轮。
|
|
268
|
+
*/
|
|
269
|
+
async function updateProfileInBackground(): Promise<void> {
|
|
270
|
+
const provider = getProvider();
|
|
271
|
+
if (!provider) return;
|
|
272
|
+
const convo = pending
|
|
273
|
+
.slice(-6)
|
|
274
|
+
.map((p) => ({ role: "user" as const, content: p.userMessage }));
|
|
275
|
+
if (convo.length === 0) return;
|
|
276
|
+
try {
|
|
277
|
+
await maybeUpdateProfile(paths.data, provider, convo, {
|
|
278
|
+
memoryDir: paths.memory,
|
|
279
|
+
});
|
|
280
|
+
} catch (e) {
|
|
281
|
+
log.warn("画像更新失败:", (e as Error).message);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
@@ -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
|
+
}
|