@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,552 @@
1
+ // src/reflection.ts
2
+ // 每日后台反思 agent(独立设计,不参考特定项目)。
3
+ //
4
+ // 设计目标:
5
+ // - 不是每轮都跑,而是每天(或更长间隔)跑一次
6
+ // - 收集最近 N 天的情绪时间线 + 当前 profile + 最近 memory
7
+ // - 用 LLM 把它们综合成结构化"洞察"
8
+ // - 落盘到 data/reflections/YYYY-MM-DD.md
9
+ // - 失败容错:所有错误都不抛
10
+ //
11
+ // 触发方式:
12
+ // 1. 手动:/reflect(REPL 命令)
13
+ // 2. 重启时检查:距离上次反思 ≥ 24h 且当日有对话 → 在 REPL 提示用户
14
+ // 3. (未来 v0.5+: 真正的 cron-style scheduling)
15
+
16
+ import { readFile, writeFile, mkdir, readdir } from "node:fs/promises";
17
+ import { existsSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import type { ModelProvider } from "./provider.ts";
20
+ import type { Timeline, TimelineEntry } from "./timeline.ts";
21
+ import { loadProfile, type Profile } from "./profile.ts";
22
+ import { scanMemory, formatManifest, type MemoryFile } from "./memory.ts";
23
+
24
+ // =====================================================================
25
+ // 类型定义
26
+ // =====================================================================
27
+
28
+ /**
29
+ * 反思文档的 4 个段落。
30
+ */
31
+ export const REFLECTION_SECTIONS = [
32
+ "情绪趋势",
33
+ "触发器与模式",
34
+ "主人格调整建议",
35
+ "长期观察",
36
+ ] as const;
37
+
38
+ export type ReflectionSection = (typeof REFLECTION_SECTIONS)[number];
39
+
40
+ export type Reflection = {
41
+ /** 反思日期 YYYY-MM-DD */
42
+ date: string;
43
+ /** 4 段内容 */
44
+ sections: Record<ReflectionSection, string>;
45
+ /** 文件路径 */
46
+ path: string;
47
+ /** 生成时间 ms */
48
+ createdAt: number;
49
+ };
50
+
51
+ /**
52
+ * 反思状态:决定下次是否该跑。
53
+ */
54
+ export type ReflectionState = {
55
+ /** 上次反思时间(ms) */
56
+ lastReflectionAt: number;
57
+ /** 上次反思对应的数据快照日期(用于增量对比) */
58
+ lastReflectionDate: string;
59
+ };
60
+
61
+ // =====================================================================
62
+ // 路径 & 默认配置
63
+ // =====================================================================
64
+
65
+ export const REFLECTIONS_DIRNAME = "reflections";
66
+ export const REFLECTION_STATE_FILENAME = "reflection-state.json";
67
+
68
+ export const DEFAULT_REFLECTION_CONFIG = {
69
+ /** 默认回看 N 天的数据 */
70
+ lookbackDays: 7,
71
+ /** 距上次反思多久应该再跑(默认 24h) */
72
+ suggestIntervalMs: 24 * 60 * 60 * 1000,
73
+ /** LLM 输出 max tokens */
74
+ maxOutputTokens: 1500,
75
+ };
76
+
77
+ /**
78
+ * 拼出反思文件路径。
79
+ */
80
+ export function getReflectionsDir(dataDir: string): string {
81
+ return join(dataDir, REFLECTIONS_DIRNAME);
82
+ }
83
+
84
+ export function getReflectionFilePath(
85
+ dataDir: string,
86
+ dateStr: string,
87
+ ): string {
88
+ return join(getReflectionsDir(dataDir), `${dateStr}.md`);
89
+ }
90
+
91
+ export function getReflectionStatePath(dataDir: string): string {
92
+ return join(getReflectionsDir(dataDir), REFLECTION_STATE_FILENAME);
93
+ }
94
+
95
+ // =====================================================================
96
+ // 状态持久化
97
+ // =====================================================================
98
+
99
+ /**
100
+ * 加载反思 state。文件不存在返回零值。
101
+ */
102
+ export async function loadReflectionState(
103
+ dataDir: string,
104
+ ): Promise<ReflectionState> {
105
+ const path = getReflectionStatePath(dataDir);
106
+ if (!existsSync(path)) {
107
+ return { lastReflectionAt: 0, lastReflectionDate: "" };
108
+ }
109
+ try {
110
+ const raw = await readFile(path, "utf-8");
111
+ const parsed = JSON.parse(raw) as Partial<ReflectionState>;
112
+ return {
113
+ lastReflectionAt: parsed.lastReflectionAt ?? 0,
114
+ lastReflectionDate: parsed.lastReflectionDate ?? "",
115
+ };
116
+ } catch {
117
+ return { lastReflectionAt: 0, lastReflectionDate: "" };
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 持久化 state。原子写。
123
+ */
124
+ export async function saveReflectionState(
125
+ dataDir: string,
126
+ state: ReflectionState,
127
+ ): Promise<void> {
128
+ const path = getReflectionStatePath(dataDir);
129
+ await mkdir(getReflectionsDir(dataDir), { recursive: true });
130
+ await writeFile(path, JSON.stringify(state, null, 2), "utf-8");
131
+ }
132
+
133
+ /**
134
+ * 决定是否应该建议用户跑一次反思。
135
+ *
136
+ * 规则:
137
+ * - 从没跑过 → true
138
+ * - 上次跑距今 ≥ suggestIntervalMs 且当日有对话 → true
139
+ * - 否则 false(避免刷屏)
140
+ */
141
+ export function shouldSuggestReflection(
142
+ state: ReflectionState,
143
+ hasConversationToday: boolean,
144
+ now: number = Date.now(),
145
+ intervalMs: number = DEFAULT_REFLECTION_CONFIG.suggestIntervalMs,
146
+ ): boolean {
147
+ if (state.lastReflectionAt === 0) return true;
148
+ if (hasConversationToday && now - state.lastReflectionAt >= intervalMs) {
149
+ return true;
150
+ }
151
+ return false;
152
+ }
153
+
154
+ // =====================================================================
155
+ // 上下文收集
156
+ // =====================================================================
157
+
158
+ export type ReflectionContextInput = {
159
+ /** timeline 实例(用于读情绪时间线) */
160
+ timeline: Timeline;
161
+ /** memory 目录 */
162
+ memoryDir: string;
163
+ /** profile 路径(或 null 让函数自己 load) */
164
+ dataDir?: string;
165
+ /** 回看天数 */
166
+ lookbackDays?: number;
167
+ };
168
+
169
+ export type GatheredContext = {
170
+ /** 时间线最近 N 天(已过滤) */
171
+ timelineEntries: TimelineEntry[];
172
+ /** 当前 profile(可为 null) */
173
+ profile: Profile | null;
174
+ /** memory 文件列表(按 mtime 倒序) */
175
+ memories: MemoryFile[];
176
+ /** 回看天数(实际使用的) */
177
+ lookbackDays: number;
178
+ };
179
+
180
+ /**
181
+ * 把最近的 timeline / memory / profile 汇总成一段纯文本 context,
182
+ * 喂给 LLM 当反思的输入。
183
+ */
184
+ export async function gatherReflectionContext(
185
+ input: ReflectionContextInput,
186
+ ): Promise<GatheredContext & { contextText: string }> {
187
+ const lookbackDays = input.lookbackDays ?? DEFAULT_REFLECTION_CONFIG.lookbackDays;
188
+ const cutoffMs = Date.now() - lookbackDays * 24 * 60 * 60 * 1000;
189
+
190
+ const allEntries = await input.timeline.readAll();
191
+ const recentEntries = allEntries.filter((e) => e.ts >= cutoffMs);
192
+ const memories = await scanMemory(input.memoryDir);
193
+
194
+ let profile: Profile | null = null;
195
+ if (input.dataDir) {
196
+ try {
197
+ profile = await loadProfile(input.dataDir);
198
+ } catch {
199
+ profile = null;
200
+ }
201
+ }
202
+
203
+ // 拼成 contextText
204
+ const lines: string[] = [];
205
+
206
+ lines.push(`# 反思上下文(最近 ${lookbackDays} 天)\n`);
207
+
208
+ // 1. 时间线情绪
209
+ lines.push(`## 1. 情绪时间线(${recentEntries.length} 条)\n`);
210
+ if (recentEntries.length === 0) {
211
+ lines.push("(无)\n");
212
+ } else {
213
+ for (const e of recentEntries) {
214
+ const date = new Date(e.ts).toLocaleString("zh-CN", {
215
+ month: "numeric",
216
+ day: "numeric",
217
+ hour: "numeric",
218
+ minute: "numeric",
219
+ });
220
+ const intensity = Math.round(e.intensity * 10);
221
+ const trigger = e.trigger ? ` · ${e.trigger}` : "";
222
+ const excerpt = e.userExcerpt ? ` · "${e.userExcerpt.slice(0, 60)}"` : "";
223
+ lines.push(`- ${date} ${e.emotion} 强度 ${intensity}/10${trigger}${excerpt}`);
224
+ }
225
+ lines.push("");
226
+
227
+ // 简单情绪分布
228
+ const emotionCounts: Record<string, number> = {};
229
+ let totalIntensity = 0;
230
+ for (const e of recentEntries) {
231
+ emotionCounts[e.emotion] = (emotionCounts[e.emotion] ?? 0) + 1;
232
+ totalIntensity += e.intensity;
233
+ }
234
+ const avgIntensity = totalIntensity / recentEntries.length;
235
+ lines.push(`**平均强度**:${(avgIntensity * 100).toFixed(0)}%`);
236
+ lines.push(
237
+ `**情绪分布**:${Object.entries(emotionCounts)
238
+ .sort((a, b) => b[1] - a[1])
239
+ .map(([k, v]) => `${k}:${v}`)
240
+ .join(", ")}`,
241
+ );
242
+ lines.push("");
243
+ }
244
+
245
+ // 2. profile
246
+ lines.push("\n## 2. 用户画像\n");
247
+ if (!profile) {
248
+ lines.push("(未加载到)\n");
249
+ } else {
250
+ for (const [name, body] of Object.entries(profile.sections)) {
251
+ const trimmed = body.trim();
252
+ if (!trimmed || trimmed.startsWith("(暂无")) continue;
253
+ lines.push(`### ${name}\n${trimmed}\n`);
254
+ }
255
+ }
256
+
257
+ // 3. memory
258
+ lines.push("\n## 3. 记忆文件清单\n");
259
+ if (memories.length === 0) {
260
+ lines.push("(无)\n");
261
+ } else {
262
+ lines.push(formatManifest(memories) + "\n");
263
+ // 把最近更新的 5 条记忆的正文也带上
264
+ const top5 = memories.slice(0, 5);
265
+ for (const m of top5) {
266
+ lines.push(`### ${m.filename} [${m.subtype}]\n${m.description}\n${m.body}\n`);
267
+ }
268
+ }
269
+
270
+ return {
271
+ timelineEntries: recentEntries,
272
+ profile,
273
+ memories,
274
+ lookbackDays,
275
+ contextText: lines.join("\n"),
276
+ };
277
+ }
278
+
279
+ // =====================================================================
280
+ // LLM 反思生成
281
+ // =====================================================================
282
+
283
+ const REFLECT_SYSTEM_PROMPT = `你是情感陪伴对话的反思助手。下面是最近 N 天的情绪时间线、用户画像、和记忆文件清单。
284
+
285
+ **任务**:基于这些证据,生成一份结构化的"洞察文档"。这不是对话、不是回应用户,是写给主人(即真实陪伴用户的 AI)看的后台笔记。
286
+
287
+ **严格按以下 4 段输出 JSON**:
288
+
289
+ {
290
+ "情绪趋势": "对比最近 7 天(或 N 天)的情绪变化。重点指出:(1) 主导情绪是否变了;(2) 强度趋势(升 / 降 / 平);(3) 异常点(突然出现或消失的情绪)",
291
+ "触发器与模式": "从时间线和记忆里识别反复出现或新出现的触发器。例如:\\n- 工作日傍晚焦虑加重\\n- 提到某个朋友时会更放松\\n- 周末睡眠问题下降",
292
+ "主人格调整建议": "基于用户对主人回应的反馈(如有),或基于情绪模式推断,主人的回复风格如何微调。注意:这是建议,不是强制;用具体例子说明",
293
+ "长期观察": "用户没有明说但被观察到的模式 / 潜在需求。例如:\\n- 用户抱怨工作但不主动说要换——可能在等被允许表达\\n- 用户对某些话题回避——可能跟过往创伤有关"
294
+ }
295
+
296
+ 要求:
297
+ 1. **基于证据** —— 每条结论都要有时间线或记忆的具体证据,没有证据就别说
298
+ 2. **具体而非抽象** —— 不要说"用户情绪波动",要说"周三晚上 22:00 焦虑强度 0.8,可能与周五 deadline 有关"
299
+ 3. **宁缺毋滥** —— 没有观察到模式就明说"暂无",不要为了凑数编故事
300
+ 4. **保留观察的语气** —— 这不是最终判断,是"待验证的洞察"
301
+ 5. **总长度 ≤ 800 字**
302
+ 6. 严格 JSON 输出,不要 Markdown 代码块
303
+
304
+ 上下文如下:
305
+
306
+ {context}`;
307
+
308
+ /**
309
+ * 调用 LLM 生成反思。
310
+ * 失败容错:返回空 sections。
311
+ */
312
+ export async function generateReflection(
313
+ provider: ModelProvider,
314
+ contextText: string,
315
+ ): Promise<Record<ReflectionSection, string>> {
316
+ const prompt = REFLECT_SYSTEM_PROMPT.replace("{context}", contextText);
317
+
318
+ let raw: string;
319
+ try {
320
+ raw = await provider.complete({
321
+ model: provider.model,
322
+ params: {
323
+ system: "你是结构化洞察生成助手,严格输出 JSON 对象。",
324
+ messages: [{ role: "user", content: prompt }],
325
+ maxTokens: DEFAULT_REFLECTION_CONFIG.maxOutputTokens,
326
+ temperature: 0.4, // 中低温度,要稳定但允许新发现
327
+ },
328
+ });
329
+ } catch {
330
+ return emptySections();
331
+ }
332
+
333
+ const cleaned = raw
334
+ .trim()
335
+ .replace(/^```(?:json)?\n?/, "")
336
+ .replace(/\n?```$/, "");
337
+
338
+ let parsed: unknown;
339
+ try {
340
+ parsed = JSON.parse(cleaned);
341
+ } catch {
342
+ return emptySections();
343
+ }
344
+
345
+ if (!parsed || typeof parsed !== "object") return emptySections();
346
+
347
+ const sections = emptySections();
348
+ for (const key of REFLECTION_SECTIONS) {
349
+ const value = (parsed as Record<string, unknown>)[key];
350
+ if (typeof value === "string" && value.trim()) {
351
+ sections[key] = value.trim().slice(0, 1500);
352
+ }
353
+ }
354
+
355
+ return sections;
356
+ }
357
+
358
+ function emptySections(): Record<ReflectionSection, string> {
359
+ const out = {} as Record<ReflectionSection, string>;
360
+ for (const s of REFLECTION_SECTIONS) out[s] = "";
361
+ return out;
362
+ }
363
+
364
+ // =====================================================================
365
+ // 落盘
366
+ // =====================================================================
367
+
368
+ /**
369
+ * 把反思 sections 序列化成 Markdown 文件。
370
+ */
371
+ function serializeReflection(
372
+ date: string,
373
+ sections: Record<ReflectionSection, string>,
374
+ ): string {
375
+ const header = [
376
+ `# 每日反思 — ${date}`,
377
+ "",
378
+ "> 由 LLM 基于最近 N 天的情绪时间线、用户画像、记忆文件生成的洞察。",
379
+ "> 这是观察,不是判断。请用 markdown 列表形式阅读。",
380
+ "",
381
+ "---",
382
+ "",
383
+ ].join("\n");
384
+
385
+ const body = REFLECTION_SECTIONS.map((name, i) => {
386
+ const content = sections[name]?.trim() || "(暂无 — 模型未观察到显著模式)";
387
+ return `## ${i + 1}. ${name}\n\n${content}`;
388
+ }).join("\n\n---\n\n");
389
+
390
+ return header + body + "\n";
391
+ }
392
+
393
+ /**
394
+ * 解析反思文件(容错)。
395
+ */
396
+ function parseReflection(raw: string): Record<ReflectionSection, string> {
397
+ const sections = emptySections();
398
+ const lines = raw.split("\n");
399
+ const sectionStarts: { name: string; lineIdx: number }[] = [];
400
+ for (let i = 0; i < lines.length; i++) {
401
+ const m = lines[i].match(/^##\s+(.+?)\s*$/);
402
+ if (m) {
403
+ const rawName = m[1].trim();
404
+ const stripped = rawName.replace(/^\d+\.\s*/, "");
405
+ sectionStarts.push({ name: stripped, lineIdx: i });
406
+ }
407
+ }
408
+
409
+ for (let i = 0; i < sectionStarts.length; i++) {
410
+ const { name, lineIdx } = sectionStarts[i];
411
+ const nextLineIdx =
412
+ i + 1 < sectionStarts.length ? sectionStarts[i + 1].lineIdx : lines.length;
413
+ const body = lines.slice(lineIdx + 1, nextLineIdx).join("\n").trim();
414
+ if ((REFLECTION_SECTIONS as readonly string[]).includes(name)) {
415
+ sections[name as ReflectionSection] = body;
416
+ }
417
+ }
418
+
419
+ return sections;
420
+ }
421
+
422
+ // =====================================================================
423
+ // 列表 / 读取
424
+ // =====================================================================
425
+
426
+ /**
427
+ * 列出所有反思(按日期倒序)。
428
+ */
429
+ export async function listReflections(
430
+ dataDir: string,
431
+ ): Promise<Reflection[]> {
432
+ const dir = getReflectionsDir(dataDir);
433
+ if (!existsSync(dir)) return [];
434
+
435
+ let entries: string[];
436
+ try {
437
+ entries = await readdir(dir);
438
+ } catch {
439
+ return [];
440
+ }
441
+
442
+ const reflections: Reflection[] = [];
443
+ for (const filename of entries) {
444
+ if (!filename.endsWith(".md") || filename === REFLECTION_STATE_FILENAME) {
445
+ continue;
446
+ }
447
+ const path = join(dir, filename);
448
+ try {
449
+ const raw = await readFile(path, "utf-8");
450
+ const sections = parseReflection(raw);
451
+ const stats = await import("node:fs/promises").then((fs) => fs.stat(path));
452
+ const date = filename.replace(/\.md$/, "");
453
+ reflections.push({
454
+ date,
455
+ sections,
456
+ path,
457
+ createdAt: stats.mtimeMs,
458
+ });
459
+ } catch {
460
+ // 跳过损坏的文件
461
+ }
462
+ }
463
+
464
+ reflections.sort((a, b) => b.date.localeCompare(a.date));
465
+ return reflections;
466
+ }
467
+
468
+ /**
469
+ * 读取单条反思。
470
+ */
471
+ export async function readReflection(
472
+ dataDir: string,
473
+ date: string,
474
+ ): Promise<Reflection | null> {
475
+ const path = getReflectionFilePath(dataDir, date);
476
+ if (!existsSync(path)) return null;
477
+ try {
478
+ const raw = await readFile(path, "utf-8");
479
+ const sections = parseReflection(raw);
480
+ const stats = await import("node:fs/promises").then((fs) => fs.stat(path));
481
+ return { date, sections, path, createdAt: stats.mtimeMs };
482
+ } catch {
483
+ return null;
484
+ }
485
+ }
486
+
487
+ // =====================================================================
488
+ // 一站式入口
489
+ // =====================================================================
490
+
491
+ export type RunReflectionOptions = {
492
+ /** 回看天数 */
493
+ lookbackDays?: number;
494
+ /** 用什么日期作为文件名(默认今天) */
495
+ dateStr?: string;
496
+ /** 是否更新 state(默认 true) */
497
+ persistState?: boolean;
498
+ };
499
+
500
+ /**
501
+ * 完整链路:收集 context → 生成反思 → 落盘 → 更新 state。
502
+ * 失败容错:所有错误都不抛,返回 null。
503
+ */
504
+ export async function runReflection(
505
+ dataDir: string,
506
+ timeline: Timeline,
507
+ memoryDir: string,
508
+ provider: ModelProvider,
509
+ options: RunReflectionOptions = {},
510
+ ): Promise<Reflection | null> {
511
+ try {
512
+ const lookbackDays =
513
+ options.lookbackDays ?? DEFAULT_REFLECTION_CONFIG.lookbackDays;
514
+ const dateStr =
515
+ options.dateStr ?? new Date().toISOString().slice(0, 10);
516
+
517
+ const { contextText } = await gatherReflectionContext({
518
+ timeline,
519
+ memoryDir,
520
+ dataDir,
521
+ lookbackDays,
522
+ });
523
+
524
+ const sections = await generateReflection(provider, contextText);
525
+
526
+ // 写盘
527
+ const dir = getReflectionsDir(dataDir);
528
+ await mkdir(dir, { recursive: true });
529
+ const path = getReflectionFilePath(dataDir, dateStr);
530
+ const content = serializeReflection(dateStr, sections);
531
+ await writeFile(path, content, "utf-8");
532
+
533
+ const reflection: Reflection = {
534
+ date: dateStr,
535
+ sections,
536
+ path,
537
+ createdAt: Date.now(),
538
+ };
539
+
540
+ if (options.persistState !== false) {
541
+ await saveReflectionState(dataDir, {
542
+ lastReflectionAt: reflection.createdAt,
543
+ lastReflectionDate: dateStr,
544
+ });
545
+ }
546
+
547
+ return reflection;
548
+ } catch (e) {
549
+ console.error(`[reflection] 失败:`, (e as Error).message);
550
+ return null;
551
+ }
552
+ }
@@ -0,0 +1,140 @@
1
+ // src/sessions.ts
2
+ // 按人格分别管理对话 session
3
+ //
4
+ // 核心逻辑:
5
+ // - 每个 session 是一个 (persona, history, model) 的三元组
6
+ // - 切换人格 = 找到该人格最近一次 session,加载它的 history
7
+ // - 找不到 = 开新 session
8
+ // - 一个用户可以同时有多个 session(不同 persona)
9
+
10
+ import { join } from "node:path";
11
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync } from "node:fs";
12
+ import type { ChatMessage } from "./provider.ts";
13
+
14
+ export type SessionMeta = {
15
+ id: string;
16
+ persona: string; // 文件名,如 "default-sunny-bro.md"
17
+ personaName: string; // H1 名字
18
+ model: string;
19
+ history: ChatMessage[];
20
+ createdAt: number;
21
+ lastActiveAt: number;
22
+ title?: string; // 第一条 user message 的前 30 字
23
+ };
24
+
25
+ const SESSIONS_DIR_NAME = "sessions";
26
+ const MAX_HISTORY = 50; // 防止 session 文件无限增长
27
+
28
+ export function getSessionsDir(dataDir: string): string {
29
+ return join(dataDir, SESSIONS_DIR_NAME);
30
+ }
31
+
32
+ export function ensureSessionsDir(dataDir: string): void {
33
+ const dir = getSessionsDir(dataDir);
34
+ if (!existsSync(dir)) {
35
+ mkdirSync(dir, { recursive: true });
36
+ }
37
+ }
38
+
39
+ function sessionPath(dataDir: string, id: string): string {
40
+ return join(getSessionsDir(dataDir), `${id}.json`);
41
+ }
42
+
43
+ /**
44
+ * 列出所有 session,按 lastActiveAt 倒序
45
+ */
46
+ export function listSessions(dataDir: string): SessionMeta[] {
47
+ const dir = getSessionsDir(dataDir);
48
+ if (!existsSync(dir)) return [];
49
+ const files = readdirSync(dir).filter((f) => f.endsWith(".json"));
50
+ const sessions: SessionMeta[] = [];
51
+ for (const f of files) {
52
+ try {
53
+ const raw = readFileSync(join(dir, f), "utf-8");
54
+ const s = JSON.parse(raw) as SessionMeta;
55
+ sessions.push(s);
56
+ } catch {
57
+ // 跳过损坏的文件
58
+ }
59
+ }
60
+ sessions.sort((a, b) => b.lastActiveAt - a.lastActiveAt);
61
+ return sessions;
62
+ }
63
+
64
+ /**
65
+ * 加载指定 session
66
+ */
67
+ export function loadSession(dataDir: string, id: string): SessionMeta | null {
68
+ const path = sessionPath(dataDir, id);
69
+ if (!existsSync(path)) return null;
70
+ try {
71
+ return JSON.parse(readFileSync(path, "utf-8")) as SessionMeta;
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * 保存 session
79
+ */
80
+ export function saveSession(dataDir: string, session: SessionMeta): void {
81
+ ensureSessionsDir(dataDir);
82
+ // 截断 history 防止无限增长
83
+ if (session.history.length > MAX_HISTORY * 2) {
84
+ session.history = session.history.slice(-MAX_HISTORY);
85
+ }
86
+ writeFileSync(sessionPath(dataDir, session.id), JSON.stringify(session, null, 2), "utf-8");
87
+ }
88
+
89
+ /**
90
+ * 删除 session
91
+ */
92
+ export function deleteSession(dataDir: string, id: string): void {
93
+ const path = sessionPath(dataDir, id);
94
+ if (existsSync(path)) unlinkSync(path);
95
+ }
96
+
97
+ /**
98
+ * 找到某 persona 最近的一个 session
99
+ * 如果没找到返回 null
100
+ */
101
+ export function findLatestSessionForPersona(
102
+ dataDir: string,
103
+ persona: string,
104
+ ): SessionMeta | null {
105
+ const sessions = listSessions(dataDir).filter((s) => s.persona === persona);
106
+ return sessions.length > 0 ? sessions[0] : null;
107
+ }
108
+
109
+ /**
110
+ * 创建一个新 session
111
+ */
112
+ export function createSession(
113
+ dataDir: string,
114
+ persona: string,
115
+ personaName: string,
116
+ model: string,
117
+ history: ChatMessage[] = [],
118
+ ): SessionMeta {
119
+ const id = `s-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
120
+ const now = Date.now();
121
+ return {
122
+ id,
123
+ persona,
124
+ personaName,
125
+ model,
126
+ history,
127
+ createdAt: now,
128
+ lastActiveAt: now,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * 给 history 第一条 user message 取个简短标题(前 30 字)
134
+ */
135
+ export function deriveTitle(history: ChatMessage[]): string | undefined {
136
+ const firstUser = history.find((m) => m.role === "user");
137
+ if (!firstUser) return undefined;
138
+ const text = firstUser.content.trim();
139
+ return text.length > 30 ? text.slice(0, 30) + "…" : text;
140
+ }