@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
package/src/index.ts ADDED
@@ -0,0 +1,1479 @@
1
+ // src/index.ts
2
+ // REPL 入口(CLI 单会话模式 + 反馈学习)
3
+ //
4
+ // 命令:
5
+ // /memory save <type> <name> <description> - 保存一条记忆
6
+ // /memory list - 列出所有记忆
7
+ // /memory read <filename> - 读记忆详情
8
+ // /timeline - 看情绪轨迹
9
+ // /timeline stats - 看情绪统计
10
+ // /learner - 看人设学习器状态
11
+ // /learner reset - 重置学习器(清空反馈)
12
+ // /stats - 会话统计
13
+ // /clear - 清空会话历史
14
+ // /help - 帮助
15
+ // /quit - 退出
16
+
17
+ import { createInterface } from "node:readline";
18
+ import { existsSync } from "node:fs";
19
+ import { readFile, readdir } from "node:fs/promises";
20
+ import { join, dirname, resolve } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ import { loadLearner, type LearnerState } from "./persona-learner.ts";
24
+ import {
25
+ defaultPersona,
26
+ loadPersonaForSession,
27
+ savePersonaForSession,
28
+ oceanHint,
29
+ type BigFivePersona,
30
+ type OCEAN,
31
+ } from "./bigfive.ts";
32
+ import { initPersonaFromDescription } from "./persona-init.ts";
33
+ import { loadProjectEnv, pickDefaultModel } from "./bootstrap.ts";
34
+ import { createProvider, type ModelProvider, type ChatMessage } from "./provider.ts";
35
+ import { Timeline, EMOTION_LABEL, EMOTION_EMOJI } from "./timeline.ts";
36
+ import { runTurn, forceCompact } from "./loop.ts";
37
+ import {
38
+ scanMemory,
39
+ readMemoryFile,
40
+ writeMemoryFile,
41
+ appendIndexEntry,
42
+ MEMORY_TYPES,
43
+ MEMORY_TYPE_LABEL,
44
+ type MemoryType,
45
+ } from "./memory.ts";
46
+ import {
47
+ createSession,
48
+ loadSession,
49
+ saveSession,
50
+ listSessions,
51
+ deleteSession,
52
+ deriveTitle,
53
+ type SessionMeta,
54
+ } from "./sessions.ts";
55
+ import {
56
+ DEFAULT_COMPACT_CONFIG,
57
+ estimateHistoryTokens,
58
+ shouldCompact,
59
+ type CompactConfig,
60
+ } from "./compact.ts";
61
+ import {
62
+ loadProfile,
63
+ renderProfileForPrompt,
64
+ maybeUpdateProfile,
65
+ type Profile,
66
+ } from "./profile.ts";
67
+ import {
68
+ runReflection,
69
+ listReflections,
70
+ readReflection,
71
+ loadReflectionState,
72
+ shouldSuggestReflection,
73
+ DEFAULT_REFLECTION_CONFIG,
74
+ } from "./reflection.ts";
75
+ import {
76
+ loadProactiveState,
77
+ saveProactiveState,
78
+ shouldTriggerProactive,
79
+ recordProactiveSent,
80
+ recordUserActivity,
81
+ prepareProactiveMessage,
82
+ DEFAULT_PROACTIVE_CONFIG,
83
+ type ProactiveConfig,
84
+ type ProactiveState,
85
+ } from "./proactive.ts";
86
+ import { color, parseJsonLoose } from "./utils.ts";
87
+
88
+ // =====================================================================
89
+ // 路径解析
90
+ // =====================================================================
91
+
92
+ const __dirname = dirname(fileURLToPath(import.meta.url));
93
+ const ROOT_DIR = resolve(__dirname, "..");
94
+
95
+ const DATA_DIR = join(ROOT_DIR, "data");
96
+ const MEMORY_DIR = join(DATA_DIR, "memory");
97
+ const TIMELINE_DIR = join(DATA_DIR, "timeline");
98
+ const PROFILE_DIR = join(DATA_DIR, "profile");
99
+
100
+ // =====================================================================
101
+ // 主函数
102
+ // =====================================================================
103
+
104
+ async function main() {
105
+ console.log(color.cyan("🌅 RememberMe\n"));
106
+
107
+ // 0. 从项目根目录的 ./settings.json 加载 env
108
+ // (不存在则忽略;用户/容器已设置的 env 变量优先)
109
+ loadProjectEnv({ settingsPath: join(ROOT_DIR, "settings.json") });
110
+
111
+ // 1. REPL 多 session 模式(和 web.ts 一致)
112
+ // 反馈学习器
113
+ const USER_ID = "default";
114
+ // 加载最近一次 session:优先选有真实对话的(跳过空 session 残留)
115
+ const allSessions = listSessions(DATA_DIR);
116
+ const nonEmpty = allSessions.find((s) => s.history.length > 0);
117
+ const loadTarget = nonEmpty ?? allSessions[0] ?? null;
118
+ let currentSessionId: string;
119
+ let history: ChatMessage[];
120
+ if (loadTarget) {
121
+ currentSessionId = loadTarget.id;
122
+ history = loadTarget.history;
123
+ } else {
124
+ // 完全无 session(首次启动):REPL 单会话模式创建空 session 作默认起点
125
+ const blank = createSession(DATA_DIR, "default", USER_ID, pickDefaultModel());
126
+ saveSession(DATA_DIR, blank);
127
+ currentSessionId = blank.id;
128
+ history = blank.history;
129
+ }
130
+ // 按 sessionId 加载人设(不存在则默认 OCEAN 0.5)
131
+ let persona: BigFivePersona =
132
+ loadPersonaForSession(DATA_DIR, currentSessionId) ?? defaultPersona(currentSessionId);
133
+ const hasPersonaFile = loadPersonaForSession(DATA_DIR, currentSessionId) !== null;
134
+ // banner:清晰显示当前 session + 加载状态
135
+ const title = loadTarget?.title;
136
+ const sessionDisplay = title
137
+ ? `${color.bold(currentSessionId.slice(0, 18))} ${color.dim("「" + title + "」")}`
138
+ : color.bold(currentSessionId);
139
+ const historyNote = history.length > 0
140
+ ? color.dim(`(已加载 ${history.length} 条历史对话)`)
141
+ : "";
142
+ const personaNote = !hasPersonaFile
143
+ ? color.dim("(未设置人设,建议 /persona init <描述>)")
144
+ : "";
145
+ console.log(`${color.green("✓")} 当前 session: ${sessionDisplay}`);
146
+ if (historyNote) console.log(` ${historyNote}`);
147
+ if (personaNote) console.log(` ${personaNote}`);
148
+ let personaLearner = loadLearner(DATA_DIR, USER_ID);
149
+ const totalFeedback = personaLearner.signalCounts.positive + personaLearner.signalCounts.negative + personaLearner.signalCounts.neutral;
150
+ if (totalFeedback === 0) {
151
+ console.log(`${color.green("✓")} 反馈学习:${color.dim("冷启动(空白起点)")}`);
152
+ } else {
153
+ console.log(`${color.green("✓")} 人设学习器:已学习 ${color.bold(String(totalFeedback))} 轮反馈`);
154
+ }
155
+
156
+ // 2. 加载 provider
157
+ let provider: ModelProvider;
158
+ try {
159
+ // 优先使用 settings.json 里的模型配置
160
+ const model = pickDefaultModel();
161
+ if (
162
+ model.startsWith("claude") ||
163
+ process.env.ANTHROPIC_API_KEY ||
164
+ process.env.ANTHROPIC_BASE_URL
165
+ ) {
166
+ provider = createProvider({
167
+ kind: "anthropic",
168
+ apiKey: process.env.ANTHROPIC_API_KEY,
169
+ model,
170
+ });
171
+ } else {
172
+ provider = createProvider();
173
+ }
174
+ } catch (e) {
175
+ console.error(color.red(`❌ ${(e as Error).message}\n`));
176
+ console.error(color.dim("请在 ~/.claude/settings.json 里设置 ANTHROPIC_API_KEY 或 ANTHROPIC_AUTH_TOKEN,或设置环境变量。"));
177
+ process.exit(1);
178
+ }
179
+ console.log(
180
+ `${color.green("✓")} 模型:${color.bold(provider.name)} / ${provider.model}`,
181
+ );
182
+ if (process.env.ANTHROPIC_BASE_URL) {
183
+ console.log(color.dim(` baseURL: ${process.env.ANTHROPIC_BASE_URL}`));
184
+ }
185
+ console.log();
186
+
187
+ // 3. 初始化 timeline
188
+ const timeline = new Timeline(TIMELINE_DIR);
189
+ await timeline.ensure();
190
+ console.log(`${color.green("✓")} 情绪时间线已就绪`);
191
+
192
+ // 3.5 初始化 profile(首次使用自动创建默认模板)
193
+ let profile: Profile;
194
+ try {
195
+ profile = await loadProfile(DATA_DIR, {
196
+ userId: USER_ID,
197
+ memoryDir: MEMORY_DIR,
198
+ timeline,
199
+ });
200
+ if (profile.initialized) {
201
+ console.log(`${color.green("✓")} 用户画像已初始化(首次使用,已创建默认模板)`);
202
+ } else {
203
+ console.log(`${color.green("✓")} 用户画像已加载(含数据源同步)`);
204
+ }
205
+ } catch (e) {
206
+ console.error(color.yellow(`⚠️ profile 加载失败,将跳过: ${(e as Error).message}`));
207
+ profile = null as unknown as Profile; // 用 sentinel,loop 里会处理 null
208
+ }
209
+
210
+ // 4. compact 配置(可用环境变量覆盖)
211
+ // EC_COMPACT_TRIGGER_AT: 触发压缩的消息条数(默认 20 = 10 轮)
212
+ // EC_COMPACT_RECENT_KEPT: 压缩时保留最近多少条(默认 6 = 3 轮)
213
+ const compactConfig: CompactConfig = {
214
+ triggerAt: parseInt(process.env.EC_COMPACT_TRIGGER_AT ?? "20"),
215
+ recentKept: parseInt(process.env.EC_COMPACT_RECENT_KEPT ?? "6"),
216
+ maxChars: parseInt(process.env.EC_COMPACT_MAX_CHARS ?? "20000"),
217
+ minCompactWorth: 1500,
218
+ };
219
+ console.log(
220
+ `${color.green("✓")} compact 配置:triggerAt=${compactConfig.triggerAt} / recentKept=${compactConfig.recentKept}`,
221
+ );
222
+ console.log();
223
+
224
+ // 4. 启动 REPL
225
+ const rl = createInterface({
226
+ input: process.stdin,
227
+ output: process.stdout,
228
+ });
229
+
230
+ console.log(
231
+ color.dim("提示:直接输入消息开始对话。输入 /help 查看命令。Ctrl+C 退出。\n"),
232
+ );
233
+
234
+ let lastAssistantReply = ""; // 用于反馈检测
235
+
236
+ // === 输入队列(修复 pipe 模式下 readline 丢输入的 bug)===
237
+ // rl.question 在 async 回调未完成时再次调用,会导致上一行的 listener
238
+ // 没被正确移除,下一行可能丢失。改用 'line' 事件 + 串行处理队列。
239
+ let inputQueue: string[] = [];
240
+ let processing = false;
241
+
242
+ const enqueueInput = (line: string) => {
243
+ const text = line.trim();
244
+ if (!text) {
245
+ // 空行直接忽略(不消耗队列 slot)
246
+ drainQueue();
247
+ return;
248
+ }
249
+ inputQueue.push(text);
250
+ drainQueue();
251
+ };
252
+
253
+ const drainQueue = () => {
254
+ if (processing) return;
255
+ const next = inputQueue.shift();
256
+ if (!next) return;
257
+ processing = true;
258
+ handleTurn(next).finally(() => {
259
+ processing = false;
260
+ drainQueue();
261
+ });
262
+ };
263
+
264
+ // 自动抽取开关与 turn 计数
265
+ // 默认开启(用户改了也没事,可用 /memory auto 关闭,或设 EC_AUTO_EXTRACT=0 显式关)
266
+ let autoExtractEnabled = process.env.EC_AUTO_EXTRACT !== "0";
267
+ let turnIndex = 0;
268
+ // 是否显示每轮的 [情绪: ...] 调试标签(默认开;/quiet 关闭)
269
+ // 情绪/记忆/compact 调试标签——默认关闭。
270
+ // 启用方法:export EC_QUIET=1(与"想看"语义相反,名字保持向后兼容)
271
+ let showEmotionLabels = process.env.EC_QUIET === "1";
272
+ // 对话模式(depth = 深度;playful = 玩伴模式)
273
+ // conversationMode 删除(runTurn 不再读取)
274
+ // let conversationMode: "depth" | "playful" =
275
+ // process.env.EC_MODE === "playful" ? "playful" : "depth";
276
+ console.log(
277
+ `${color.green("✓")} 记忆自动抽取:${autoExtractEnabled ? color.green("开") : color.dim("关")}(用 /memory auto toggle 切换)`,
278
+ );
279
+
280
+ // 反思 state
281
+ const reflectionState = await loadReflectionState(DATA_DIR);
282
+ if (reflectionState.lastReflectionAt > 0) {
283
+ const ago = Date.now() - reflectionState.lastReflectionAt;
284
+ const hoursAgo = (ago / (60 * 60 * 1000)).toFixed(1);
285
+ console.log(
286
+ `${color.dim(` 上次反思:${hoursAgo} 小时前(${reflectionState.lastReflectionDate})`)}`,
287
+ );
288
+ } else {
289
+ console.log(`${color.dim(` 反思:暂无,建议运行 /reflect 生成第一份`)}`);
290
+ }
291
+ console.log();
292
+
293
+ // 重启时检查是否该提示用户跑反思
294
+ // 条件:state 里 lastReflectionAt=0 或距今 ≥ 24h 且当日还没运行过
295
+ const needSuggest = shouldSuggestReflection(
296
+ reflectionState,
297
+ true, // REPL 启动本身就意味着今天会有对话
298
+ );
299
+ if (needSuggest) {
300
+ console.log(
301
+ color.yellow(
302
+ `💡 提示:距上次反思超过 24h。可以运行 ${color.cyan("/reflect")} 生成今日洞察。`,
303
+ ),
304
+ );
305
+ console.log();
306
+ }
307
+
308
+ // 主动发起对话(默认关闭)
309
+ // 启用方法:export EC_PROACTIVE=1
310
+ const proactiveConfig: ProactiveConfig = {
311
+ enabled: process.env.EC_PROACTIVE === "1",
312
+ idleThresholdHours: parseFloat(
313
+ process.env.EC_PROACTIVE_IDLE_HOURS ?? "4",
314
+ ),
315
+ maxPerDay: parseInt(process.env.EC_PROACTIVE_MAX_PER_DAY ?? "2"),
316
+ quietHours: {
317
+ start: parseInt(process.env.EC_PROACTIVE_QUIET_START ?? "23"),
318
+ end: parseInt(process.env.EC_PROACTIVE_QUIET_END ?? "8"),
319
+ },
320
+ cooldownMinutes: parseInt(process.env.EC_PROACTIVE_COOLDOWN_MIN ?? "60"),
321
+ };
322
+ // 主动对话不再在 REPL 启动时发(避免"抢白")
323
+ // 改为在用户正常回复末尾自然注入"对了..."(loop.ts 的 proactiveEmbedded)
324
+ console.log(
325
+ `${color.dim("✓")} 主动对话:${proactiveConfig.enabled ? color.dim("对话中嵌入 '对了'") : color.dim("关")}(仅在空闲 > ${proactiveConfig.idleThresholdHours}h 且有上下文时触发,嵌入主回复末尾)`,
326
+ );
327
+
328
+ const proactiveState = await loadProactiveState(DATA_DIR);
329
+ // 旧 state 跨过日期 → 今天还没发
330
+ if (proactiveState.todayDate) {
331
+ const todayStr = new Date().toISOString().slice(0, 10);
332
+ if (proactiveState.todayDate !== todayStr) {
333
+ console.log(color.dim(` 主动对话状态:${proactiveState.todayDate} 已发 ${proactiveState.todayCount} 次 → 今天新计数`));
334
+ proactiveState.todayCount = 0;
335
+ }
336
+ }
337
+
338
+ // 不在启动时记录用户活动——这样 lastUserActivityAt 保持原值
339
+ // (用于测试"用户离开 X 小时"这种"嵌入对了"机制)
340
+ // 真正的用户活动在用户发消息时由 enqueueInput 路径记录
341
+
342
+ console.log();
343
+
344
+ // 用 AbortController 支持中断
345
+ let currentAbort: AbortController | null = null;
346
+
347
+ // 保存当前 session 的工具函数(/quit、/session switch 时调)
348
+ const saveCurrentSession = () => {
349
+ try {
350
+ const sess = createSession(DATA_DIR, "default", USER_ID, provider.model);
351
+ const meta: SessionMeta = {
352
+ ...sess,
353
+ id: currentSessionId,
354
+ history,
355
+ title: deriveTitle(history),
356
+ lastActiveAt: Date.now(),
357
+ };
358
+ saveSession(DATA_DIR, meta);
359
+ } catch (e) {
360
+ // 静默失败,不影响主流程
361
+ }
362
+ };
363
+ // Ctrl+C / rl close 时也保存
364
+ rl.on("close", () => {
365
+ saveCurrentSession();
366
+ console.log(color.dim("\n👋 再见!"));
367
+ process.exit(0);
368
+ });
369
+
370
+ const handleTurn = async (text: string): Promise<void> => {
371
+ // 命令处理
372
+ if (text.startsWith("/")) {
373
+ await handleCommand(text, {
374
+ persona,
375
+ personaLearner,
376
+ timeline,
377
+ provider,
378
+ history,
379
+ compactConfig,
380
+ userId: USER_ID,
381
+ autoExtractEnabled,
382
+ setAutoExtractEnabled: (v: boolean) => {
383
+ autoExtractEnabled = v;
384
+ },
385
+ showEmotionLabels,
386
+ setShowEmotionLabels: (v: boolean) => {
387
+ showEmotionLabels = v;
388
+ },
389
+ currentSessionId,
390
+ setCurrentSession: (id: string, h: ChatMessage[]) => {
391
+ currentSessionId = id;
392
+ history.length = 0;
393
+ history.push(...h);
394
+ },
395
+ setPersona: (p: BigFivePersona) => {
396
+ persona = p;
397
+ },
398
+ reloadPersona: async () => {
399
+ const p = loadPersonaForSession(DATA_DIR, currentSessionId)
400
+ ?? defaultPersona(currentSessionId);
401
+ persona = p;
402
+ return p;
403
+ },
404
+ saveCurrentSession,
405
+ });
406
+ return;
407
+ }
408
+
409
+ // 对话
410
+ try {
411
+ currentAbort = new AbortController();
412
+ process.stdout.write(color.green("\n> "));
413
+
414
+ turnIndex++;
415
+ // 只在"新会话"时记录活动(gap > 1h)
416
+ // 避免每轮都更新 lastUserActivityAt 导致 idle 永远 = 0
417
+ const SESSION_BREAK_MS = 60 * 60 * 1000;
418
+ if (
419
+ proactiveState.lastUserActivityAt === 0 ||
420
+ Date.now() - proactiveState.lastUserActivityAt > SESSION_BREAK_MS
421
+ ) {
422
+ recordUserActivity(proactiveState);
423
+ // fire-and-forget 保存(不阻塞对话)
424
+ saveProactiveState(DATA_DIR, proactiveState).catch(() => {});
425
+ }
426
+ const result = await runTurn(
427
+ {
428
+ provider,
429
+ memoryDir: MEMORY_DIR,
430
+ timeline,
431
+ compactConfig,
432
+ dataDir: DATA_DIR,
433
+ userId: USER_ID,
434
+ persona,
435
+ previousAssistantReply: lastAssistantReply,
436
+ turnIndex,
437
+ onMemoryExtracted: autoExtractEnabled
438
+ ? (results) => {
439
+ for (const r of results) {
440
+ if (r.action === "new") {
441
+ console.log(
442
+ color.green(
443
+ `\n ✍️ [memory] 自动新建:${r.subtype}/${r.filename}`,
444
+ ),
445
+ );
446
+ } else if (r.action === "merged") {
447
+ console.log(
448
+ color.cyan(
449
+ `\n ✍️ [memory] 自动补充:${r.filename}`,
450
+ ),
451
+ );
452
+ }
453
+ // skipped 不打印(避免噪声)
454
+ }
455
+ }
456
+ : undefined,
457
+ },
458
+ text,
459
+ history,
460
+ (chunk) => {
461
+ if (chunk.delta) {
462
+ process.stdout.write(chunk.delta);
463
+ }
464
+ },
465
+ currentAbort.signal,
466
+ );
467
+
468
+ process.stdout.write("\n");
469
+
470
+ // 调试信息(灰色显示情绪和召回的记忆)—— /quiet 可关闭
471
+ if (showEmotionLabels && result.emotion) {
472
+ const e = result.emotion;
473
+ const emoji = EMOTION_EMOJI[e.emotion];
474
+ const label = EMOTION_LABEL[e.emotion];
475
+ const intensity = "▓".repeat(Math.round(e.intensity * 5));
476
+ console.log(
477
+ color.dim(
478
+ ` [情绪: ${emoji} ${label} ${intensity}${e.trigger ? ` | 触发: ${e.trigger}` : ""}]`,
479
+ ),
480
+ );
481
+ }
482
+ if (showEmotionLabels && result.recalledMemories.length > 0) {
483
+ const names = result.recalledMemories
484
+ .map((m) => `${m.subtype}:${m.filename}`)
485
+ .join(", ");
486
+ console.log(color.dim(` [召回记忆: ${names}]`));
487
+ }
488
+ if (showEmotionLabels && result.compacted) {
489
+ console.log(
490
+ color.dim(
491
+ ` [✂️ compact: 节省约 ${result.savedTokens ?? 0} tokens]`,
492
+ ),
493
+ );
494
+ }
495
+
496
+ // 更新历史:必须用 effectiveHistory(compact 后的版本)替换原 history,
497
+ // 否则 REPL 永远只在原始 history 上 append,compact 等于白做。
498
+ const effectiveHistory = [...result.effectiveHistory];
499
+ history.length = 0;
500
+ history.push(...effectiveHistory);
501
+ history.push({ role: "user", content: text });
502
+ history.push({ role: "assistant", content: result.responseText });
503
+
504
+ // 记下本轮回复,下一轮作为反馈检测的输入
505
+ lastAssistantReply = result.responseText;
506
+
507
+ // 限制历史长度(避免 token 爆炸;MVP 简单实现:保留最近 40 条)
508
+ if (history.length > 40) {
509
+ history.splice(0, history.length - 40);
510
+ }
511
+ } catch (e) {
512
+ if ((e as Error).name === "AbortError") {
513
+ console.log(color.dim("\n [已中断]"));
514
+ } else {
515
+ console.error(color.red(`\n❌ ${(e as Error).message}`));
516
+ }
517
+ } finally {
518
+ currentAbort = null;
519
+ }
520
+ };
521
+
522
+ // 监听每一行输入(替换 rl.question 的 race condition)
523
+ rl.on("line", (line) => enqueueInput(line));
524
+
525
+ // 启动:先打印 prompt,让队列开始接收
526
+ process.stdout.write(color.cyan("\n你:"));
527
+ drainQueue();
528
+ }
529
+
530
+ // =====================================================================
531
+ // 命令处理
532
+ // =====================================================================
533
+
534
+ type CommandContext = {
535
+ /** 大五人设(按 sessionId 加载,OCEAN) */
536
+ persona: BigFivePersona;
537
+ /** 人设学习器(取代硬编码 personality) */
538
+ personaLearner: LearnerState;
539
+ timeline: Timeline;
540
+ provider: ModelProvider;
541
+ history: ChatMessage[];
542
+ compactConfig?: CompactConfig;
543
+ /** 用户 ID(用于按用户隔离 learner state) */
544
+ userId: string;
545
+ /** 当前是否开启 auto-extract */
546
+ autoExtractEnabled: boolean;
547
+ /** 切换 auto-extract 开关 */
548
+ setAutoExtractEnabled: (v: boolean) => void;
549
+ /** 是否显示情绪分析标签(默认 true;/quiet 关闭) */
550
+ showEmotionLabels: boolean;
551
+ setShowEmotionLabels: (v: boolean) => void;
552
+ /** 当前 session id(/session switch 时改) */
553
+ currentSessionId: string;
554
+ /** 切换 session:替换 currentSessionId 和 history 引用 */
555
+ setCurrentSession: (id: string, history: ChatMessage[]) => void;
556
+ /** 替换当前人设(/persona init/reset/describe 用) */
557
+ setPersona: (p: BigFivePersona) => void;
558
+ /** 重新从 data/personality/{currentSessionId}.json 读 persona 并替换 */
559
+ reloadPersona: () => Promise<BigFivePersona>;
560
+ /** 显式保存当前 session 到 data/sessions/{id}.json */
561
+ saveCurrentSession: () => void;
562
+ };
563
+
564
+ async function handleCommand(text: string, ctx: CommandContext) {
565
+ const [cmd, ...args] = text.slice(1).split(/\s+/);
566
+
567
+ switch (cmd) {
568
+ case "help":
569
+ printHelp();
570
+ break;
571
+
572
+ case "memory":
573
+ await handleMemoryCommand(args, ctx);
574
+ break;
575
+
576
+ case "timeline":
577
+ await handleTimelineCommand(args, ctx);
578
+ break;
579
+
580
+ case "learner":
581
+ await handleLearnerCommand(args, ctx);
582
+ break;
583
+
584
+ case "stats":
585
+ await handleStatsCommand(ctx);
586
+ break;
587
+
588
+ case "compact":
589
+ await handleCompactCommand(ctx);
590
+ break;
591
+
592
+ case "profile":
593
+ await handleProfileCommand(args, ctx);
594
+ break;
595
+
596
+ case "reflect":
597
+ await handleReflectCommand(args, ctx);
598
+ break;
599
+
600
+ case "reflections":
601
+ await handleReflectionsCommand(args, ctx);
602
+ break;
603
+
604
+ case "proactive":
605
+ await handleProactiveCommand(args, ctx);
606
+ break;
607
+
608
+ case "clear":
609
+ ctx.history.length = 0;
610
+ console.log(color.dim("✓ 会话历史已清空"));
611
+ break;
612
+
613
+ case "quiet":
614
+ handleQuietCommand(ctx);
615
+ break;
616
+
617
+ case "persona":
618
+ await handlePersonaCommand(args, ctx);
619
+ break;
620
+
621
+ case "session":
622
+ await handleSessionCommand(args, ctx);
623
+ break;
624
+
625
+ // /mode 命令删除(runTurn 不再区分 playful/depth)
626
+ // case "mode":
627
+ // handleModeCommand(args, ctx);
628
+ break;
629
+
630
+ case "quit":
631
+ case "exit":
632
+ ctx.saveCurrentSession();
633
+ console.log(color.dim("👋 再见!"));
634
+ process.exit(0);
635
+ break;
636
+
637
+ default:
638
+ console.log(color.yellow(`未知命令: /${cmd}。输入 /help 查看可用命令。`));
639
+ }
640
+ }
641
+
642
+ function printHelp() {
643
+ console.log(`
644
+ ${color.bold("可用命令:")}
645
+ /persona show 显示当前 OCEAN 人设
646
+ /persona init <一句话描述> 用 LLM 生成 OCEAN(写入当前 session)
647
+ /persona describe <文本> 不调 LLM,直接改 preferences
648
+ /persona reset 重置人设为默认中性
649
+ /session list 列出所有 session
650
+ /session current 显示当前 session
651
+ /session new [描述] 新建 session(可选立刻 init 人设)
652
+ /session switch <id> 切换到指定 session
653
+ /session save 手动保存当前 session
654
+ /session delete <id> 删除 session(不能删当前)
655
+ /memory save <type> <name> <description> 保存一条记忆
656
+ /memory list 列出所有记忆
657
+ /memory read <filename> 读记忆详情
658
+ /memory types 列出所有支持的类型
659
+ /memory auto <on|off|status> 自动抽取开关
660
+ /memory suggest 手动触发一次抽取
661
+ /timeline 看最近情绪轨迹
662
+ /timeline stats 看情绪统计
663
+ /learner 看人设学习器状态
664
+ /learner reset 重置学习器(清空反馈)
665
+ /profile 查看用户画像
666
+ /profile path 查看画像文件路径
667
+ /profile reset 重置画像到默认模板
668
+ /reflect 生成今日洞察
669
+ /reflect [days] 用指定回看天数生成
670
+ /reflections list 列出历史反思
671
+ /reflections read <date> 读某条反思
672
+ /proactive <status|trigger|reset> 主动对话状态/触发/重置
673
+ /stats 会话统计
674
+ /compact 手动压缩历史
675
+ /quiet 切换 [情绪: ...] 调试标签
676
+ /clear 清空会话历史
677
+ /help 本帮助
678
+ /quit 退出(自动保存当前 session)
679
+
680
+ ${color.bold("支持的记忆类型:")}
681
+ ${MEMORY_TYPES.map((t) => ` - ${t} (${MEMORY_TYPE_LABEL[t]})`).join("\n")}
682
+ `);
683
+ }
684
+
685
+ async function handleMemoryCommand(args: string[], ctx: CommandContext) {
686
+ const [subcmd, ...rest] = args;
687
+
688
+ switch (subcmd) {
689
+ case "list": {
690
+ const files = await scanMemory(MEMORY_DIR);
691
+ if (files.length === 0) {
692
+ console.log(color.dim("还没有记忆文件。"));
693
+ return;
694
+ }
695
+ console.log(color.bold(`\n共 ${files.length} 条记忆:\n`));
696
+ // 按 subtype 分组
697
+ const groups: Record<string, typeof files> = {};
698
+ for (const f of files) {
699
+ if (!groups[f.subtype]) groups[f.subtype] = [];
700
+ groups[f.subtype].push(f);
701
+ }
702
+ const order: Array<keyof typeof MEMORY_TYPE_LABEL> = [
703
+ "emotion",
704
+ "event",
705
+ "reference",
706
+ ];
707
+ for (const subtype of order) {
708
+ const items = groups[subtype];
709
+ if (!items || items.length === 0) continue;
710
+ console.log(
711
+ color.bold(` [${MEMORY_TYPE_LABEL[subtype]}] (${items.length})`),
712
+ );
713
+ for (const f of items) {
714
+ const date = new Date(f.mtimeMs).toISOString().slice(0, 10);
715
+ console.log(
716
+ ` ${color.cyan(f.filename)} ${color.dim(date)}`,
717
+ );
718
+ console.log(` ${color.dim(f.description)}`);
719
+ }
720
+ }
721
+ return;
722
+ }
723
+
724
+ case "read": {
725
+ const filename = rest[0];
726
+ if (!filename) {
727
+ console.log(color.yellow("用法: /memory read <filename>"));
728
+ return;
729
+ }
730
+ const file = await readMemoryFile(MEMORY_DIR, filename);
731
+ if (!file) {
732
+ console.log(color.yellow(`找不到记忆文件: ${filename}`));
733
+ return;
734
+ }
735
+ console.log(color.bold(`\n[${MEMORY_TYPE_LABEL[file.subtype]}] ${file.name}\n`));
736
+ console.log(color.dim(file.description + "\n"));
737
+ console.log(file.body);
738
+ return;
739
+ }
740
+
741
+ case "types": {
742
+ console.log(color.bold("\n支持的记忆类型(2 主类 + 1 小类):"));
743
+ console.log(color.dim(" emotion —— 反复出现的情绪模式(必须有 ≥2 次证据)"));
744
+ console.log(color.dim(" event —— 对用户有情感意义的生活事件"));
745
+ console.log(color.dim(" reference —— 外部资源(医生/咨询师/联系方式)"));
746
+ return;
747
+ }
748
+
749
+ case "save": {
750
+ const [type, name, ...descParts] = rest;
751
+ const description = descParts.join(" ");
752
+ if (!type || !name || !description) {
753
+ console.log(
754
+ color.yellow(
755
+ "用法: /memory save <type> <name> <description>\n" +
756
+ "示例: /memory save emotion deadline-anxiety 用户提到 deadline 时焦虑升高",
757
+ ),
758
+ );
759
+ return;
760
+ }
761
+ if (!MEMORY_TYPES.includes(type as MemoryType)) {
762
+ console.log(
763
+ color.yellow(
764
+ `未知类型: ${type}。支持: ${MEMORY_TYPES.join(", ")}`,
765
+ ),
766
+ );
767
+ return;
768
+ }
769
+ await saveMemoryInteractive(type as MemoryType, name, description);
770
+ return;
771
+ }
772
+
773
+ case "auto": {
774
+ const [subcmd] = rest;
775
+ if (subcmd === "on") {
776
+ ctx.setAutoExtractEnabled(true);
777
+ console.log(color.green("✓ 记忆自动抽取已开启"));
778
+ console.log(color.dim(" 触发条件:每 5 轮 或 情绪强度 ≥ 0.7"));
779
+ return;
780
+ }
781
+ if (subcmd === "off") {
782
+ ctx.setAutoExtractEnabled(false);
783
+ console.log(color.dim("✓ 记忆自动抽取已关闭"));
784
+ return;
785
+ }
786
+ if (subcmd === "status" || !subcmd) {
787
+ console.log(
788
+ color.bold(
789
+ `\n记忆自动抽取:${ctx.autoExtractEnabled ? color.green("开") : color.gray("关")}`,
790
+ ),
791
+ );
792
+ console.log(color.dim(" 触发条件:每 5 轮兜底 或 情绪强度 ≥ 0.7"));
793
+ console.log(color.dim(" 命令:/memory auto on|off|status"));
794
+ return;
795
+ }
796
+ console.log(color.yellow("用法: /memory auto <on|off|status>"));
797
+ return;
798
+ }
799
+
800
+ case "suggest": {
801
+ // 手动触发一次记忆抽取
802
+ if (ctx.history.length === 0) {
803
+ console.log(color.yellow("目前没有对话内容可抽取。先聊几句再试。"));
804
+ return;
805
+ }
806
+ console.log(color.bold("\n🔍 正在从最近对话中抽取记忆...\n"));
807
+ const { maybeAutoExtract } = await import("./memory-extract.ts");
808
+ const recent = ctx.history
809
+ .slice(-12)
810
+ .map((m) => ({ role: m.role, content: m.content }));
811
+ const results = await maybeAutoExtract(MEMORY_DIR, ctx.provider, recent, {
812
+ minConfidence: 0.5, // 手动模式阈值低一点,发现更多
813
+ });
814
+
815
+ if (results.length === 0) {
816
+ console.log(color.dim(" 没有识别到新的值得记忆的事实。"));
817
+ console.log(color.dim(" 提示:可以明确告诉对方一些事实,便于下次记得。"));
818
+ return;
819
+ }
820
+
821
+ console.log(color.green(`✓ 处理了 ${results.length} 条候选:\n`));
822
+ for (const r of results) {
823
+ const subtypeLabel = MEMORY_TYPE_LABEL[r.candidate.type];
824
+ if (r.action === "new") {
825
+ console.log(
826
+ color.green(
827
+ ` ✍️ 新建 [${subtypeLabel}] ${r.candidate.type}/${r.candidate.name}.md — ${r.candidate.description}`,
828
+ ),
829
+ );
830
+ if (r.linkedTo && r.linkedTo.length > 0) {
831
+ console.log(
832
+ color.dim(
833
+ ` ↪ 跨印证关联:${r.linkedTo.join(", ")}`,
834
+ ),
835
+ );
836
+ }
837
+ } else if (r.action === "merged") {
838
+ console.log(
839
+ color.cyan(
840
+ ` 🔗 合并 [${subtypeLabel}] ${r.candidate.type}/${r.existingFile?.filename} — 补充:${r.candidate.description}`,
841
+ ),
842
+ );
843
+ } else {
844
+ console.log(
845
+ color.dim(
846
+ ` ⏭️ 跳过 [${subtypeLabel}] ${r.candidate.type}/${r.candidate.name}(已存在相似内容)`,
847
+ ),
848
+ );
849
+ }
850
+ }
851
+ return;
852
+ }
853
+
854
+ default:
855
+ console.log(color.yellow("用法: /memory <list|read|types|save|auto|suggest>"));
856
+ }
857
+ }
858
+
859
+ /**
860
+ * 交互式保存记忆。
861
+ */
862
+ async function saveMemoryInteractive(
863
+ type: MemoryType,
864
+ name: string,
865
+ description: string,
866
+ ) {
867
+ const rl = createInterface({
868
+ input: process.stdin,
869
+ output: process.stdout,
870
+ });
871
+
872
+ console.log(color.bold(`\n保存记忆:${type} / ${name}\n`));
873
+ console.log(color.dim("请输入记忆正文(trigger/manifestation/evidence 等)。多行用 \\n 分隔。"));
874
+ console.log(color.dim("输入空行结束:\n"));
875
+
876
+ const body = await new Promise<string>((resolve) => {
877
+ let buffer = "";
878
+ const onLine = (line: string) => {
879
+ if (line.trim() === "") {
880
+ rl.removeListener("line", onLine);
881
+ rl.close();
882
+ resolve(buffer);
883
+ } else {
884
+ buffer += (buffer ? "\n" : "") + line;
885
+ }
886
+ };
887
+ rl.on("line", onLine);
888
+ });
889
+
890
+ if (!body.trim()) {
891
+ console.log(color.yellow("记忆内容为空,已取消。"));
892
+ return;
893
+ }
894
+
895
+ const filename = `${sanitizeFilename(name)}.md`;
896
+ await writeMemoryFile(
897
+ MEMORY_DIR,
898
+ { name, description, subtype: type, body },
899
+ filename,
900
+ );
901
+ await appendIndexEntry(MEMORY_DIR, {
902
+ title: name,
903
+ subtype: type,
904
+ filename: filename.replace(/\.md$/, ""),
905
+ hook: description,
906
+ });
907
+
908
+ console.log(color.green(`✓ 已保存:emotion/${type}/${filename}`));
909
+ }
910
+
911
+ function sanitizeFilename(name: string): string {
912
+ return name
913
+ .toLowerCase()
914
+ .replace(/[^a-z0-9一-龥_-]/g, "_")
915
+ .replace(/_+/g, "_")
916
+ .slice(0, 60);
917
+ }
918
+
919
+ async function handleTimelineCommand(args: string[], _ctx: CommandContext) {
920
+ const [subcmd] = args;
921
+
922
+ if (subcmd === "stats") {
923
+ const stats = await _ctx.timeline.getStats();
924
+ console.log(color.bold("\n📊 情绪统计\n"));
925
+ console.log(`总记录数:${stats.totalEntries}`);
926
+ if (stats.currentDominant) {
927
+ const emoji = EMOTION_EMOJI[stats.currentDominant];
928
+ const label = EMOTION_LABEL[stats.currentDominant];
929
+ console.log(`当前主导情绪:${emoji} ${label}`);
930
+ }
931
+ console.log(`近 7 天平均强度:${(stats.avgIntensity7Days * 100).toFixed(0)}%`);
932
+ if (Object.keys(stats.recent7Days).length > 0) {
933
+ console.log(`\n近 7 天分布:`);
934
+ for (const [emotion, count] of Object.entries(stats.recent7Days)) {
935
+ const emoji = EMOTION_EMOJI[emotion as keyof typeof EMOTION_LABEL];
936
+ const label = EMOTION_LABEL[emotion as keyof typeof EMOTION_LABEL];
937
+ console.log(` ${emoji} ${label}: ${count}`);
938
+ }
939
+ }
940
+ return;
941
+ }
942
+
943
+ // 默认:显示最近 10 条
944
+ const recent = await _ctx.timeline.readRecent(10);
945
+ if (recent.length === 0) {
946
+ console.log(color.dim("还没有情绪记录。"));
947
+ return;
948
+ }
949
+ console.log(color.bold(`\n📈 最近 ${recent.length} 条情绪记录\n`));
950
+ for (const e of recent) {
951
+ const date = new Date(e.ts).toLocaleString("zh-CN");
952
+ const emoji = EMOTION_EMOJI[e.emotion];
953
+ const label = EMOTION_LABEL[e.emotion];
954
+ const intensity = "▓".repeat(Math.max(1, Math.round(e.intensity * 5)));
955
+ const trigger = e.trigger ? ` (${e.trigger})` : "";
956
+ console.log(`${color.dim(date)} ${emoji} ${color.bold(label)} ${intensity}${trigger}`);
957
+ if (e.userExcerpt) {
958
+ console.log(color.dim(` 你: "${e.userExcerpt.slice(0, 80)}${e.userExcerpt.length > 80 ? "…" : ""}"`));
959
+ }
960
+ if (e.myResponseExcerpt) {
961
+ console.log(color.dim(` 我: "${e.myResponseExcerpt.slice(0, 80)}${e.myResponseExcerpt.length > 80 ? "…" : ""}"`));
962
+ }
963
+ }
964
+ }
965
+
966
+ // /learner 命令:显示人设学习器状态
967
+ //
968
+ // 取代旧的 /personality 命令——人设不再可手动切换,
969
+ // 人设完全由反馈学习器动态生成。
970
+
971
+ async function handleLearnerCommand(
972
+ args: string[],
973
+ ctx: CommandContext,
974
+ ): Promise<void> {
975
+ const sub = args[0];
976
+ const learner = ctx.personaLearner;
977
+ const total =
978
+ learner.signalCounts.positive +
979
+ learner.signalCounts.negative +
980
+ learner.signalCounts.neutral;
981
+
982
+ if (sub === "reset") {
983
+ const { resetLearner } = await import("./persona-learner.ts");
984
+ const fresh = resetLearner(DATA_DIR, ctx.userId);
985
+ console.log(color.green("✓ 已重置人设学习器。下一轮对话开始以空白起点。"));
986
+ ctx.personaLearner = fresh;
987
+ return;
988
+ }
989
+
990
+ console.log(color.bold("\n人设学习器状态(开放版):"));
991
+ if (total === 0) {
992
+ console.log(color.dim(" 冷启动 —— 尚未收到反馈"));
993
+ console.log(color.dim(" 给真人回几条消息后,正/负反馈会自动累积为自然语言观察"));
994
+ } else {
995
+ console.log(` 总反馈数: ${color.bold(String(total))}`);
996
+ console.log(
997
+ ` 正: ${learner.signalCounts.positive} / 负: ${learner.signalCounts.negative} / 中: ${learner.signalCounts.neutral}`,
998
+ );
999
+
1000
+ if (learner.positivePatterns.length > 0) {
1001
+ console.log(` ${color.green("用户喜欢(自然语言观察):")}`);
1002
+ for (const p of learner.positivePatterns.slice(-10)) {
1003
+ console.log(` ${color.green("✓")} ${p}`);
1004
+ }
1005
+ }
1006
+ if (learner.negativePatterns.length > 0) {
1007
+ console.log(` ${color.red("用户不喜欢:")}`);
1008
+ for (const p of learner.negativePatterns.slice(-10)) {
1009
+ console.log(` ${color.red("✗")} ${p}`);
1010
+ }
1011
+ }
1012
+ if (learner.positiveExamples.length > 0) {
1013
+ console.log(
1014
+ ` ${color.green("正向示例(" + learner.positiveExamples.length + " 个):")}`,
1015
+ );
1016
+ const ex = learner.positiveExamples[learner.positiveExamples.length - 1];
1017
+ console.log(` 用户:${ex.userMessage.slice(0, 80)}${ex.userMessage.length > 80 ? "..." : ""}`);
1018
+ console.log(` 你: ${ex.aiReply.slice(0, 80)}${ex.aiReply.length > 80 ? "..." : ""}`);
1019
+ if (ex.whyWorked) console.log(` 原因:${ex.whyWorked}`);
1020
+ }
1021
+ if (learner.negativeExamples.length > 0) {
1022
+ console.log(
1023
+ ` ${color.red("负向示例(" + learner.negativeExamples.length + " 个):")}`,
1024
+ );
1025
+ const ex = learner.negativeExamples[learner.negativeExamples.length - 1];
1026
+ console.log(` 用户:${ex.userMessage.slice(0, 80)}${ex.userMessage.length > 80 ? "..." : ""}`);
1027
+ console.log(` 你: ${ex.aiReply.slice(0, 80)}${ex.aiReply.length > 80 ? "..." : ""}`);
1028
+ if (ex.whyDidntWork) console.log(` 原因:${ex.whyDidntWork}`);
1029
+ }
1030
+ if (learner.recentReasons.length > 0) {
1031
+ console.log(` ${color.dim("最近反馈信号(最近 5 条):")}`);
1032
+ for (const r of learner.recentReasons.slice(-5)) {
1033
+ console.log(` ${color.dim(`[${r.signal}] ${r.text}`)}`);
1034
+ }
1035
+ }
1036
+ }
1037
+ console.log();
1038
+ }
1039
+
1040
+ async function handleStatsCommand(ctx: CommandContext): Promise<void> {
1041
+ console.log(color.bold("\n📊 会话统计\n"));
1042
+ console.log(` 消息数: ${color.bold(String(ctx.history.length))}`);
1043
+ const memCount = await readdir(MEMORY_DIR).catch(() => []);
1044
+ console.log(` 记忆文件: ${color.bold(String(memCount.length))}`);
1045
+ const timelineCount = await ctx.timeline.readAll().catch(() => []);
1046
+ console.log(` 情绪时间线条目: ${color.bold(String(timelineCount.length))}`);
1047
+ console.log();
1048
+ console.log(color.dim("提示:长会话用 /compact 手动压缩历史"));
1049
+ }
1050
+
1051
+ async function handleCompactCommand(ctx: CommandContext): Promise<void> {
1052
+ console.log(color.dim("正在压缩历史..."));
1053
+ try {
1054
+ const { history: newHistory, result } = await forceCompact(
1055
+ ctx.provider,
1056
+ ctx.history,
1057
+ DEFAULT_COMPACT_CONFIG,
1058
+ );
1059
+ if (result && result.compactedCount > 0) {
1060
+ console.log(
1061
+ color.green(
1062
+ `✓ 已压缩 ${result.compactedCount} 条消息,节省约 ${result.savedTokens} tokens`,
1063
+ ),
1064
+ );
1065
+ ctx.history.length = 0;
1066
+ ctx.history.push(...newHistory);
1067
+ } else {
1068
+ console.log(color.dim("当前历史无需压缩"));
1069
+ }
1070
+ } catch (e) {
1071
+ console.log(color.red(`compact 失败: ${(e as Error).message}`));
1072
+ }
1073
+ }
1074
+
1075
+ async function handleProfileCommand(
1076
+ args: string[],
1077
+ ctx: CommandContext,
1078
+ ): Promise<void> {
1079
+ const sub = args[0];
1080
+ if (sub === "path") {
1081
+ console.log(`画像文件: ${color.cyan(join(PROFILE_DIR, "PROFILE.md"))}`);
1082
+ return;
1083
+ }
1084
+ if (sub === "reset") {
1085
+ const profilePath = join(PROFILE_DIR, "PROFILE.md");
1086
+ try {
1087
+ const { unlink } = await import("node:fs/promises");
1088
+ await unlink(profilePath);
1089
+ } catch {
1090
+ // 文件本来就不存在
1091
+ }
1092
+ // 重新加载(触发 syncFromSources 用默认模板 + memory + learner 数据源)
1093
+ // 注:timeline 需要 main() 的实例,handleProfileCommand 拿不到;
1094
+ // 用户在下一轮对话时由 maybeUpdateProfile 再写入 timeline 数据
1095
+ await loadProfile(DATA_DIR, {
1096
+ userId: "default",
1097
+ memoryDir: MEMORY_DIR,
1098
+ });
1099
+ console.log(color.green("✓ 画像已重置(默认模板 + 数据源同步)"));
1100
+ return;
1101
+ }
1102
+ // 默认:显示当前画像内容
1103
+ try {
1104
+ const profilePath = join(PROFILE_DIR, "PROFILE.md");
1105
+ const profile = await readFile(profilePath, "utf-8");
1106
+ console.log(color.bold("\n👤 用户画像:\n"));
1107
+ console.log(profile.slice(0, 1500));
1108
+ if (profile.length > 1500) console.log(color.dim("\n... (内容过长,已截断)"));
1109
+ } catch {
1110
+ console.log(color.dim("画像文件不存在"));
1111
+ }
1112
+ }
1113
+
1114
+ async function handleReflectCommand(
1115
+ args: string[],
1116
+ ctx: CommandContext,
1117
+ ): Promise<void> {
1118
+ const days = parseInt(args[0] ?? "7", 10);
1119
+ console.log(color.dim(`正在生成最近 ${days} 天的洞察...`));
1120
+ try {
1121
+ const { runReflection } = await import("./reflection.ts");
1122
+ const insight = await runReflection(DATA_DIR, ctx.timeline, MEMORY_DIR, ctx.provider, { lookbackDays: days });
1123
+ if (insight) {
1124
+ console.log(color.green("\n📝 今日洞察:\n"));
1125
+ console.log(insight);
1126
+ } else {
1127
+ console.log(color.dim("没有足够的数据生成洞察"));
1128
+ }
1129
+ } catch (e) {
1130
+ console.log(color.red(`反思失败: ${(e as Error).message}`));
1131
+ }
1132
+ }
1133
+
1134
+ async function handleReflectionsCommand(
1135
+ args: string[],
1136
+ ctx: CommandContext,
1137
+ ): Promise<void> {
1138
+ const sub = args[0];
1139
+ if (sub === "list") {
1140
+ const { listReflections } = await import("./reflection.ts");
1141
+ const files = await listReflections(DATA_DIR);
1142
+ if (files.length === 0) {
1143
+ console.log(color.dim("还没有反思历史"));
1144
+ return;
1145
+ }
1146
+ console.log(color.bold("\n📚 反思历史:"));
1147
+ for (const f of files) {
1148
+ console.log(` - ${f}`);
1149
+ }
1150
+ return;
1151
+ }
1152
+ if (sub === "read" && args[1]) {
1153
+ const { readReflection } = await import("./reflection.ts");
1154
+ const content = await readReflection(DATA_DIR, args[1]);
1155
+ if (content) {
1156
+ console.log(content);
1157
+ } else {
1158
+ console.log(color.yellow(`没有 ${args[1]} 的反思`));
1159
+ }
1160
+ return;
1161
+ }
1162
+ console.log(color.yellow("用法:/reflections list | /reflections read <YYYY-MM-DD>"));
1163
+ }
1164
+
1165
+ async function handleProactiveCommand(
1166
+ args: string[],
1167
+ ctx: CommandContext,
1168
+ ): Promise<void> {
1169
+ const { loadProactiveState, shouldTriggerProactive, prepareProactiveMessage, recordProactiveSent, DEFAULT_PROACTIVE_CONFIG } = await import("./proactive.ts");
1170
+ const sub = args[0];
1171
+ const state = await loadProactiveState(DATA_DIR);
1172
+
1173
+ if (sub === "status" || !sub) {
1174
+ const decision = shouldTriggerProactive(state, DEFAULT_PROACTIVE_CONFIG);
1175
+ console.log(color.bold("\n💡 主动对话状态:\n"));
1176
+ console.log(` 上次用户活动: ${state.lastUserActivityAt ? new Date(state.lastUserActivityAt).toLocaleString() : "暂无"}`);
1177
+ console.log(` 上次主动消息: ${state.lastProactiveAt ? new Date(state.lastProactiveAt).toLocaleString() : "暂无"}`);
1178
+ console.log(` 今日已发: ${state.todayCount}`);
1179
+ console.log(` 状态: ${decision.should ? color.green("可触发") : color.dim("暂不可(" + decision.reason + ")")}`);
1180
+ return;
1181
+ }
1182
+
1183
+ if (sub === "trigger") {
1184
+ const decision = shouldTriggerProactive(state, DEFAULT_PROACTIVE_CONFIG);
1185
+ if (!decision.should) {
1186
+ console.log(color.dim(`暂不可触发: ${decision.reason}`));
1187
+ return;
1188
+ }
1189
+ try {
1190
+ const { loadProfile } = await import("./profile.ts");
1191
+ const profile = await loadProfile(DATA_DIR);
1192
+ const persona = ctx.persona;
1193
+ const msg = await prepareProactiveMessage(ctx.provider, {
1194
+ dataDir: DATA_DIR,
1195
+ memoryDir: MEMORY_DIR,
1196
+ timeline: ctx.timeline,
1197
+ profile,
1198
+ personality: {
1199
+ name: "RememberMe",
1200
+ description: persona.preferences || "情感陪伴对话助手",
1201
+ },
1202
+ });
1203
+ console.log(color.bold("\n💡 主动消息:\n"));
1204
+ console.log(msg);
1205
+ recordProactiveSent(state);
1206
+ const { saveProactiveState } = await import("./proactive.ts");
1207
+ await saveProactiveState(DATA_DIR, state);
1208
+ } catch (e) {
1209
+ console.log(color.red(`触发失败: ${(e as Error).message}`));
1210
+ }
1211
+ return;
1212
+ }
1213
+
1214
+ if (sub === "reset") {
1215
+ state.lastProactiveAt = 0;
1216
+ state.todayCount = 0;
1217
+ state.lastUserActivityAt = 0;
1218
+ const { saveProactiveState } = await import("./proactive.ts");
1219
+ await saveProactiveState(DATA_DIR, state);
1220
+ console.log(color.green("✓ 已重置主动对话状态"));
1221
+ return;
1222
+ }
1223
+
1224
+ console.log(color.yellow("用法:/proactive status | /proactive trigger | /proactive reset"));
1225
+ }
1226
+
1227
+ function handleQuietCommand(ctx: CommandContext): void {
1228
+ ctx.setShowEmotionLabels(!ctx.showEmotionLabels);
1229
+ if (ctx.showEmotionLabels) {
1230
+ console.log(color.green("✓ 已开启调试标签(情绪 / 记忆 / compact)"));
1231
+ } else {
1232
+ console.log(color.dim("✓ 已关闭调试标签 —— 对话更干净了"));
1233
+ }
1234
+ }
1235
+
1236
+ // =====================================================================
1237
+ // /persona 子命令
1238
+ // =====================================================================
1239
+
1240
+ async function handlePersonaCommand(
1241
+ args: string[],
1242
+ ctx: CommandContext,
1243
+ ): Promise<void> {
1244
+ const [subcmd, ...rest] = args;
1245
+
1246
+ switch (subcmd) {
1247
+ case "show":
1248
+ case undefined: {
1249
+ const p = ctx.persona;
1250
+ console.log(color.bold(`\n🌊 当前人设(session: ${ctx.currentSessionId.slice(0, 18)}…)\n`));
1251
+ const dims: (keyof OCEAN)[] = [
1252
+ "openness",
1253
+ "conscientiousness",
1254
+ "extraversion",
1255
+ "agreeableness",
1256
+ "neuroticism",
1257
+ ];
1258
+ for (const k of dims) {
1259
+ const v = p.ocean[k];
1260
+ const hint = oceanHint(k, v);
1261
+ const label = k.padEnd(20);
1262
+ console.log(` ${label} ${color.cyan(v.toFixed(2))} ${color.dim(hint)}`);
1263
+ }
1264
+ console.log(`\n ${color.bold("preferences:")} ${color.dim(p.preferences)}`);
1265
+ return;
1266
+ }
1267
+
1268
+ case "init": {
1269
+ const description = rest.join(" ").trim();
1270
+ if (!description) {
1271
+ console.log(color.yellow("用法:/persona init <一句话描述>"));
1272
+ console.log(color.dim("示例:/persona init 一个像苏格拉底那样的智者"));
1273
+ return;
1274
+ }
1275
+ console.log(color.dim(`\n🌊 正在基于「${description}」生成 OCEAN...`));
1276
+ try {
1277
+ const persona = await initPersonaFromDescription(
1278
+ ctx.provider,
1279
+ { description, sessionId: ctx.currentSessionId },
1280
+ DATA_DIR,
1281
+ );
1282
+ ctx.setPersona(persona);
1283
+ console.log(color.green("\n✓ 人设已设置:"));
1284
+ for (const k of ["openness", "conscientiousness", "extraversion", "agreeableness", "neuroticism"] as (keyof OCEAN)[]) {
1285
+ console.log(` ${k.padEnd(20)} ${color.cyan(persona.ocean[k].toFixed(2))} ${color.dim(oceanHint(k, persona.ocean[k]))}`);
1286
+ }
1287
+ console.log(`\n ${color.bold("preferences:")} ${color.dim(persona.preferences)}`);
1288
+ } catch (e) {
1289
+ console.log(color.red(`人设生成失败:${(e as Error).message}`));
1290
+ }
1291
+ return;
1292
+ }
1293
+
1294
+ case "reset": {
1295
+ const personaFile = join(DATA_DIR, "personality", `${ctx.currentSessionId}.json`);
1296
+ try {
1297
+ const { unlink } = await import("node:fs/promises");
1298
+ await unlink(personaFile);
1299
+ } catch {
1300
+ // 文件本来就不存在也无所谓
1301
+ }
1302
+ const fresh = defaultPersona(ctx.currentSessionId);
1303
+ ctx.setPersona(fresh);
1304
+ console.log(color.green(`\n✓ 人设已重置为默认中性(OCEAN 全 0.5)`));
1305
+ return;
1306
+ }
1307
+
1308
+ case "describe": {
1309
+ const text = rest.join(" ").trim();
1310
+ if (!text) {
1311
+ console.log(color.yellow("用法:/persona describe <自由文本偏好>"));
1312
+ console.log(color.dim("(不调 LLM,直接修改 preferences 字段)"));
1313
+ return;
1314
+ }
1315
+ const updated: BigFivePersona = {
1316
+ ...ctx.persona,
1317
+ preferences: text,
1318
+ updatedAt: Date.now(),
1319
+ };
1320
+ savePersonaForSession(DATA_DIR, updated);
1321
+ ctx.setPersona(updated);
1322
+ console.log(color.green(`\n✓ preferences 已更新(不调 LLM)`));
1323
+ console.log(color.dim(` ${text}`));
1324
+ return;
1325
+ }
1326
+
1327
+ default:
1328
+ console.log(color.yellow("用法:/persona show | init <描述> | describe <文本> | reset"));
1329
+ }
1330
+ }
1331
+
1332
+ // =====================================================================
1333
+ // 启动入口
1334
+ // =====================================================================
1335
+
1336
+ main().catch((e) => {
1337
+ console.error(color.red(`\n❌ 启动失败: ${(e as Error).message}`));
1338
+ if ((e as Error).stack) console.error(color.dim((e as Error).stack ?? ""));
1339
+ process.exit(1);
1340
+ });
1341
+
1342
+ // =====================================================================
1343
+ // /session 子命令
1344
+ // =====================================================================
1345
+
1346
+ async function handleSessionCommand(
1347
+ args: string[],
1348
+ ctx: CommandContext,
1349
+ ): Promise<void> {
1350
+ const [subcmd, ...rest] = args;
1351
+
1352
+ switch (subcmd) {
1353
+ case "list":
1354
+ case undefined: {
1355
+ const sessions = listSessions(DATA_DIR);
1356
+ if (sessions.length === 0) {
1357
+ console.log(color.dim("\n(还没有任何 session)"));
1358
+ return;
1359
+ }
1360
+ console.log(color.bold(`\n📚 共 ${sessions.length} 个 session:\n`));
1361
+ for (const s of sessions) {
1362
+ const isCurrent = s.id === ctx.currentSessionId;
1363
+ const marker = isCurrent ? color.green("→ ") : " ";
1364
+ const ago = humanizeAgo(Date.now() - s.lastActiveAt);
1365
+ const title = s.title ? `「${s.title}」` : color.dim("(无标题)");
1366
+ const histLen = s.history.length;
1367
+ console.log(
1368
+ `${marker}${color.cyan(s.id)} ${title} ${color.dim(`对话 ${histLen} 条 · ${ago}前`)}`,
1369
+ );
1370
+ }
1371
+ console.log(color.dim(`\n切换:/session switch <id>`));
1372
+ return;
1373
+ }
1374
+
1375
+ case "current": {
1376
+ const title = deriveTitle(ctx.history);
1377
+ const p = ctx.persona;
1378
+ console.log(color.bold(`\n📍 当前 session\n`));
1379
+ console.log(` id: ${color.cyan(ctx.currentSessionId)}`);
1380
+ console.log(` 标题: ${title ?? color.dim("(无标题)")}`);
1381
+ console.log(` 历史: ${ctx.history.length} 条`);
1382
+ console.log(` 人设: ${color.cyan(p.preferences.slice(0, 60))}${p.preferences.length > 60 ? "…" : ""}`);
1383
+ return;
1384
+ }
1385
+
1386
+ case "new": {
1387
+ const description = rest.join(" ").trim();
1388
+ // 先保存当前 session
1389
+ ctx.saveCurrentSession();
1390
+ // 创建新 session
1391
+ const blank = createSession(DATA_DIR, "default", ctx.userId, ctx.provider.model);
1392
+ saveSession(DATA_DIR, blank);
1393
+ ctx.setCurrentSession(blank.id, []);
1394
+ // 重置人设为默认(或调 LLM 生成)
1395
+ if (description) {
1396
+ console.log(color.dim(`\n🌊 正在为新 session 生成人设:「${description}」`));
1397
+ try {
1398
+ const persona = await initPersonaFromDescription(
1399
+ ctx.provider,
1400
+ { description, sessionId: blank.id },
1401
+ DATA_DIR,
1402
+ );
1403
+ ctx.setPersona(persona);
1404
+ console.log(color.green(`\n✓ 新 session:${color.cyan(blank.id)}(已设置人设)`));
1405
+ } catch (e) {
1406
+ ctx.setPersona(defaultPersona(blank.id));
1407
+ console.log(color.green(`\n✓ 新 session:${color.cyan(blank.id)}(人设生成失败,已用默认)`));
1408
+ console.log(color.dim(` ${(e as Error).message}`));
1409
+ }
1410
+ } else {
1411
+ ctx.setPersona(defaultPersona(blank.id));
1412
+ console.log(color.green(`\n✓ 新 session:${color.cyan(blank.id)}(默认人设)`));
1413
+ }
1414
+ console.log(color.dim(" 开始对话吧。"));
1415
+ return;
1416
+ }
1417
+
1418
+ case "switch": {
1419
+ const id = rest[0];
1420
+ if (!id) {
1421
+ console.log(color.yellow("用法:/session switch <id>"));
1422
+ return;
1423
+ }
1424
+ const target = loadSession(DATA_DIR, id);
1425
+ if (!target) {
1426
+ console.log(color.yellow(`找不到 session:${id}`));
1427
+ return;
1428
+ }
1429
+ // 保存当前
1430
+ ctx.saveCurrentSession();
1431
+ // 切换:先改 currentSessionId,再 reloadPersona
1432
+ ctx.setCurrentSession(target.id, target.history);
1433
+ await ctx.reloadPersona();
1434
+ const title = target.title ? `「${target.title}」` : "(无标题)";
1435
+ console.log(color.green(`\n✓ 已切换到:${color.cyan(target.id)} ${title}`));
1436
+ console.log(color.dim(` 历史 ${target.history.length} 条 · 人设已 reload`));
1437
+ return;
1438
+ }
1439
+
1440
+ case "save": {
1441
+ ctx.saveCurrentSession();
1442
+ console.log(color.green(`\n✓ 已保存当前 session:${color.cyan(ctx.currentSessionId)}`));
1443
+ return;
1444
+ }
1445
+
1446
+ case "delete": {
1447
+ const id = rest[0];
1448
+ if (!id) {
1449
+ console.log(color.yellow("用法:/session delete <id>"));
1450
+ return;
1451
+ }
1452
+ if (id === ctx.currentSessionId) {
1453
+ console.log(color.red("\n✗ 不能删除当前正在使用的 session"));
1454
+ console.log(color.dim(" 先 /session switch 到别的,再删这个"));
1455
+ return;
1456
+ }
1457
+ deleteSession(DATA_DIR, id);
1458
+ // 顺手删关联人设
1459
+ try {
1460
+ const { unlink } = await import("node:fs/promises");
1461
+ await unlink(join(DATA_DIR, "personality", `${id}.json`));
1462
+ } catch {
1463
+ // 人设文件不存在也无所谓
1464
+ }
1465
+ console.log(color.green(`\n✓ 已删除 session:${color.cyan(id)}`));
1466
+ return;
1467
+ }
1468
+
1469
+ default:
1470
+ console.log(color.yellow("用法:/session list | current | new [描述] | switch <id> | save | delete <id>"));
1471
+ }
1472
+ }
1473
+
1474
+ function humanizeAgo(ms: number): string {
1475
+ if (ms < 60_000) return "刚刚";
1476
+ if (ms < 3600_000) return `${Math.floor(ms / 60_000)}分钟`;
1477
+ if (ms < 86400_000) return `${Math.floor(ms / 3600_000)}小时`;
1478
+ return `${Math.floor(ms / 86400_000)}天`;
1479
+ }