@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.
Files changed (45) hide show
  1. package/ARCHITECTURE.md +787 -0
  2. package/LICENSE +202 -0
  3. package/README.en.md +459 -0
  4. package/README.md +477 -2
  5. package/dist/mcp/index.js +37334 -0
  6. package/package.json +67 -4
  7. package/server.json +38 -0
  8. package/settings.json.example +7 -0
  9. package/src/bigfive.ts +163 -0
  10. package/src/bootstrap.ts +104 -0
  11. package/src/classify.ts +186 -0
  12. package/src/compact.ts +225 -0
  13. package/src/context-file.ts +305 -0
  14. package/src/embedded-proactive.ts +214 -0
  15. package/src/evolution/access-tracker.ts +118 -0
  16. package/src/evolution/curator.ts +220 -0
  17. package/src/evolution/lifecycle.ts +175 -0
  18. package/src/feedback-detector.ts +177 -0
  19. package/src/i18n.ts +89 -0
  20. package/src/index.ts +1479 -0
  21. package/src/loop.ts +396 -0
  22. package/src/mcp/build.ts +64 -0
  23. package/src/mcp/config.ts +108 -0
  24. package/src/mcp/index.ts +66 -0
  25. package/src/mcp/instructions.ts +44 -0
  26. package/src/mcp/logger.ts +32 -0
  27. package/src/mcp/provider.ts +142 -0
  28. package/src/mcp/server.ts +52 -0
  29. package/src/mcp/tools/memory.ts +126 -0
  30. package/src/mcp/tools/profile.ts +67 -0
  31. package/src/mcp/tools/record-turn.ts +284 -0
  32. package/src/memory-extract.ts +390 -0
  33. package/src/memory.ts +790 -0
  34. package/src/persona-init.ts +153 -0
  35. package/src/persona-learner.ts +349 -0
  36. package/src/proactive.ts +557 -0
  37. package/src/profile.ts +1095 -0
  38. package/src/prompt.ts +288 -0
  39. package/src/provider.ts +292 -0
  40. package/src/reflection.ts +552 -0
  41. package/src/sessions.ts +140 -0
  42. package/src/timeline.ts +208 -0
  43. package/src/utils.ts +91 -0
  44. package/src/web-security.ts +43 -0
  45. package/src/web.ts +724 -0
