@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.
Files changed (44) hide show
  1. package/ARCHITECTURE.md +787 -0
  2. package/LICENSE +201 -0
  3. package/README.en.md +441 -0
  4. package/README.md +459 -2
  5. package/dist/mcp/index.js +37287 -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 +43 -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 +239 -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 +1008 -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.ts +624 -0
@@ -0,0 +1,557 @@
1
+ // src/proactive.ts
2
+ // 主动发起对话系统。
3
+ //
4
+ // 设计目标:
5
+ // - 当用户长时间未交互(idle > 阈值),系统可主动发一条消息
6
+ // - 内容基于 profile + 近期 memory + emotion patterns,不是随机寒暄
7
+ // - 每天最多 1-2 次,避开深夜时段
8
+ // - 主动消息有标记,区别于用户触发的回复
9
+ //
10
+ // 触发流程(v0.7 MVP:基于 REPL 启动时机):
11
+ // REPL 启动 → 加载 proactive state → 检查 shouldTriggerProactive
12
+ // → 满足条件:side-query 生成消息 → 打印给用户([💡 主动] 前缀)
13
+ // → 记录 lastProactiveAt / todayCount++
14
+ // → 每轮 turn 后记录 lastUserActivityAt
15
+ //
16
+ // 注:v0.7 没有真正的后台 cron(需要常驻进程)。
17
+ // 真实场景需要把"主动消息生成"和"投递"分离——生成可在任意时刻跑(用 systemd timer / launchd),
18
+ // 投递检查可在 REPL 启动 / 用户活跃时做。本版本做的是简化版。
19
+
20
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
21
+ import { existsSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import type { ModelProvider } from "./provider.ts";
24
+ import type { Profile } from "./profile.ts";
25
+ import type { Timeline } from "./timeline.ts";
26
+
27
+ // 不再依赖 personality.ts(人格由 persona-learner 动态生成)。
28
+ // proactive 模块只需要 name + description 字段,本地定义最小接口。
29
+ type PersonaLite = { name: string; description?: string };
30
+ type Personality = PersonaLite;
31
+ import {
32
+ scanMemory,
33
+ formatManifest,
34
+ type MemoryFile,
35
+ } from "./memory.ts";
36
+
37
+ // =====================================================================
38
+ // 配置
39
+ // =====================================================================
40
+
41
+ export type ProactiveConfig = {
42
+ /** 总开关 */
43
+ enabled: boolean;
44
+ /** 静默阈值(小时)—— 距上次用户活动超过此时间可能触发 */
45
+ idleThresholdHours: number;
46
+ /** 每日最大主动消息数 */
47
+ maxPerDay: number;
48
+ /** 安静时段(小时 24h 制,可跨午夜,如 23-8) */
49
+ quietHours: { start: number; end: number };
50
+ /** 距上次主动消息的最小间隔(分钟)—— 防止短时间内连发 */
51
+ cooldownMinutes: number;
52
+ };
53
+
54
+ export const DEFAULT_PROACTIVE_CONFIG: ProactiveConfig = {
55
+ enabled: true,
56
+ idleThresholdHours: 4,
57
+ maxPerDay: 2,
58
+ quietHours: { start: 23, end: 8 },
59
+ cooldownMinutes: 60,
60
+ };
61
+
62
+ // =====================================================================
63
+ // 状态
64
+ // =====================================================================
65
+
66
+ export type ProactiveState = {
67
+ /** 上次用户活动时间(消息或启动)的 ms 时间戳 */
68
+ lastUserActivityAt: number;
69
+ /** 上次主动消息时间的 ms 时间戳 */
70
+ lastProactiveAt: number;
71
+ /** 今日已发数量 */
72
+ todayCount: number;
73
+ /** 今日日期 YYYY-MM-DD(本地) */
74
+ todayDate: string;
75
+ };
76
+
77
+ export const PROACTIVE_STATE_FILENAME = "proactive-state.json";
78
+
79
+ export function getProactiveStatePath(dataDir: string): string {
80
+ return join(dataDir, PROACTIVE_STATE_FILENAME);
81
+ }
82
+
83
+ export async function loadProactiveState(
84
+ dataDir: string,
85
+ ): Promise<ProactiveState> {
86
+ const path = getProactiveStatePath(dataDir);
87
+ if (!existsSync(path)) {
88
+ return {
89
+ lastUserActivityAt: 0,
90
+ lastProactiveAt: 0,
91
+ todayCount: 0,
92
+ todayDate: "",
93
+ };
94
+ }
95
+ try {
96
+ const raw = await readFile(path, "utf-8");
97
+ const parsed = JSON.parse(raw) as Partial<ProactiveState>;
98
+ return {
99
+ lastUserActivityAt: parsed.lastUserActivityAt ?? 0,
100
+ lastProactiveAt: parsed.lastProactiveAt ?? 0,
101
+ todayCount: parsed.todayCount ?? 0,
102
+ todayDate: parsed.todayDate ?? "",
103
+ };
104
+ } catch {
105
+ return {
106
+ lastUserActivityAt: 0,
107
+ lastProactiveAt: 0,
108
+ todayCount: 0,
109
+ todayDate: "",
110
+ };
111
+ }
112
+ }
113
+
114
+ export async function saveProactiveState(
115
+ dataDir: string,
116
+ state: ProactiveState,
117
+ ): Promise<void> {
118
+ const path = getProactiveStatePath(dataDir);
119
+ await mkdir(dataDir, { recursive: true });
120
+ await writeFile(path, JSON.stringify(state, null, 2), "utf-8");
121
+ }
122
+
123
+ // =====================================================================
124
+ // 时间辅助
125
+ // =====================================================================
126
+
127
+ /**
128
+ * 本地日期 YYYY-MM-DD(用本地时区,不用 UTC,避免跨日混乱)。
129
+ */
130
+ export function todayLocal(now: Date = new Date()): string {
131
+ const y = now.getFullYear();
132
+ const m = String(now.getMonth() + 1).padStart(2, "0");
133
+ const d = String(now.getDate()).padStart(2, "0");
134
+ return `${y}-${m}-${d}`;
135
+ }
136
+
137
+ /**
138
+ * 判断当前小时是否在安静时段。
139
+ * 支持跨午夜(start > end,如 23-8):
140
+ * - 23-8 跨午夜:hour=23 → 在;hour=0 → 在;hour=10 → 不在
141
+ * - 13-18 不跨:hour=15 → 在;hour=10 → 不在
142
+ */
143
+ export function isQuietHour(
144
+ hour: number,
145
+ quietHours: { start: number; end: number },
146
+ ): boolean {
147
+ const { start, end } = quietHours;
148
+ if (start <= end) {
149
+ return hour >= start && hour < end;
150
+ }
151
+ // 跨午夜
152
+ return hour >= start || hour < end;
153
+ }
154
+
155
+ // =====================================================================
156
+ // 触发决策
157
+ // =====================================================================
158
+
159
+ export type TriggerDecision = {
160
+ should: boolean;
161
+ reason:
162
+ | "disabled"
163
+ | "daily_limit"
164
+ | "quiet_hour"
165
+ | "not_idle_long_enough"
166
+ | "cooldown"
167
+ | "ok";
168
+ };
169
+
170
+ /**
171
+ * 决定是否应该主动发起消息。
172
+ *
173
+ * 5 个条件(AND):
174
+ * 1. enabled
175
+ * 2. todayCount < maxPerDay(新的一天重置)
176
+ * 3. 当前时间不在 quietHours
177
+ * 4. 距上次用户活动 >= idleThresholdHours(如果 lastUserActivityAt > 0)
178
+ * 5. 距上次主动消息 >= cooldownMinutes(如果 lastProactiveAt > 0)
179
+ *
180
+ * 注意:当 lastUserActivityAt === 0(首次启动),跳过条件 4(视为一直空闲)。
181
+ */
182
+ export function shouldTriggerProactive(
183
+ state: ProactiveState,
184
+ config: ProactiveConfig,
185
+ now: Date = new Date(),
186
+ ): TriggerDecision {
187
+ if (!config.enabled) {
188
+ return { should: false, reason: "disabled" };
189
+ }
190
+
191
+ const today = todayLocal(now);
192
+ const effectiveCount = state.todayDate === today ? state.todayCount : 0;
193
+ if (effectiveCount >= config.maxPerDay) {
194
+ return { should: false, reason: "daily_limit" };
195
+ }
196
+
197
+ const hour = now.getHours();
198
+ if (isQuietHour(hour, config.quietHours)) {
199
+ return { should: false, reason: "quiet_hour" };
200
+ }
201
+
202
+ // 静默阈值:只有曾经有过用户活动时才检查(首次启动跳过)
203
+ if (state.lastUserActivityAt > 0) {
204
+ const idleMs = now.getTime() - state.lastUserActivityAt;
205
+ if (idleMs < config.idleThresholdHours * 3600 * 1000) {
206
+ return { should: false, reason: "not_idle_long_enough" };
207
+ }
208
+ }
209
+
210
+ // Cooldown
211
+ if (state.lastProactiveAt > 0) {
212
+ const sinceProactiveMs = now.getTime() - state.lastProactiveAt;
213
+ if (sinceProactiveMs < config.cooldownMinutes * 60 * 1000) {
214
+ return { should: false, reason: "cooldown" };
215
+ }
216
+ }
217
+
218
+ return { should: true, reason: "ok" };
219
+ }
220
+
221
+ // =====================================================================
222
+ // 状态更新辅助
223
+ // =====================================================================
224
+
225
+ /**
226
+ * 记录一次主动消息已发出。
227
+ */
228
+ export function recordProactiveSent(
229
+ state: ProactiveState,
230
+ now: Date = new Date(),
231
+ ): void {
232
+ const today = todayLocal(now);
233
+ state.lastProactiveAt = now.getTime();
234
+ state.todayCount = state.todayDate === today ? state.todayCount + 1 : 1;
235
+ state.todayDate = today;
236
+ }
237
+
238
+ /**
239
+ * 记录用户活动(消息发送 / 启动 REPL)。
240
+ */
241
+ export function recordUserActivity(
242
+ state: ProactiveState,
243
+ now: Date = new Date(),
244
+ ): void {
245
+ state.lastUserActivityAt = now.getTime();
246
+ }
247
+
248
+ // =====================================================================
249
+ // 主动消息生成(side-query)
250
+ // =====================================================================
251
+
252
+ const PROACTIVE_SYSTEM_PROMPT = `你是 [PERSONALITY_NAME],[PERSONALITY_DESCRIPTION]。
253
+
254
+ 现在需要你主动给用户发一条消息。这不是回应用户的提问,是你(人格)主动想起用户、想关心一下。
255
+
256
+ **严格基于以下上下文**生成:
257
+ {context}
258
+
259
+ # 最重要的红线(绝对不能违反)
260
+
261
+ 1. **绝对不能编造**——上下文中没有的东西,**绝对不能提**。例如:
262
+ - 上下文中没有提到养猫,**绝对不能**说"饺子今天怎么样"
263
+ - 上下文中没有提到工作内容,**绝对不能**说"那个报告写完了吗"
264
+ - 上下文中没有提到任何具体人/事/物,**绝对不能**凭空引用
265
+ 2. **只能引用上下文中出现过的具体内容**——人物名字、事件、情绪、偏好、话题
266
+ 3. 如果上下文中**没有足够内容**生成有意义的消息(都是"(暂无)"或空),直接说"想你了,最近还好吗?"这种**无具体引用**但**不编造**的话
267
+ 4. **绝不能**为了"显得关心"而编造细节——宁可短而空,也不能假
268
+
269
+ # 风格要求
270
+
271
+ 1. **简短**——≤ 80 字
272
+ 2. **语气**:符合人格(如果人格是"小阳",就用他的轻松语气;如果是"教练",就直接)
273
+ 3. **不要问太多问题**——一两个就够
274
+ 4. **不要重复最近对话的内容**——这是新的开场,不是回顾
275
+ 5. **结尾自然**——让用户可以选择接或不接
276
+
277
+ 格式:直接输出消息内容,不要 Markdown 标题或前缀`;
278
+
279
+ export type ProactiveContext = {
280
+ profile: Profile | null;
281
+ memories: MemoryFile[];
282
+ timelineSummary: string;
283
+ personalityName: string;
284
+ personalityDescription: string;
285
+ };
286
+
287
+ function buildContextText(ctx: ProactiveContext): string {
288
+ const parts: string[] = [];
289
+ if (ctx.profile) {
290
+ const sectionEntries = Object.entries(ctx.profile.sections);
291
+ const nonEmpty = sectionEntries.filter(([_, body]) => {
292
+ const trimmed = body.trim();
293
+ return trimmed && !trimmed.startsWith("(暂无");
294
+ });
295
+ if (nonEmpty.length > 0) {
296
+ parts.push("## 用户画像");
297
+ for (const [name, body] of nonEmpty) {
298
+ parts.push(`### ${name}\n${body.trim()}`);
299
+ }
300
+ }
301
+ }
302
+ if (ctx.memories.length > 0) {
303
+ parts.push("\n## 近期记忆(最近 5 条)");
304
+ parts.push(formatManifest(ctx.memories.slice(0, 5)));
305
+ }
306
+ if (ctx.timelineSummary) {
307
+ parts.push("\n## 近期情绪");
308
+ parts.push(ctx.timelineSummary);
309
+ }
310
+ return parts.join("\n");
311
+ }
312
+
313
+ /**
314
+ * 从 profile / memory / timeline 提取所有"可引用关键词",
315
+ * 用于检测生成的消息是否真的引用了上下文。
316
+ */
317
+ export function extractContextKeywords(ctx: ProactiveContext): Set<string> {
318
+ const keywords = new Set<string>();
319
+ const chineseStopwords = new Set([
320
+ "的", "了", "在", "是", "我", "你", "他", "她", "它", "我们", "你们", "他们",
321
+ "和", "与", "或", "但", "而", "就", "都", "也", "还", "又", "才", "要",
322
+ "一个", "一些", "什么", "怎么", "为什么", "怎样", "哪里", "哪个",
323
+ "今天", "昨天", "明天", "现在", "以前", "以后",
324
+ "啊", "嗯", "哦", "呢", "吧", "嘛", "哈", "嘿", "呀", "啦",
325
+ "很", "太", "非常", "特别", "比较", "更", "最",
326
+ ]);
327
+
328
+ const addWords = (text: string) => {
329
+ // 2+ 字的连续中文字符串
330
+ const matches = text.match(/[一-龥]{2,}/g) || [];
331
+ for (const m of matches) {
332
+ if (m.length > 2) {
333
+ // 长串拆成 2-字滑窗(避免 "跟妈的关系" 整段当成 1 个关键词)
334
+ for (let i = 0; i < m.length - 1; i++) {
335
+ const sub = m.slice(i, i + 2);
336
+ if (!chineseStopwords.has(sub)) keywords.add(sub);
337
+ }
338
+ } else {
339
+ if (!chineseStopwords.has(m)) keywords.add(m);
340
+ }
341
+ }
342
+ // 数字
343
+ const nums = text.match(/\d+/g) || [];
344
+ for (const n of nums) keywords.add(n);
345
+ // 英文 4+ 字符
346
+ const en = text.match(/[a-zA-Z]{4,}/g) || [];
347
+ for (const e of en) keywords.add(e.toLowerCase());
348
+ };
349
+
350
+ if (ctx.profile) {
351
+ for (const body of Object.values(ctx.profile.sections)) {
352
+ addWords(body);
353
+ }
354
+ }
355
+ for (const mem of ctx.memories) {
356
+ addWords(mem.name + " " + mem.description + " " + mem.body);
357
+ }
358
+ if (ctx.timelineSummary) {
359
+ addWords(ctx.timelineSummary);
360
+ }
361
+
362
+ return keywords;
363
+ }
364
+
365
+ /**
366
+ * 验证生成的消息是否真的引用了上下文。
367
+ *
368
+ * 算法:消息中至少要包含 1 个从上下文提取的关键词(长度 >= 2)。
369
+ * 短句模板(如"想你了,最近还好吗?")也会通过——因为不编造就 OK。
370
+ */
371
+ export function validateProactiveMessage(
372
+ message: string,
373
+ ctx: ProactiveContext,
374
+ ): { valid: boolean; reason: string; matchedKeywords: string[] } {
375
+ const keywords = extractContextKeywords(ctx);
376
+
377
+ // 收集消息中所有"具体词"(中文 2-字 + 3-字 substring + 英文/数字 4+ 字符)
378
+ const specificTokens = new Set<string>();
379
+
380
+ // 中文:滑窗 2-字 + 3-字 substring
381
+ for (let i = 0; i < message.length - 1; i++) {
382
+ const sub = message.slice(i, i + 2);
383
+ if (/[一-龥]{2}/.test(sub)) specificTokens.add(sub);
384
+ }
385
+ for (let i = 0; i < message.length - 2; i++) {
386
+ const sub = message.slice(i, i + 3);
387
+ if (/[一-龥]{3}/.test(sub)) specificTokens.add(sub);
388
+ }
389
+ // 英文:3+ 字符单词
390
+ const enWords = message.match(/[a-zA-Z]{3,}/g) || [];
391
+ for (const w of enWords) specificTokens.add(w.toLowerCase());
392
+ // 数字
393
+ const nums = message.match(/\d+/g) || [];
394
+ for (const n of nums) specificTokens.add(n);
395
+
396
+ // 通用 2-字和 3-字短语(不视为具体名词)
397
+ const genericBigrams = new Set([
398
+ "你的", "你妈", "我妈", "他她", "我们", "你们", "他们",
399
+ "最近", "之前", "以后", "现在", "以前", "今天", "明天",
400
+ "怎么", "如何", "怎样", "什么", "哪样", "这个", "那个",
401
+ "好了", "完了", "觉得", "感觉", "以为", "觉得", "知道",
402
+ "想我", "想你", "想到", "突然", "一会", "一下", "一会",
403
+ "可以", "应该", "能够", "大概", "也许", "或者",
404
+ "时候", "地方", "东西", "事情", "问题", "情况", "觉得",
405
+ "一些", "这个", "那个", "这样", "那样", "怎么",
406
+ "说话", "聊天", "生活", "工作", "学习", "睡觉", "吃饭",
407
+ "今天", "明天", "后天", "早上", "晚上", "中午", "下午",
408
+ ]);
409
+ const genericTrigrams = new Set([
410
+ "想你了", "在干嘛", "还好吗", "在吗", "最近怎么样",
411
+ "吃饭了吗", "睡觉了吗", "今天怎么样",
412
+ ]);
413
+
414
+ // 过滤掉通用短语(2-字 和 3-字)
415
+ // 关键:如果 2-字 substring 完整包含在某个 3-字通用短语里,也算通用
416
+ // (例如 "想你" 和 "你了" 都在 "想你了" 里)
417
+ const genericBigramsExpanded = new Set(genericBigrams);
418
+ for (const tri of genericTrigrams) {
419
+ for (let i = 0; i < tri.length - 1; i++) {
420
+ genericBigramsExpanded.add(tri.slice(i, i + 2));
421
+ }
422
+ }
423
+ const specificSubstrings: string[] = [];
424
+ for (const tok of specificTokens) {
425
+ if (genericBigramsExpanded.has(tok) || genericTrigrams.has(tok)) continue;
426
+ specificSubstrings.push(tok);
427
+ }
428
+
429
+ // 检查每个具体词是否在 context 里
430
+ const matched: string[] = [];
431
+ for (const tok of specificSubstrings) {
432
+ if (keywords.has(tok)) {
433
+ if (!matched.includes(tok)) matched.push(tok);
434
+ }
435
+ }
436
+
437
+ // 规则 1:消息有具体词 → 至少 1 个要在 context 里
438
+ if (specificSubstrings.length > 0 && matched.length === 0) {
439
+ return {
440
+ valid: false,
441
+ reason: `消息包含具体词 [${specificSubstrings
442
+ .slice(0, 5)
443
+ .join(", ")}] 但上下文里没有 — 疑似编造`,
444
+ matchedKeywords: [],
445
+ };
446
+ }
447
+
448
+ // 规则 2:消息全是通用词("想你了"、"在吗")→ OK
449
+ if (matched.length === 0) {
450
+ return { valid: true, reason: "消息无具体引用(仅通用短语)", matchedKeywords: [] };
451
+ }
452
+
453
+ return { valid: true, reason: "引用了上下文关键词", matchedKeywords: matched };
454
+ }
455
+
456
+ /**
457
+ * 安全的 fallback 消息(绝不编造)。
458
+ */
459
+ function safeFallback(personalityName: string, hasContext: boolean): string {
460
+ if (!hasContext) {
461
+ return "想你了,最近还好吗?";
462
+ }
463
+ return "在吗?突然想到你了。";
464
+ }
465
+
466
+ /**
467
+ * 调用 LLM 生成主动消息。
468
+ *
469
+ * 关键不变量(**绝不能违反**):
470
+ * 1. 消息中提到的任何具体内容(人/事/物/数字/书名/猫名等)必须来自上下文
471
+ * 2. 如果上下文为空,**只能**用"想你了"这种无具体引用的安全 fallback
472
+ * 3. validateProactiveMessage 失败时回退到 safeFallback,**绝不**输出原 LLM 结果
473
+ *
474
+ * 失败容错:返回 safeFallback(绝不返回空字符串,避免 REPL 出错)。
475
+ */
476
+ export async function generateProactiveMessage(
477
+ provider: ModelProvider,
478
+ personality: Personality,
479
+ ctx: ProactiveContext,
480
+ ): Promise<string> {
481
+ const contextText = buildContextText(ctx);
482
+ const hasContext = contextText && contextText !== "(暂无上下文)";
483
+
484
+ // 上下文为空时直接用 fallback(不浪费 LLM 调用)
485
+ if (!hasContext) {
486
+ return safeFallback(personality.name, false);
487
+ }
488
+
489
+ const prompt = PROACTIVE_SYSTEM_PROMPT
490
+ .replace("[PERSONALITY_NAME]", personality.name)
491
+ .replace(
492
+ "[PERSONALITY_DESCRIPTION]",
493
+ personality.description || "情感陪伴对话助手",
494
+ )
495
+ .replace("{context}", contextText);
496
+
497
+ let raw = "";
498
+ try {
499
+ raw = await provider.complete({
500
+ model: provider.model,
501
+ params: {
502
+ system: prompt,
503
+ messages: [
504
+ { role: "user", content: "请基于上下文生成一条主动消息" },
505
+ ],
506
+ maxTokens: 200,
507
+ temperature: 0.7,
508
+ },
509
+ });
510
+ } catch {
511
+ return safeFallback(personality.name, true);
512
+ }
513
+
514
+ const message = raw.trim().slice(0, 500);
515
+
516
+ // 验证:消息是否真的引用了上下文?没引用就丢弃(防止编造)
517
+ const validation = validateProactiveMessage(message, ctx);
518
+ if (!validation.valid) {
519
+ console.warn(
520
+ `[proactive] 拒绝编造的消息:${message.slice(0, 50)}... 原因: ${validation.reason}`,
521
+ );
522
+ return safeFallback(personality.name, true);
523
+ }
524
+
525
+ return message;
526
+ }
527
+
528
+ // =====================================================================
529
+ // 一站式:gather context + generate
530
+ // =====================================================================
531
+
532
+ export type GatherProactiveInput = {
533
+ dataDir: string;
534
+ memoryDir: string;
535
+ timeline: Timeline;
536
+ profile: Profile | null;
537
+ personality: Personality;
538
+ };
539
+
540
+ /**
541
+ * 收集主动消息所需的所有上下文 + 调用 LLM 生成。
542
+ */
543
+ export async function prepareProactiveMessage(
544
+ provider: ModelProvider,
545
+ input: GatherProactiveInput,
546
+ ): Promise<string> {
547
+ const memories = await scanMemory(input.memoryDir);
548
+ const timelineSummary = await input.timeline.renderSummary(7);
549
+
550
+ return generateProactiveMessage(provider, input.personality, {
551
+ profile: input.profile,
552
+ memories,
553
+ timelineSummary,
554
+ personalityName: input.personality.name,
555
+ personalityDescription: input.personality.description || "",
556
+ });
557
+ }