@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/web.ts ADDED
@@ -0,0 +1,624 @@
1
+ // src/web.ts — RememberMe 网页版后端(Bun.serve)
2
+ // 移除硬编码人格,改为反馈学习驱动的动态人设
3
+ // 启动: bun run start (默认) → 此文件
4
+ // REPL: bun run repl → src/index.ts
5
+
6
+ import { join, resolve } from "node:path";
7
+ import { readFileSync, existsSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { mkdir } from "node:fs/promises";
10
+ import type { ChatMessage, ModelProvider, StreamChunk, StreamOptions } from "./provider.ts";
11
+ import type { Profile } from "./profile.ts";
12
+ import { buildSystemPrompt } from "./prompt.ts";
13
+ import { createSession, saveSession, loadSession, deleteSession, listSessions, deriveTitle, type SessionMeta } from "./sessions.ts";
14
+ import { detectEmotion, recallMemories, type EmotionDetection } from "./classify.ts";
15
+ import { maybeCompact, DEFAULT_COMPACT_CONFIG, type CompactConfig } from "./compact.ts";
16
+ import { scanMemory, readMemoryIndex } from "./memory.ts";
17
+ import { maybeUpdateProfile, loadProfile } from "./profile.ts";
18
+ import { loadLearner, saveLearner, type LearnerState } from "./persona-learner.ts";
19
+ import { loadPersonaForSession, savePersonaForSession, defaultPersona, type BigFivePersona } from "./bigfive.ts";
20
+ import { initPersonaFromDescription } from "./persona-init.ts";
21
+ import { Timeline } from "./timeline.ts";
22
+ import { loadProjectEnv, pickDefaultModel } from "./bootstrap.ts";
23
+ import { createProvider } from "./provider.ts";
24
+
25
+ const ROOT_DIR = process.cwd();
26
+ const WEB_DIR = join(ROOT_DIR, "web");
27
+ const DATA_DIR = join(ROOT_DIR, "data");
28
+ const PROFILE_DIR = join(DATA_DIR, "profile");
29
+ const MEMORY_DIR = join(DATA_DIR, "memory");
30
+ const TIMELINE_DIR = join(DATA_DIR, "timeline");
31
+ const SETTINGS_PATH = join(ROOT_DIR, "settings.json");
32
+ const DEFAULT_USER_ID = "default";
33
+ /** 默认人设文件(personality/ 目录下) */
34
+ const DEFAULT_PERSONA_FILE = "default.md";
35
+
36
+ interface AppState {
37
+ provider: ModelProvider;
38
+ userId: string;
39
+ /** 大五人设(按 sessionId 加载) */
40
+ persona: BigFivePersona | null;
41
+ personaLearner: LearnerState;
42
+ profile: Profile | null;
43
+ currentSessionId: string | null;
44
+ /** 上一轮 AI 回复(用于本轮的反馈检测) */
45
+ previousAssistantReply: string;
46
+ history: ChatMessage[];
47
+ timeline: Timeline;
48
+ compactConfig: CompactConfig;
49
+ }
50
+
51
+ async function bootstrap(): Promise<AppState> {
52
+ loadProjectEnv({ settingsPath: SETTINGS_PATH });
53
+
54
+ await mkdir(PROFILE_DIR, { recursive: true });
55
+ await mkdir(MEMORY_DIR, { recursive: true });
56
+ await mkdir(TIMELINE_DIR, { recursive: true });
57
+
58
+ const model = pickDefaultModel();
59
+ const provider = createProvider({ kind: "anthropic", model });
60
+ const userId = DEFAULT_USER_ID;
61
+
62
+ // 反馈学习器(v0.17.0 人设 body 改为按 sessionId 加载)
63
+ const personaLearner = loadLearner(DATA_DIR, userId);
64
+
65
+ let profile: Profile | null = null;
66
+ // v0.21.1 修复:web 启动时无条件 loadProfile,让它自动创建 PROFILE.md
67
+ // 之前 existsSync 判断导致首次 clone 后 PROFILE.md 不存在 → state.profile = null
68
+ // → profile 段不注入 prompt → 用户感觉"什么都不记得"
69
+ try {
70
+ profile = await loadProfile(DATA_DIR);
71
+ } catch (e) {
72
+ console.error(`[web] profile 加载失败:`, (e as Error).message);
73
+ profile = null;
74
+ }
75
+
76
+ const timeline = new Timeline(TIMELINE_DIR);
77
+ await timeline.ensure();
78
+
79
+ // 加载最近一次 session(v0.15.0 不再按 persona 过滤)
80
+ // 不再自动创建空 session:sessions/ 为空时 currentSessionId=null,
81
+ // 首次发消息时 /api/send 才会创建 session
82
+ const allSessions = listSessions(DATA_DIR);
83
+ const firstSession = allSessions.length > 0 ? allSessions[0] : null;
84
+
85
+ return {
86
+ provider,
87
+ userId,
88
+ persona: firstSession ? loadPersonaForSession(DATA_DIR, firstSession.id) : null,
89
+ personaLearner,
90
+ profile,
91
+ currentSessionId: firstSession?.id ?? null,
92
+ previousAssistantReply: "",
93
+ history: firstSession?.history ?? [],
94
+ timeline,
95
+ compactConfig: DEFAULT_COMPACT_CONFIG,
96
+ };
97
+ }
98
+
99
+ async function runTurn(
100
+ state: AppState,
101
+ userMessage: string,
102
+ onChunk: (chunk: StreamChunk) => void,
103
+ signal: AbortSignal,
104
+ ): Promise<{
105
+ responseText: string;
106
+ emotion: EmotionDetection | null;
107
+ profileUpdated: boolean;
108
+ }> {
109
+ // side-query: 情绪 + 记忆(并行)
110
+ const memCandidates = await scanMemory(MEMORY_DIR);
111
+ const memoryIndex = await readMemoryIndex(MEMORY_DIR);
112
+ const emotion = await detectEmotion(state.provider, userMessage);
113
+ const recalled = await recallMemories(state.provider, userMessage, memCandidates, 5);
114
+
115
+ // compact
116
+ const { history: compactedHistory, result: compactResult } = await maybeCompact(
117
+ state.history,
118
+ state.provider,
119
+ state.compactConfig,
120
+ );
121
+
122
+ // 重新加载 learner(v0.15.0: 反馈循环可能在上轮更新了它)
123
+ state.personaLearner = loadLearner(DATA_DIR, state.userId);
124
+
125
+ // 重新加载 profile(profile 更新是 fire-and-forget,不 reload 会读到旧值)
126
+ // 修复:对话 A 聊了几轮 → PROFILE.md 已更新 → 切到对话 B 应读到新 profile
127
+ try {
128
+ state.profile = await loadProfile(DATA_DIR);
129
+ } catch (e) {
130
+ console.error(`[web] profile 加载失败:`, (e as Error).message);
131
+ }
132
+
133
+ // system prompt(v0.18.0: OCEAN 大五人设 + 反馈学习)
134
+ // 按 sessionId 加载人设(如不存在则用默认 OCEAN)
135
+ state.persona = loadPersonaForSession(DATA_DIR, state.currentSessionId!);
136
+ const systemPrompt = await buildSystemPrompt({
137
+ persona: state.persona,
138
+ personaLearner: state.personaLearner,
139
+ memoryIndex,
140
+ profile: state.profile,
141
+ emotion,
142
+ recalledMemories: recalled,
143
+ timeline: state.timeline,
144
+ });
145
+
146
+ const messages: ChatMessage[] = [
147
+ ...compactedHistory,
148
+ { role: "user", content: userMessage },
149
+ ];
150
+
151
+ let fullText = "";
152
+ const streamOpts: StreamOptions = {
153
+ model: state.provider.model,
154
+ params: {
155
+ system: systemPrompt,
156
+ messages,
157
+ maxTokens: 3000,
158
+ temperature: 0.8,
159
+ presencePenalty: 0.4,
160
+ signal,
161
+ },
162
+ };
163
+
164
+ for await (const chunk of state.provider.stream(streamOpts)) {
165
+ fullText += chunk.delta;
166
+ onChunk(chunk);
167
+ if (chunk.done) break;
168
+ }
169
+
170
+ // 写时间线
171
+ if (emotion) {
172
+ await state.timeline.append({
173
+ emotion: emotion.emotion,
174
+ intensity: emotion.intensity,
175
+ trigger: emotion.trigger,
176
+ userExcerpt: userMessage.slice(0, 200),
177
+ myResponseExcerpt: fullText.slice(0, 200),
178
+ });
179
+ }
180
+
181
+ // 后台 profile 更新(fire-and-forget,不阻塞用户响应)
182
+ // v0.21 修复:之前 await 让用户感觉"输出结束还卡了几十秒"(LLM 摘要调用 2-5s)
183
+ let profileUpdated = false;
184
+ if (state.profile) {
185
+ const recent = [
186
+ ...messages.slice(-6),
187
+ { role: "assistant" as const, content: fullText.slice(0, 500) },
188
+ ];
189
+ maybeUpdateProfile(DATA_DIR, state.provider, recent, {
190
+ userId: state.userId,
191
+ memoryDir: MEMORY_DIR,
192
+ timeline: state.timeline,
193
+ })
194
+ .then((result) => {
195
+ if (result.updated && process.env.EC_DEBUG) {
196
+ console.log(`[web/profile] 已更新`);
197
+ }
198
+ })
199
+ .catch(() => {
200
+ // maybeUpdateProfile 内部已 catch
201
+ });
202
+ }
203
+
204
+ // 反馈学习循环(fire-and-forget,不阻塞用户)
205
+ // 用"上一轮 AI 回复"和"本轮用户消息"作为信号
206
+ const prevReply = state.previousAssistantReply;
207
+ if (prevReply && prevReply.trim().length > 0) {
208
+ const { detectFeedback } = await import("./feedback-detector.ts");
209
+ const { loadLearner, applyFeedback, saveLearner } = await import("./persona-learner.ts");
210
+ detectFeedback(state.provider, prevReply, userMessage, signal)
211
+ .then((result) => {
212
+ try {
213
+ const state2 = loadLearner(DATA_DIR, state.userId);
214
+ const updated = applyFeedback(state2, result.signal, result.insights, result.example);
215
+ saveLearner(DATA_DIR, updated);
216
+ if (process.env.EC_DEBUG) {
217
+ console.log(`[feedback] signal=${result.signal} insights=${JSON.stringify(result.insights)} reason="${result.reason}"`);
218
+ }
219
+ } catch {
220
+ // 静默失败
221
+ }
222
+ })
223
+ .catch(() => {});
224
+ }
225
+
226
+ return { responseText: fullText, emotion, profileUpdated };
227
+ }
228
+
229
+ function serveStatic(path: string, contentType: string): Response {
230
+ try {
231
+ const content = readFileSync(path);
232
+ return new Response(content, {
233
+ headers: {
234
+ "Content-Type": contentType,
235
+ // 不让浏览器缓存 JS / CSS / HTML,否则改了 app.js 用户还得 Ctrl+Shift+R
236
+ "Cache-Control": "no-store, must-revalidate",
237
+ "Pragma": "no-cache",
238
+ "Expires": "0",
239
+ },
240
+ });
241
+ } catch {
242
+ return new Response("Not Found", { status: 404 });
243
+ }
244
+ }
245
+
246
+ // 1x1 透明 PNG,让浏览器停止刷 favicon 404
247
+ const FAVICON_PNG = new Uint8Array([
248
+ 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
249
+ 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x08,0x06,0x00,0x00,0x00,0x1f,0x15,0xc4,
250
+ 0x89,0x00,0x00,0x00,0x0d,0x49,0x44,0x41,0x54,0x78,0x9c,0x63,0x00,0x01,0x00,0x00,
251
+ 0x05,0x00,0x01,0x0d,0x0a,0x2d,0xb4,0x00,0x00,0x00,0x00,0x49,0x45,0x4e,0x44,0xae,
252
+ 0x42,0x60,0x82,
253
+ ]);
254
+
255
+ async function main() {
256
+ const port = parseInt(process.env.PORT ?? "3000", 10);
257
+ const state = await bootstrap();
258
+
259
+ // 剥掉 LLM 偶尔漏出来的 markdown(**加粗** *斜体* `代码` # 标题)
260
+ // 真人不这么聊天,必须在后端兜底
261
+ const stripMarkdown = (text: string): string =>
262
+ text
263
+ .replace(/\*\*([^*]+)\*\*/g, "$1") // **加粗** → 加粗
264
+ .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, "$1") // *斜体* → 斜体
265
+ .replace(/`([^`]+)`/g, "$1") // `代码` → 代码
266
+ .replace(/^#{1,6}\s+/gm, "") // # 标题 → 空
267
+ .replace(/^[-*]\s+/gm, ""); // - 列表 / * 列表 → 空
268
+
269
+ // SSE 编码辅助:自动把 event 名塞进 data.type,前端只 parse data 即可
270
+ const sse = (event: string, data: Record<string, unknown>) =>
271
+ `event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`;
272
+
273
+ const server = Bun.serve({
274
+ port,
275
+ // LLM 流式回复经常超过 10s,Bun 默认 idleTimeout=10s 会强断
276
+ // 拉满到 255s(max)
277
+ idleTimeout: 255,
278
+ async fetch(req) {
279
+ const url = new URL(req.url);
280
+ const path = url.pathname;
281
+
282
+ // 静态文件
283
+ if (req.method === "GET") {
284
+ if (path === "/" || path === "/index.html") {
285
+ return serveStatic(join(WEB_DIR, "index.html"), "text/html; charset=utf-8");
286
+ }
287
+ if (path === "/style.css") {
288
+ return serveStatic(join(WEB_DIR, "style.css"), "text/css; charset=utf-8");
289
+ }
290
+ if (path === "/app.js") {
291
+ return serveStatic(join(WEB_DIR, "app.js"), "application/javascript; charset=utf-8");
292
+ }
293
+ if (path === "/favicon.ico") {
294
+ return new Response(FAVICON_PNG, {
295
+ headers: { "Content-Type": "image/png", "Cache-Control": "public, max-age=86400" },
296
+ });
297
+ }
298
+ if (path === "/api/state") {
299
+ return new Response(JSON.stringify({
300
+ model: state.provider.model,
301
+ personaLoaded: state.persona !== null,
302
+ currentSessionId: state.currentSessionId,
303
+ learnerTotalFeedback: state.personaLearner.signalCounts.positive +
304
+ state.personaLearner.signalCounts.negative +
305
+ state.personaLearner.signalCounts.neutral,
306
+ }), { headers: { "Content-Type": "application/json" } });
307
+ }
308
+ if (path === "/health") {
309
+ return new Response(JSON.stringify({
310
+ status: "ok",
311
+ learnerTotalFeedback: state.personaLearner.signalCounts.positive +
312
+ state.personaLearner.signalCounts.negative +
313
+ state.personaLearner.signalCounts.neutral,
314
+ }), { headers: { "Content-Type": "application/json" } });
315
+ }
316
+ if (path === "/api/sessions") {
317
+ const sessions = listSessions(DATA_DIR);
318
+ return new Response(JSON.stringify({
319
+ sessions: sessions.map((sess) => ({
320
+ id: sess.id,
321
+ title: sess.title,
322
+ messageCount: sess.history.length,
323
+ createdAt: sess.createdAt,
324
+ lastActiveAt: sess.lastActiveAt,
325
+ })),
326
+ currentSessionId: state.currentSessionId,
327
+ }), { headers: { "Content-Type": "application/json" } });
328
+ }
329
+ if (path === "/api/messages") {
330
+ return new Response(JSON.stringify({
331
+ messages: state.history,
332
+ sessionId: state.currentSessionId,
333
+ }), { headers: { "Content-Type": "application/json" } });
334
+ }
335
+ return new Response("Not Found", { status: 404 });
336
+ }
337
+
338
+ // API: 发送消息(流式 SSE)
339
+ if (req.method === "POST" && path === "/api/send") {
340
+ let body: { message?: string } = {};
341
+ try {
342
+ body = await req.json();
343
+ } catch {
344
+ return new Response("Invalid JSON", { status: 400 });
345
+ }
346
+ if (!body.message || !body.message.trim()) {
347
+ return new Response("Empty message", { status: 400 });
348
+ }
349
+
350
+ const encoder = new TextEncoder();
351
+ const stream = new ReadableStream({
352
+ async start(controller) {
353
+ const ac = new AbortController();
354
+ // 客户端断开 → 取消
355
+ req.signal.addEventListener("abort", () => ac.abort());
356
+
357
+ const send = (event: string, data: unknown) => {
358
+ try {
359
+ const payload = (data && typeof data === "object" ? data : {}) as Record<string, unknown>;
360
+ controller.enqueue(encoder.encode(sse(event, payload)));
361
+ } catch {
362
+ // 连接已断
363
+ }
364
+ };
365
+
366
+ send("status", { message: "思考中…" });
367
+
368
+ // 懒创建 session:用户从没开过 session 时,发第一条消息才创建
369
+ if (!state.currentSessionId) {
370
+ const newSess = createSession(DATA_DIR, "default", state.userId, state.provider.model);
371
+ saveSession(DATA_DIR, newSess);
372
+ state.currentSessionId = newSess.id;
373
+ state.history = newSess.history;
374
+ state.persona = loadPersonaForSession(DATA_DIR, newSess.id);
375
+ // 通知前端 session 已创建(前端可刷新 sidebar)
376
+ send("session", { sessionId: newSess.id });
377
+ }
378
+
379
+ try {
380
+ const result = await runTurn(
381
+ state,
382
+ body.message!.trim(),
383
+ (chunk) => {
384
+ if (chunk.delta) {
385
+ send("text", { delta: stripMarkdown(chunk.delta) });
386
+ }
387
+ },
388
+ ac.signal,
389
+ );
390
+
391
+ // 追加到历史(用最终版本,不是 draft)
392
+ state.history.push({ role: "user", content: body.message!.trim() });
393
+ state.history.push({ role: "assistant", content: stripMarkdown(result.responseText) });
394
+ // 记下本轮 AI 回复,下一轮用户消息来时作为反馈检测的输入
395
+ state.previousAssistantReply = stripMarkdown(result.responseText);
396
+ // 持久化到 session
397
+ if (state.currentSessionId) {
398
+ const sess = loadSession(DATA_DIR, state.currentSessionId);
399
+ if (sess) {
400
+ sess.history = state.history;
401
+ sess.lastActiveAt = Date.now();
402
+ sess.model = state.provider.model;
403
+ // 首条 user message 自动生成标题(v0.14.0)
404
+ if (!sess.title) {
405
+ sess.title = deriveTitle(sess.history) ?? "新对话";
406
+ }
407
+ saveSession(DATA_DIR, sess);
408
+ }
409
+ }
410
+
411
+ // 状态事件
412
+ if (result.emotion) {
413
+ const e = result.emotion;
414
+ send("status", {
415
+ message: `${e.emotion} (${(e.intensity * 100).toFixed(0)}%)`,
416
+ });
417
+ send("meta", {
418
+ delta: `情绪: ${e.emotion} ${(e.intensity * 100).toFixed(0)}%${
419
+ e.trigger ? ` | 触发: ${e.trigger}` : ""
420
+ }\n`,
421
+ });
422
+ }
423
+ if (result.profileUpdated) {
424
+ send("meta", { delta: "profile 已更新\n" });
425
+ }
426
+
427
+ send("done", { ok: true });
428
+ } catch (err) {
429
+ send("error", { message: (err as Error).message });
430
+ } finally {
431
+ controller.close();
432
+ }
433
+ },
434
+ });
435
+
436
+ return new Response(stream, {
437
+ headers: {
438
+ "Content-Type": "text/event-stream; charset=utf-8",
439
+ "Cache-Control": "no-cache",
440
+ "Connection": "keep-alive",
441
+ },
442
+ });
443
+ }
444
+ // API: 清空 → 归档当前 + 开新(同人格)
445
+ if (req.method === "POST" && path === "/api/clear") {
446
+ if (state.currentSessionId) {
447
+ const cur = loadSession(DATA_DIR, state.currentSessionId);
448
+ if (cur) {
449
+ cur.history = state.history;
450
+ cur.lastActiveAt = Date.now() - 1;
451
+ cur.title = cur.title ?? (state.history[0]?.content.slice(0, 30) || "新对话");
452
+ saveSession(DATA_DIR, cur);
453
+ }
454
+ }
455
+ const blank = createSession(
456
+ DATA_DIR,
457
+ "default",
458
+ state.userId,
459
+ state.provider.model,
460
+ );
461
+ saveSession(DATA_DIR, blank);
462
+ state.currentSessionId = blank.id;
463
+ state.history = [];
464
+ return new Response(JSON.stringify({ ok: true, sessionId: blank.id }), {
465
+ headers: { "Content-Type": "application/json" },
466
+ });
467
+ }
468
+
469
+
470
+ // API: 加载指定 session(v0.15.0: 不再切 persona)
471
+ if (req.method === "POST" && path.startsWith("/api/session/load/")) {
472
+ const id = path.slice("/api/session/load/".length);
473
+ // 先保存当前
474
+ if (state.currentSessionId) {
475
+ const cur = loadSession(DATA_DIR, state.currentSessionId);
476
+ if (cur) {
477
+ cur.history = state.history;
478
+ cur.lastActiveAt = Date.now();
479
+ saveSession(DATA_DIR, cur);
480
+ }
481
+ }
482
+ const sess = loadSession(DATA_DIR, id);
483
+ if (!sess) {
484
+ return new Response(JSON.stringify({ error: "session not found" }), {
485
+ status: 404, headers: { "Content-Type": "application/json" },
486
+ });
487
+ }
488
+ state.currentSessionId = sess.id;
489
+ state.history = sess.history;
490
+ return new Response(JSON.stringify({
491
+ ok: true, sessionId: sess.id,
492
+ messageCount: sess.history.length,
493
+ }), { headers: { "Content-Type": "application/json" } });
494
+ }
495
+
496
+ // API: 删除指定 session(v0.14.0)
497
+ // DELETE /api/session/{id}
498
+ // 如果删的是当前 session:自动开新(同人格)并切换
499
+ if (req.method === "DELETE" && path.startsWith("/api/session/")) {
500
+ const id = path.slice("/api/session/".length);
501
+ if (!id) {
502
+ return new Response(JSON.stringify({ error: "session id required" }), {
503
+ status: 400, headers: { "Content-Type": "application/json" },
504
+ });
505
+ }
506
+ const sess = loadSession(DATA_DIR, id);
507
+ if (!sess) {
508
+ return new Response(JSON.stringify({ error: "session not found" }), {
509
+ status: 404, headers: { "Content-Type": "application/json" },
510
+ });
511
+ }
512
+ const wasCurrent = id === state.currentSessionId;
513
+ deleteSession(DATA_DIR, id);
514
+
515
+ if (wasCurrent) {
516
+ // 删的是当前 → 开新空 session
517
+ const blank = createSession(
518
+ DATA_DIR,
519
+ "default",
520
+ state.userId,
521
+ state.provider.model,
522
+ );
523
+ saveSession(DATA_DIR, blank);
524
+ state.currentSessionId = blank.id;
525
+ state.history = [];
526
+ return new Response(JSON.stringify({
527
+ ok: true,
528
+ deletedId: id,
529
+ newSessionId: blank.id,
530
+ switchedToNew: true,
531
+ }), { headers: { "Content-Type": "application/json" } });
532
+ }
533
+
534
+ return new Response(JSON.stringify({
535
+ ok: true,
536
+ deletedId: id,
537
+ switchedToNew: false,
538
+ }), { headers: { "Content-Type": "application/json" } });
539
+ }
540
+
541
+ // API: 新开空白对话(v0.18.0: 顺便检查人设是否需要 init)
542
+ if (req.method === "POST" && path === "/api/session/new") {
543
+ if (state.currentSessionId) {
544
+ const cur = loadSession(DATA_DIR, state.currentSessionId);
545
+ if (cur) {
546
+ cur.history = state.history;
547
+ // 归档时 lastActiveAt = now - 1,确保 blank 一定更新
548
+ cur.lastActiveAt = Date.now() - 1;
549
+ saveSession(DATA_DIR, cur);
550
+ }
551
+ }
552
+ const blank = createSession(
553
+ DATA_DIR,
554
+ "default",
555
+ state.userId,
556
+ state.provider.model,
557
+ );
558
+ saveSession(DATA_DIR, blank);
559
+ state.currentSessionId = blank.id;
560
+ state.history = [];
561
+ // 检查新人设是否需要 init
562
+ const existingPersona = loadPersonaForSession(DATA_DIR, blank.id);
563
+ return new Response(JSON.stringify({
564
+ ok: true,
565
+ sessionId: blank.id,
566
+ needsInit: existingPersona === null,
567
+ persona: existingPersona,
568
+ }), { headers: { "Content-Type": "application/json" } });
569
+ }
570
+
571
+ // API: 为某会话 init 人设(v0.18.0: 大五人格)
572
+ // POST /api/session/{id}/persona/init
573
+ // body: { description: string }
574
+ if (req.method === "POST" && path.match(/^\/api\/session\/[^/]+\/persona\/init$/)) {
575
+ const id = path.split("/")[3];
576
+ let body: { description?: string };
577
+ try {
578
+ body = await req.json();
579
+ } catch {
580
+ return new Response(JSON.stringify({ error: "Invalid JSON" }), {
581
+ status: 400, headers: { "Content-Type": "application/json" },
582
+ });
583
+ }
584
+ if (!body.description || !body.description.trim()) {
585
+ // 用户不填描述 → 用默认 OCEAN(0.5)
586
+ const def = defaultPersona(id);
587
+ savePersonaForSession(DATA_DIR, def);
588
+ return new Response(JSON.stringify({ ok: true, persona: def }), {
589
+ headers: { "Content-Type": "application/json" },
590
+ });
591
+ }
592
+ try {
593
+ const persona = await initPersonaFromDescription(
594
+ state.provider,
595
+ { description: body.description.trim(), sessionId: id },
596
+ DATA_DIR,
597
+ );
598
+ return new Response(JSON.stringify({ ok: true, persona }), {
599
+ headers: { "Content-Type": "application/json" },
600
+ });
601
+ } catch (err) {
602
+ return new Response(JSON.stringify({ error: (err as Error).message }), {
603
+ status: 500, headers: { "Content-Type": "application/json" },
604
+ });
605
+ }
606
+ }
607
+
608
+ return new Response("Method Not Allowed", { status: 405 });
609
+ },
610
+ });
611
+
612
+ console.log(`\n RememberMe 网页版`);
613
+ console.log(` → http://localhost:${server.port}\n`);
614
+ const total = state.personaLearner.signalCounts.positive +
615
+ state.personaLearner.signalCounts.negative +
616
+ state.personaLearner.signalCounts.neutral;
617
+ console.log(` 人设: ${total === 0 ? "冷启动(空白起点)" : `已学习 ${total} 轮反馈`}`);
618
+ console.log(` 模型: ${state.provider.model}\n`);
619
+ }
620
+
621
+ main().catch((err) => {
622
+ console.error("[fatal]", err);
623
+ process.exit(1);
624
+ });