package/src/compact.ts ADDED
@@ -0,0 +1,225 @@
1
+ // src/compact.ts
2
+ // 自动压缩长对话历史(emotional-aware)。
3
+ //
4
+ // 通用 LLM agent 模式:长对话超过窗口时,用另一个 LLM 生成结构化摘要。
5
+ // 本项目根据情感场景定制摘要字段(保留用户偏好纠正、情绪转折点)。
6
+ //
7
+ // 情感场景的特别需求:
8
+ // 1. 必须保留用户的情绪强度与转折点("用户说累但其实是压抑的愤怒")
9
+ // 2. 必须保留用户对主人的偏好纠正("用户说别再总结")
10
+ // 3. 必须保留未完结的话题(下次接茬用)
11
+ // 4. 必须保留人格语气基准不能漂移
12
+
13
+ import type { ChatMessage, ModelProvider } from "./provider.ts";
14
+ import { estimateTokens } from "./utils.ts";
15
+ import { t } from "./i18n.ts";
16
+
17
+ // estimateTokens 的实现已移到 utils.ts(memory.ts 的索引预算也要用)。
18
+ // 这里继续导出,保持 compact 模块既有的公开面不变。
19
+ export { estimateTokens };
20
+
21
+ // =====================================================================
22
+ // 配置
23
+ // =====================================================================
24
+
25
+ export type CompactConfig = {
26
+ /** 触发压缩的历史长度(消息数 = 2×轮数)。默认 20 条 = 10 轮对话 */
27
+ triggerAt: number;
28
+ /** 压缩时保留最近多少条。默认 6 条 = 3 轮 */
29
+ recentKept: number;
30
+ /** 估算 token 上限(粗略按字符数 / 2)。默认 20000 字符 ≈ 10000 tokens */
31
+ maxChars: number;
32
+ /** 当历史总 token 估算低于此值时,跳过 compact(summary 反而更长,不划算)。默认 1500 */
33
+ minCompactWorth: number;
34
+ };
35
+
36
+ export const DEFAULT_COMPACT_CONFIG: CompactConfig = {
37
+ triggerAt: 20,
38
+ recentKept: 6,
39
+ maxChars: 20000,
40
+ /** 当历史总 token 估算低于此值时,compact 不划算(summary 反而更长),跳过 */
41
+ minCompactWorth: 1500,
42
+ };
43
+
44
+ // =====================================================================
45
+ // Token 估算(粗略字符法,避免引入 tokenizer 依赖)
46
+ // =====================================================================
47
+
48
+ export function estimateHistoryTokens(history: ChatMessage[]): number {
49
+ let total = 0;
50
+ for (const m of history) {
51
+ total += estimateTokens(m.content);
52
+ }
53
+ return total;
54
+ }
55
+
56
+ // =====================================================================
57
+ // 触发判断
58
+ // =====================================================================
59
+
60
+ export type CompactDecision = {
61
+ shouldCompact: boolean;
62
+ reason: "ok" | "too_many_messages" | "too_many_tokens";
63
+ /** 待压缩的旧消息数 */
64
+ oldCount?: number;
65
+ /** 保留的最近消息数 */
66
+ recentCount?: number;
67
+ };
68
+
69
+ export function shouldCompact(
70
+ history: ChatMessage[],
71
+ config: CompactConfig = DEFAULT_COMPACT_CONFIG,
72
+ ): CompactDecision {
73
+ // 1. 先检查 short-circuit:旧历史总 token 太小时,compact 不划算(summary 反而更长)
74
+ const tokens = estimateHistoryTokens(history);
75
+ if (tokens < config.minCompactWorth) {
76
+ return { shouldCompact: false, reason: "ok" };
77
+ }
78
+
79
+ // 2. 消息数触发
80
+ if (history.length >= config.triggerAt) {
81
+ return {
82
+ shouldCompact: true,
83
+ reason: "too_many_messages",
84
+ oldCount: history.length - config.recentKept,
85
+ recentCount: config.recentKept,
86
+ };
87
+ }
88
+
89
+ // 3. token 数触发(粗略估算 = 2 × token 数 → 比较 maxChars)
90
+ if (tokens * 2 >= config.maxChars) {
91
+ return {
92
+ shouldCompact: true,
93
+ reason: "too_many_tokens",
94
+ oldCount: history.length - config.recentKept,
95
+ recentCount: config.recentKept,
96
+ };
97
+ }
98
+
99
+ return { shouldCompact: false, reason: "ok" };
100
+ }
101
+
102
+ // =====================================================================
103
+ // 压缩执行
104
+ // =====================================================================
105
+
106
+ /**
107
+ * 情感场景定制的压缩 prompt(关键段不可省略)。
108
+ *
109
+ * 6 段分类(情感场景定制,不参考任何特定项目):
110
+ * 1. 用户情绪轨迹(含转折)
111
+ * 2. 用户关键信息(角色、关系、生活事件)
112
+ * 3. 用户偏好与纠正(最关键——这是人格调整的输入)
113
+ * 4. 未完结话题与承诺(下次接茬用)
114
+ * 5. 当前主导情绪与主人在这次对话中的语气
115
+ * 6. 其他需要传递给下一个 LLM 的上下文
116
+ */
117
+ const COMPACT_SYSTEM_PROMPT = t("compact.system_prompt");
118
+
119
+ function buildCompactInput(
120
+ history: ChatMessage[],
121
+ profileSummary?: string,
122
+ ): string {
123
+ const lines = history.map(
124
+ (m, i) => `${i + 1}. [${m.role}] ${m.content}`,
125
+ );
126
+ const profileBlock = profileSummary
127
+ ? `\n\n${t("compact.user_prefix")}\n${profileSummary}\n`
128
+ : "";
129
+ return `${t("compact.user_prefix")}${profileBlock}\n\n${lines.join("\n\n")}`;
130
+ }
131
+
132
+ export type CompactResult = {
133
+ /** 替换后的历史(摘要消息 + 保留的最近消息) */
134
+ history: ChatMessage[];
135
+ /** 摘要原文 */
136
+ summary: string;
137
+ /** 压缩轮数 */
138
+ compactedCount: number;
139
+ /** 节省的估算 token 数 */
140
+ savedTokens: number;
141
+ };
142
+
143
+ export async function compactHistory(
144
+ history: ChatMessage[],
145
+ provider: ModelProvider,
146
+ config: CompactConfig = DEFAULT_COMPACT_CONFIG,
147
+ /** 可选的用户画像摘要,让 compact 的摘要与长期信息一致 */
148
+ profileSummary?: string,
149
+ ): Promise<CompactResult> {
150
+ if (history.length <= config.recentKept) {
151
+ return {
152
+ history,
153
+ summary: "",
154
+ compactedCount: 0,
155
+ savedTokens: 0,
156
+ };
157
+ }
158
+
159
+ const oldMessages = history.slice(0, history.length - config.recentKept);
160
+ const recentMessages = history.slice(history.length - config.recentKept);
161
+
162
+ // token 估算(压缩前)
163
+ const tokensBefore = estimateHistoryTokens(history);
164
+
165
+ // 用主模型做摘要(也可以走小模型,未来扩展)
166
+ const summary = await provider.complete({
167
+ model: provider.model,
168
+ params: {
169
+ system: COMPACT_SYSTEM_PROMPT,
170
+ messages: [
171
+ {
172
+ role: "user",
173
+ content: buildCompactInput(oldMessages, profileSummary),
174
+ },
175
+ ],
176
+ maxTokens: 800, // 硬限制:summary 必须 < 800 tokens(约 1600 中文字)
177
+ temperature: 0.3, // 低温度,要求稳定输出
178
+ },
179
+ });
180
+
181
+ // 摘要作为一个 user 角色消息(不是 assistant 角色)。
182
+ // 为什么是 user 而不是 assistant:避免模型把 summary 当成"我刚才说的话",
183
+ // 进而污染下一轮的回应(比如把 summary 里的"工作压力"当成最近的话题,
184
+ // 然后用户说"我吃了碗面"时回"聊了什么")。
185
+ // 前缀用方括号和 [BACKGROUND] 标记,让模型明确这是上下文信息而非对话内容。
186
+ const summaryMessage: ChatMessage = {
187
+ role: "user",
188
+ content: `[BACKGROUND — 由另一个 LLM 生成的早前对话压缩摘要,仅供参考,不要据此回答当前问题。继续按你的当前人格与用户对话。]\n\n${summary.trim()}\n\n[END BACKGROUND]`,
189
+ };
190
+
191
+ const newHistory = [summaryMessage, ...recentMessages];
192
+ const tokensAfter = estimateHistoryTokens(newHistory);
193
+
194
+ return {
195
+ history: newHistory,
196
+ summary,
197
+ compactedCount: oldMessages.length,
198
+ savedTokens: Math.max(0, tokensBefore - tokensAfter),
199
+ };
200
+ }
201
+
202
+ // =====================================================================
203
+ // 整合入口
204
+ // =====================================================================
205
+
206
+ /**
207
+ * 一站式:决定+执行压缩。供 loop.ts 调用。
208
+ *
209
+ * 如果不需要压缩直接返回原 history。
210
+ */
211
+ export async function maybeCompact(
212
+ history: ChatMessage[],
213
+ provider: ModelProvider,
214
+ config: CompactConfig = DEFAULT_COMPACT_CONFIG,
215
+ /** 可选的用户画像摘要 */
216
+ profileSummary?: string,
217
+ ): Promise<{ history: ChatMessage[]; result: CompactResult | null }> {
218
+ const decision = shouldCompact(history, config);
219
+ if (!decision.shouldCompact) {
220
+ return { history, result: null };
221
+ }
222
+
223
+ const result = await compactHistory(history, provider, config, profileSummary);
224
+ return { history: result.history, result };
225
+ }
@@ -0,0 +1,305 @@
1
+ // src/context-file.ts
2
+ // 纯 Markdown 格式的 profile / personality 文件解析器。
3
+ //
4
+ // 格式约定(统一):
5
+ // # <name> ← H1 = name
6
+ //
7
+ // - **类型**:personality | profile ← 元数据列表(可选)
8
+ // - **版本**:1.0.0
9
+ // - **作者**:xxx
10
+ // - **描述**:xxx
11
+ //
12
+ // <正文:自由格式 / 或 6 段结构(profile)> ← 元数据列表之后的所有内容
13
+ //
14
+ // 元数据列表结束标志:第一个 ## 标题 或 非列表行
15
+ //
16
+ // 互换性(保持纯 Markdown):
17
+ // PROFILE.md 复制到 personality/ → loadPersonality 成功
18
+ // personality/*.md 复制到 data/profile/ → loadProfile 成功
19
+ //
20
+ // 完全去掉 YAML frontmatter(--- 分隔符),
21
+ // 对非技术用户更友好。
22
+
23
+ import { join } from "node:path";
24
+
25
+ // =====================================================================
26
+ // Profile 6 段(这里定义,profile.ts re-export)
27
+ // =====================================================================
28
+
29
+ export const PROFILE_SECTIONS = [
30
+ "基本信息",
31
+ "沟通风格",
32
+ "关注议题",
33
+ "已知偏好与禁忌",
34
+ "长期情绪基线",
35
+ "近期变化",
36
+ ] as const;
37
+
38
+ export type ProfileSection = (typeof PROFILE_SECTIONS)[number];
39
+
40
+ // =====================================================================
41
+ // 类型
42
+ // =====================================================================
43
+
44
+ export type ContextFileKind = "personality" | "profile";
45
+
46
+ export type ContextFileMeta = {
47
+ name: string;
48
+ version: string;
49
+ description: string;
50
+ author: string;
51
+ kind: ContextFileKind;
52
+ };
53
+
54
+ /** 解析后的文件。 */
55
+ export type ContextFile = {
56
+ meta: ContextFileMeta;
57
+ /** body(不含 H1 和元数据列表) */
58
+ body: string;
59
+ /**
60
+ * 如果 body 含 6 段 ## 结构,则提取;否则 undefined。
61
+ */
62
+ structuredSections?: Record<ProfileSection, string>;
63
+ /** 完整原始文本(用于 round-trip 序列化) */
64
+ raw: string;
65
+ /** 文件路径 */
66
+ sourcePath: string;
67
+ };
68
+
69
+ // =====================================================================
70
+ // 元数据键名映射
71
+ // =====================================================================
72
+
73
+ /**
74
+ * 元数据列表的 key → meta 字段映射(支持中英文)。
75
+ */
76
+ const META_KEY_MAP: Record<string, keyof ContextFileMeta> = {
77
+ 类型: "kind",
78
+ kind: "kind",
79
+ 版本: "version",
80
+ version: "version",
81
+ 作者: "author",
82
+ author: "author",
83
+ 描述: "description",
84
+ description: "description",
85
+ 名称: "name",
86
+ name: "name",
87
+ };
88
+
89
+ // =====================================================================
90
+ // 解析
91
+ // =====================================================================
92
+
93
+ /**
94
+ * 从纯 Markdown 文件中提取 H1(name)和元数据列表。
95
+ *
96
+ * 返回:
97
+ * - name: 第一个 H1 的文本(去掉前缀 # 和首尾空白)
98
+ * - meta: 解析出的元数据
99
+ * - body: 元数据列表之后的所有内容(已 trim)
100
+ * - bodyStartLine: body 在 raw 中的起始行号(用于 6 段检测)
101
+ */
102
+ function extractMarkdownMetadata(raw: string): {
103
+ name: string;
104
+ meta: ContextFileMeta;
105
+ body: string;
106
+ } {
107
+ const lines = raw.split("\n");
108
+
109
+ // 默认 meta
110
+ const meta: ContextFileMeta = {
111
+ name: "",
112
+ version: "0.0.0",
113
+ description: "",
114
+ author: "unknown",
115
+ kind: "personality",
116
+ };
117
+
118
+ let i = 0;
119
+
120
+ // 1. 跳过前导空行
121
+ while (i < lines.length && lines[i].trim() === "") i++;
122
+
123
+ // 2. 找第一个 H1
124
+ let name = "";
125
+ if (i < lines.length && /^#\s+/.test(lines[i])) {
126
+ name = lines[i].replace(/^#\s+/, "").trim();
127
+ meta.name = name;
128
+ i++;
129
+ }
130
+
131
+ // 3. 跳到元数据列表(跳过 H1 后的空行)
132
+ while (i < lines.length && lines[i].trim() === "") i++;
133
+
134
+ // 4. 读取连续的元数据列表项(- **key**:value)
135
+ // 结束条件:第一个 ## 标题 / 非列表行
136
+ while (i < lines.length) {
137
+ const line = lines[i];
138
+ // 元数据项正则:- **key** [::] value
139
+ // 支持中文冒号(:U+FF1A)和英文冒号(:)
140
+ const m = line.match(
141
+ /^-\s+\*\*(.+?)\*\*\s*[::]\s*(.*?)\s*$/,
142
+ );
143
+ if (m) {
144
+ const key = m[1].trim();
145
+ const value = m[2].trim();
146
+ const metaKey = META_KEY_MAP[key] ?? META_KEY_MAP[key.toLowerCase()];
147
+ if (metaKey === "kind") {
148
+ meta.kind = value === "profile" ? "profile" : "personality";
149
+ } else if (metaKey) {
150
+ // Type assertion:metaKey is a keyof ContextFileMeta
151
+ (meta as Record<string, string>)[metaKey] = value;
152
+ } else {
153
+ // 未识别的 key 也存到 meta 上(v0.21: 用于 ocean_* 等自定义字段)
154
+ (meta as Record<string, string>)[key.toLowerCase()] = value;
155
+ }
156
+ i++;
157
+ } else if (line.trim() === "") {
158
+ // 空行:跳过(但如果下一个非空行不是列表项,结束元数据块)
159
+ const next = i + 1;
160
+ if (
161
+ next < lines.length &&
162
+ lines[next].trim() !== "" &&
163
+ !/^-\s+/.test(lines[next])
164
+ ) {
165
+ i++;
166
+ break;
167
+ }
168
+ i++;
169
+ } else {
170
+ // 非列表、非空行 → 元数据块结束
171
+ break;
172
+ }
173
+ }
174
+
175
+ // 5. body = 剩余所有行
176
+ const body = lines.slice(i).join("\n").trim();
177
+
178
+ return { name, meta, body };
179
+ }
180
+
181
+ /**
182
+ * 解析上下文文件(personality 或 profile),返回统一结构。
183
+ */
184
+ export function parseContextFile(
185
+ raw: string,
186
+ sourcePath: string,
187
+ ): ContextFile {
188
+ const { meta, body } = extractMarkdownMetadata(raw);
189
+ const structuredSections = tryParseStructuredSections(body);
190
+
191
+ return {
192
+ meta,
193
+ body,
194
+ structuredSections,
195
+ raw,
196
+ sourcePath,
197
+ };
198
+ }
199
+
200
+ // =====================================================================
201
+ // 6 段结构检测
202
+ // =====================================================================
203
+
204
+ /**
205
+ * 检测 body 是否含 6 段 PROFILE_SECTIONS 结构。
206
+ */
207
+ function tryParseStructuredSections(
208
+ body: string,
209
+ ): Record<ProfileSection, string> | undefined {
210
+ const lines = body.split("\n");
211
+ const sectionStarts: { name: string; lineIdx: number }[] = [];
212
+ for (let i = 0; i < lines.length; i++) {
213
+ const m = lines[i].match(/^##\s+(.+?)\s*$/);
214
+ if (m) {
215
+ const rawName = m[1].trim();
216
+ const stripped = rawName.replace(/^\d+\.\s*/, "");
217
+ sectionStarts.push({ name: stripped, lineIdx: i });
218
+ }
219
+ }
220
+
221
+ const hasStructuredSection = sectionStarts.some((s) =>
222
+ (PROFILE_SECTIONS as readonly string[]).includes(s.name),
223
+ );
224
+ if (!hasStructuredSection) return undefined;
225
+
226
+ const sections = {} as Record<ProfileSection, string>;
227
+ for (const s of PROFILE_SECTIONS) sections[s] = "";
228
+
229
+ for (let i = 0; i < sectionStarts.length; i++) {
230
+ const { name, lineIdx } = sectionStarts[i];
231
+ const nextIdx =
232
+ i + 1 < sectionStarts.length ? sectionStarts[i + 1].lineIdx : lines.length;
233
+ const sectionBody = lines.slice(lineIdx + 1, nextIdx).join("\n").trim();
234
+
235
+ if ((PROFILE_SECTIONS as readonly string[]).includes(name)) {
236
+ sections[name as ProfileSection] = sectionBody;
237
+ }
238
+ }
239
+
240
+ return sections;
241
+ }
242
+
243
+ // =====================================================================
244
+ // 序列化
245
+ // =====================================================================
246
+
247
+ /**
248
+ * 把 meta + body 序列化成纯 Markdown 文件。
249
+ *
250
+ * 格式:
251
+ * # <name>
252
+ *
253
+ * - **类型**:<kind>
254
+ * - **版本**:<version>
255
+ * - **作者**:<author>
256
+ * - **描述**:<description>
257
+ *
258
+ * <body>
259
+ *
260
+ * 如果 meta.name 为空但 body 第一行是 H1,name 用 body 里的 H1。
261
+ */
262
+ export function serializeContextFile(
263
+ meta: ContextFileMeta,
264
+ body: string,
265
+ ): string {
266
+ // 优先用 meta.name;如果是 profile 默认空(但 default template 给了名字)
267
+ const name = meta.name || "未命名";
268
+
269
+ const metaLines: string[] = [];
270
+ if (meta.kind) {
271
+ metaLines.push(`- **类型**:${meta.kind}`);
272
+ }
273
+ if (meta.version && meta.version !== "0.0.0") {
274
+ metaLines.push(`- **版本**:${meta.version}`);
275
+ }
276
+ if (meta.author && meta.author !== "unknown") {
277
+ metaLines.push(`- **作者**:${meta.author}`);
278
+ }
279
+ if (meta.description) {
280
+ metaLines.push(`- **描述**:${meta.description}`);
281
+ }
282
+
283
+ const parts: string[] = [`# ${name}`, ""];
284
+ if (metaLines.length > 0) {
285
+ parts.push(metaLines.join("\n"), "");
286
+ }
287
+ if (body.trim()) {
288
+ parts.push(body.trim());
289
+ }
290
+
291
+ return parts.join("\n") + "\n";
292
+ }
293
+
294
+ // =====================================================================
295
+ // 路径工具
296
+ // =====================================================================
297
+
298
+ export const PROFILE_FILENAME = "PROFILE.md";
299
+
300
+ /**
301
+ * 拼出 profile 文件路径。约定:<dataDir>/profile/PROFILE.md。
302
+ */
303
+ export function getProfilePath(dataDir: string): string {
304
+ return join(dataDir, "profile", PROFILE_FILENAME);
305
+ }