@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
@@ -0,0 +1,153 @@
1
+ // src/persona-init.ts
2
+ // 从用户描述生成大五人格(OCEAN)JSON
3
+ //
4
+ // 用户说一句话(如"一个像苏格拉底那样的智者")→ LLM 推断 5 维数值 + 自由文本偏好
5
+ // 失败时降级为默认 OCEAN(0.5)+ 通用 preferences
6
+
7
+ import type { ModelProvider } from "./provider.ts";
8
+ import {
9
+ defaultPersona,
10
+ oceanHint,
11
+ savePersonaForSession,
12
+ validateOCEAN,
13
+ validatePersona,
14
+ type BigFivePersona,
15
+ type OCEAN,
16
+ } from "./bigfive.ts";
17
+
18
+ const INIT_SYSTEM_PROMPT = `你是"大五人格(Big Five / OCEAN)"分析器。
19
+ 用户用一句话描述想要的人格,你把它转成 5 维数值 + 自由文本偏好。
20
+
21
+ **5 维(每项 0.00-1.00,保留 2 位小数)**:
22
+ - **openness**(开放性):想象力、好奇心、抽象思维
23
+ - 低(0.0-0.3):偏好熟悉、具体、实用的内容
24
+ - 中(0.3-0.7):能接受新想法但不主动探索
25
+ - 高(0.7-1.0):喜欢新想法、抽象概念、跨领域联想
26
+ - **conscientiousness**(尽责性):条理性、自律、可靠
27
+ - 低:回复随性、跳跃
28
+ - 中:偶尔组织
29
+ - 高:条理清晰、先组织再表达
30
+ - **extraversion**(外向性):热情、健谈、活跃
31
+ - 低:偏好安静、内敛
32
+ - 中:根据话题调整
33
+ - 高:热情、主动扩展话题
34
+ - **agreeableness**(宜人性):信任、合作、利他
35
+ - 低:直接挑战而非迁就
36
+ - 中:能共情也直接表达不同意见
37
+ - 高:温和、不对抗、善于共情
38
+ - **neuroticism**(神经质):情绪敏感、焦虑
39
+ - 低:情绪稳定、冷静
40
+ - 中:偶尔情绪化但大体稳定
41
+ - 高:易波动、对压力反应强
42
+
43
+ **preferences**(自由文本,1-2 句话):把用户描述翻译成"这个角色说话会怎么说话"的行为倾向。例如:
44
+ - "用具体例子而非抽象概念"
45
+ - "说话带黑色幽默但不刻薄"
46
+ - "喜欢引用历史典故"
47
+ - "不主动开玩笑但会接梗"
48
+
49
+ **输出严格 JSON**(无任何前言):
50
+ {
51
+ "ocean": {
52
+ "openness": 0.0-1.0,
53
+ "conscientiousness": 0.0-1.0,
54
+ "extraversion": 0.0-1.0,
55
+ "agreeableness": 0.0-1.0,
56
+ "neuroticism": 0.0-1.0
57
+ },
58
+ "preferences": "..."
59
+ }`;
60
+
61
+ export type GenerateOptions = {
62
+ /** 用户描述(中文/英文都可以) */
63
+ description: string;
64
+ sessionId: string;
65
+ signal?: AbortSignal;
66
+ };
67
+
68
+ /**
69
+ * 从用户描述生成 BigFivePersona,保存到 data/personality/{sessionId}.json。
70
+ *
71
+ * 失败时(LLM 调用失败 / JSON 解析失败)降级为默认 OCEAN(0.5)+ 通用 preferences。
72
+ */
73
+ export async function initPersonaFromDescription(
74
+ provider: ModelProvider,
75
+ options: GenerateOptions,
76
+ dataDir: string,
77
+ ): Promise<BigFivePersona> {
78
+ const fallback = defaultPersona(options.sessionId);
79
+
80
+ let parsed: BigFivePersona;
81
+ try {
82
+ const raw = await provider.complete({
83
+ model: provider.model,
84
+ params: {
85
+ system: INIT_SYSTEM_PROMPT,
86
+ messages: [
87
+ {
88
+ role: "user",
89
+ content: `请基于这个描述生成大五人格:\n"""${options.description}"""`,
90
+ },
91
+ ],
92
+ maxTokens: 500,
93
+ temperature: 0.4,
94
+ signal: options.signal,
95
+ },
96
+ });
97
+
98
+ parsed = parseInitOutput(raw, options.sessionId);
99
+ } catch (err) {
100
+ // LLM 调用失败:降级为默认
101
+ parsed = { ...fallback, preferences: `(人设生成失败:${(err as Error).message.slice(0, 50)})${fallback.preferences}` };
102
+ }
103
+
104
+ savePersonaForSession(dataDir, parsed);
105
+ return parsed;
106
+ }
107
+
108
+ /** 解析 LLM 输出为 BigFivePersona */
109
+ export function parseInitOutput(raw: string, sessionId: string): BigFivePersona {
110
+ const fallback = defaultPersona(sessionId);
111
+
112
+ // 提取 JSON
113
+ let text = raw.trim();
114
+ text = text.replace(/^```(?:json)?\n?/i, "").replace(/\n?```\s*$/i, "").trim();
115
+ const objMatch = text.match(/\{[\s\S]*\}/);
116
+ if (!objMatch) return fallback;
117
+
118
+ let parsed: any;
119
+ try {
120
+ parsed = JSON.parse(objMatch[0]);
121
+ } catch {
122
+ return fallback;
123
+ }
124
+
125
+ // 不依赖 validatePersona:直接尝试读取 ocean 字段
126
+ // 不存在 → 用 fallback;存在 → 数值 clamp 到 0-1
127
+ const oceanIn = parsed?.ocean;
128
+ if (!oceanIn || typeof oceanIn !== "object") return fallback;
129
+
130
+ const ocean: OCEAN = {
131
+ openness: clampOcean(oceanIn.openness),
132
+ conscientiousness: clampOcean(oceanIn.conscientiousness),
133
+ extraversion: clampOcean(oceanIn.extraversion),
134
+ agreeableness: clampOcean(oceanIn.agreeableness),
135
+ neuroticism: clampOcean(oceanIn.neuroticism),
136
+ };
137
+
138
+ return {
139
+ sessionId,
140
+ ocean,
141
+ preferences: parsed.preferences?.trim() || fallback.preferences,
142
+ createdAt: Date.now(),
143
+ updatedAt: Date.now(),
144
+ };
145
+ }
146
+
147
+ function clampOcean(v: number): number {
148
+ if (typeof v !== "number" || isNaN(v)) return 0.5;
149
+ return Math.round(Math.max(0, Math.min(1, v)) * 100) / 100;
150
+ }
151
+
152
+ // Re-export oceanHint for convenience
153
+ export { oceanHint };
@@ -0,0 +1,349 @@
1
+ // src/persona-learner.ts
2
+ // 真正开放的人设学习器
3
+ //
4
+ // 上一版用预定义枚举(length/tone/depth/format)记录偏好。
5
+ // 新版用完全开放的自由文本观察 + 具体对话示例:
6
+ // - positivePatterns: LLM 自由描述的"用户喜欢什么"
7
+ // - negativePatterns: LLM 自由描述的"用户不喜欢什么"
8
+ // - positiveExamples / negativeExamples: 具体对话示例(in-context learning)
9
+ //
10
+ // 存储:data/learned-prefs/{userId}.json
11
+ // 每用户独立(简化为 userId="default")
12
+
13
+ import { join } from "node:path";
14
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
15
+ import type { ModelProvider } from "./provider.ts";
16
+ import type { ConversationExample, FeedbackSignal } from "./feedback-detector.ts";
17
+
18
+ export const SCHEMA_VERSION = 2;
19
+
20
+ /** 软上限:超过会触发后台合并 */
21
+ export const SOFT_CAP_POSITIVE = 15;
22
+ export const SOFT_CAP_NEGATIVE = 15;
23
+
24
+ /** 硬上限:保留最近 N 条(防止 prompt 撑爆) */
25
+ export const HARD_CAP_PATTERNS = 20;
26
+ export const HARD_CAP_EXAMPLES = 5;
27
+
28
+ /** 文本长度上限 */
29
+ const MAX_INSIGHT_LEN = 200;
30
+ const MAX_REASON_LEN = 100;
31
+ const MAX_EXAMPLE_USER_LEN = 500;
32
+ const MAX_EXAMPLE_AI_LEN = 500;
33
+ const MAX_EXAMPLE_NOTE_LEN = 200;
34
+
35
+ export type LearnerState = {
36
+ userId: string;
37
+ version: number;
38
+
39
+ /** 信号计数(debug/可观测用,不进 prompt) */
40
+ signalCounts: {
41
+ positive: number;
42
+ negative: number;
43
+ neutral: number;
44
+ };
45
+
46
+ /** 自由文本偏好观察(核心:完全开放,无预设维度) */
47
+ positivePatterns: string[];
48
+ negativePatterns: string[];
49
+
50
+ /** 具体对话示例(强信号:给 LLM 看什么是好回复) */
51
+ positiveExamples: ConversationExample[];
52
+ negativeExamples: ConversationExample[];
53
+
54
+ /** 最近反馈原因(debug 用) */
55
+ recentReasons: { signal: FeedbackSignal; text: string; at: number }[];
56
+
57
+ createdAt: number;
58
+ updatedAt: number;
59
+ };
60
+
61
+ export function emptyState(userId: string): LearnerState {
62
+ const now = Date.now();
63
+ return {
64
+ userId,
65
+ version: SCHEMA_VERSION,
66
+ signalCounts: { positive: 0, negative: 0, neutral: 0 },
67
+ positivePatterns: [],
68
+ negativePatterns: [],
69
+ positiveExamples: [],
70
+ negativeExamples: [],
71
+ recentReasons: [],
72
+ createdAt: now,
73
+ updatedAt: now,
74
+ };
75
+ }
76
+
77
+ function prefsFile(dataDir: string, userId: string): string {
78
+ return join(dataDir, "learned-prefs", `${userId}.json`);
79
+ }
80
+
81
+ /**
82
+ * 加载 learner state。
83
+ * - 文件不存在:返回空状态
84
+ * - 老版本(version < SCHEMA_VERSION 或缺关键字段):返回空状态(数据丢弃)
85
+ */
86
+ export function loadLearner(dataDir: string, userId: string): LearnerState {
87
+ const path = prefsFile(dataDir, userId);
88
+ if (!existsSync(path)) {
89
+ return emptyState(userId);
90
+ }
91
+ try {
92
+ const raw = readFileSync(path, "utf-8");
93
+ const parsed = JSON.parse(raw) as LearnerState;
94
+
95
+ // 版本检查:老 schema 数据直接丢弃
96
+ if (parsed.version !== SCHEMA_VERSION) {
97
+ return emptyState(userId);
98
+ }
99
+
100
+ // 兼容性:补全缺失字段
101
+ if (!parsed.signalCounts) {
102
+ parsed.signalCounts = { positive: 0, negative: 0, neutral: 0 };
103
+ }
104
+ if (!Array.isArray(parsed.positivePatterns)) parsed.positivePatterns = [];
105
+ if (!Array.isArray(parsed.negativePatterns)) parsed.negativePatterns = [];
106
+ if (!Array.isArray(parsed.positiveExamples)) parsed.positiveExamples = [];
107
+ if (!Array.isArray(parsed.negativeExamples)) parsed.negativeExamples = [];
108
+ if (!Array.isArray(parsed.recentReasons)) parsed.recentReasons = [];
109
+
110
+ return parsed;
111
+ } catch {
112
+ return emptyState(userId);
113
+ }
114
+ }
115
+
116
+ export function saveLearner(dataDir: string, state: LearnerState): void {
117
+ const path = prefsFile(dataDir, state.userId);
118
+ mkdirSync(join(dataDir, "learned-prefs"), { recursive: true });
119
+ state.updatedAt = Date.now();
120
+ writeFileSync(path, JSON.stringify(state, null, 2), "utf-8");
121
+ }
122
+
123
+ export function resetLearner(dataDir: string, userId: string): LearnerState {
124
+ const fresh = emptyState(userId);
125
+ saveLearner(dataDir, fresh);
126
+ return fresh;
127
+ }
128
+
129
+ /**
130
+ * 把一次反馈应用到 learner state。
131
+ *
132
+ * @param state 当前状态
133
+ * @param signal positive / negative / neutral
134
+ * @param insights LLM 自由文本观察的列表(不限词汇)
135
+ * @param example 可选的具体对话示例
136
+ */
137
+ export function applyFeedback(
138
+ state: LearnerState,
139
+ signal: FeedbackSignal,
140
+ insights: string[] = [],
141
+ example?: ConversationExample,
142
+ ): LearnerState {
143
+ const next: LearnerState = JSON.parse(JSON.stringify(state));
144
+ next.version = SCHEMA_VERSION;
145
+
146
+ // 信号计数
147
+ next.signalCounts[signal]++;
148
+
149
+ // 自由文本偏好观察
150
+ const cleanedInsights = insights
151
+ .filter((s) => typeof s === "string" && s.trim())
152
+ .map((s) => s.trim().slice(0, MAX_INSIGHT_LEN));
153
+
154
+ if (signal === "positive") {
155
+ next.positivePatterns.push(...cleanedInsights);
156
+ // 硬上限:保留最近 N 条
157
+ if (next.positivePatterns.length > HARD_CAP_PATTERNS) {
158
+ next.positivePatterns = next.positivePatterns.slice(-HARD_CAP_PATTERNS);
159
+ }
160
+ } else if (signal === "negative") {
161
+ next.negativePatterns.push(...cleanedInsights);
162
+ if (next.negativePatterns.length > HARD_CAP_PATTERNS) {
163
+ next.negativePatterns = next.negativePatterns.slice(-HARD_CAP_PATTERNS);
164
+ }
165
+ }
166
+ // neutral: 只累加 signalCounts,不存 patterns
167
+
168
+ // 具体对话示例
169
+ if (example && (signal === "positive" || signal === "negative")) {
170
+ const ex: ConversationExample = {
171
+ userMessage: (example.userMessage ?? "").slice(0, MAX_EXAMPLE_USER_LEN),
172
+ aiReply: (example.aiReply ?? "").slice(0, MAX_EXAMPLE_AI_LEN),
173
+ };
174
+ if (signal === "positive" && example.whyWorked) {
175
+ ex.whyWorked = example.whyWorked.slice(0, MAX_EXAMPLE_NOTE_LEN);
176
+ }
177
+ if (signal === "negative" && example.whyDidntWork) {
178
+ ex.whyDidntWork = example.whyDidntWork.slice(0, MAX_EXAMPLE_NOTE_LEN);
179
+ }
180
+
181
+ if (signal === "positive") {
182
+ next.positiveExamples.push(ex);
183
+ if (next.positiveExamples.length > HARD_CAP_EXAMPLES) {
184
+ next.positiveExamples = next.positiveExamples.slice(-HARD_CAP_EXAMPLES);
185
+ }
186
+ } else {
187
+ next.negativeExamples.push(ex);
188
+ if (next.negativeExamples.length > HARD_CAP_EXAMPLES) {
189
+ next.negativeExamples = next.negativeExamples.slice(-HARD_CAP_EXAMPLES);
190
+ }
191
+ }
192
+ }
193
+
194
+ // recentReasons(debug 用)
195
+ if (insights.length > 0 || signal !== "neutral") {
196
+ next.recentReasons.push({
197
+ signal,
198
+ text: insights.slice(0, 3).join("; ").slice(0, MAX_REASON_LEN),
199
+ at: Date.now(),
200
+ });
201
+ if (next.recentReasons.length > 20) {
202
+ next.recentReasons = next.recentReasons.slice(-20);
203
+ }
204
+ }
205
+
206
+ next.updatedAt = Date.now();
207
+ return next;
208
+ }
209
+
210
+ /**
211
+ * 总反馈数(用于判断是否冷启动)
212
+ */
213
+ export function totalFeedback(state: LearnerState): number {
214
+ return (
215
+ state.signalCounts.positive +
216
+ state.signalCounts.negative +
217
+ state.signalCounts.neutral
218
+ );
219
+ }
220
+
221
+ /**
222
+ * 判断是否需要触发合并
223
+ */
224
+ export function needsMerge(state: LearnerState): boolean {
225
+ return (
226
+ state.positivePatterns.length > SOFT_CAP_POSITIVE ||
227
+ state.negativePatterns.length > SOFT_CAP_NEGATIVE
228
+ );
229
+ }
230
+
231
+ /**
232
+ * 把 learner state 转换成动态 persona 文本。
233
+ *
234
+ * 设计原则(v0.19 移除硬风格版):
235
+ * - 不注入角色身份声明("你是一个真实的人…")和"核心原则"段
236
+ * 让 LLM 按默认风格回复,偏好应该从对话中通过反馈循环自然长出来
237
+ * - 输出只包括用户实际反馈累积的 patterns 和 examples
238
+ *
239
+ * 冷启动:无任何数据时返回**空字符串**,不污染 system prompt。
240
+ */
241
+ export function buildDynamicPersona(state: LearnerState): string {
242
+ const lines: string[] = [];
243
+
244
+ // 自由文本偏好观察
245
+ if (state.positivePatterns.length > 0) {
246
+ lines.push("【这个用户过去喜欢的(学习这些)】");
247
+ for (const p of state.positivePatterns.slice(-10)) {
248
+ lines.push(`- ${p}`);
249
+ }
250
+ }
251
+
252
+ if (state.negativePatterns.length > 0) {
253
+ if (lines.length > 0) lines.push("");
254
+ lines.push("【这个用户过去不喜欢的(避免)】");
255
+ for (const p of state.negativePatterns.slice(-10)) {
256
+ lines.push(`- ${p}`);
257
+ }
258
+ }
259
+
260
+ // 具体对话示例(in-context demonstration)
261
+ // 正例取最近 2 个,负例取最近 1 个
262
+ const posEx = state.positiveExamples.slice(-2);
263
+ if (posEx.length > 0) {
264
+ if (lines.length > 0) lines.push("");
265
+ lines.push("【过去用户明确满意的回复示例(学习这种风格)】");
266
+ for (const ex of posEx) {
267
+ lines.push(`用户:${ex.userMessage}`);
268
+ lines.push(`你:${ex.aiReply}`);
269
+ if (ex.whyWorked) {
270
+ lines.push(`原因:${ex.whyWorked}`);
271
+ }
272
+ lines.push("---");
273
+ }
274
+ }
275
+
276
+ const negEx = state.negativeExamples.slice(-1);
277
+ if (negEx.length > 0) {
278
+ if (lines.length > 0) lines.push("");
279
+ lines.push("【要避免的回复(用户不满意)】");
280
+ for (const ex of negEx) {
281
+ lines.push(`用户:${ex.userMessage}`);
282
+ lines.push(`你:${ex.aiReply}`);
283
+ if (ex.whyDidntWork) {
284
+ lines.push(`原因:${ex.whyDidntWork}`);
285
+ }
286
+ lines.push("---");
287
+ }
288
+ }
289
+
290
+ return lines.join("\n");
291
+ }
292
+
293
+ /**
294
+ * 后台合并相似 patterns(防止冗余累积)
295
+ *
296
+ * @param provider LLM provider
297
+ * @param patterns 当前 patterns 列表
298
+ * @param signal positive 或 negative(用于 prompt 上下文)
299
+ * @returns 合并后的 patterns 列表
300
+ */
301
+ export async function mergePatterns(
302
+ provider: ModelProvider,
303
+ patterns: string[],
304
+ signal: FeedbackSignal,
305
+ signal2?: AbortSignal,
306
+ ): Promise<string[]> {
307
+ if (patterns.length <= 10) return patterns;
308
+
309
+ const userPrompt = `合并以下用户偏好的自由文本描述,去重、保留核心、合并相似项。
310
+
311
+ 当前 ${signal === "positive" ? "用户喜欢" : "用户不喜欢"} 的列表:
312
+ ${patterns.map((p, i) => `${i + 1}. ${p}`).join("\n")}
313
+
314
+ 要求:
315
+ - 合并语义重复的(例如"用户喜欢例子"和"用户希望先举例"→ 合并)
316
+ - 删除完全重复的
317
+ - 保留有差异的细节
318
+ - 输出合并后的列表(JSON 数组,每项一句话)
319
+ - 最多保留 10 条
320
+ - 只输出 JSON 数组,不要其他文字`;
321
+
322
+ try {
323
+ const raw = await provider.complete({
324
+ model: provider.model,
325
+ params: {
326
+ system: "你是文本去重合并助手。输出严格 JSON 数组。",
327
+ messages: [{ role: "user", content: userPrompt }],
328
+ maxTokens: 800,
329
+ temperature: 0.2,
330
+ signal: signal2,
331
+ },
332
+ });
333
+
334
+ // 解析 JSON 数组
335
+ const text = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim();
336
+ const match = text.match(/\[[\s\S]*\]/);
337
+ if (!match) return patterns;
338
+
339
+ const parsed = JSON.parse(match[0]);
340
+ if (Array.isArray(parsed)) {
341
+ return parsed
342
+ .filter((s): s is string => typeof s === "string" && Boolean(s.trim()))
343
+ .map((s: string) => s.trim().slice(0, MAX_INSIGHT_LEN));
344
+ }
345
+ return patterns;
346
+ } catch {
347
+ return patterns;
348
+ }
349
+ }