@jokab1074/rememberme 0.0.0-stage → 0.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +787 -0
- package/LICENSE +202 -0
- package/README.en.md +459 -0
- package/README.md +477 -2
- package/dist/mcp/index.js +37334 -0
- package/package.json +67 -4
- package/server.json +38 -0
- package/settings.json.example +7 -0
- package/src/bigfive.ts +163 -0
- package/src/bootstrap.ts +104 -0
- package/src/classify.ts +186 -0
- package/src/compact.ts +225 -0
- package/src/context-file.ts +305 -0
- package/src/embedded-proactive.ts +214 -0
- package/src/evolution/access-tracker.ts +118 -0
- package/src/evolution/curator.ts +220 -0
- package/src/evolution/lifecycle.ts +175 -0
- package/src/feedback-detector.ts +177 -0
- package/src/i18n.ts +89 -0
- package/src/index.ts +1479 -0
- package/src/loop.ts +396 -0
- package/src/mcp/build.ts +64 -0
- package/src/mcp/config.ts +108 -0
- package/src/mcp/index.ts +66 -0
- package/src/mcp/instructions.ts +44 -0
- package/src/mcp/logger.ts +32 -0
- package/src/mcp/provider.ts +142 -0
- package/src/mcp/server.ts +52 -0
- package/src/mcp/tools/memory.ts +126 -0
- package/src/mcp/tools/profile.ts +67 -0
- package/src/mcp/tools/record-turn.ts +284 -0
- package/src/memory-extract.ts +390 -0
- package/src/memory.ts +790 -0
- package/src/persona-init.ts +153 -0
- package/src/persona-learner.ts +349 -0
- package/src/proactive.ts +557 -0
- package/src/profile.ts +1095 -0
- package/src/prompt.ts +288 -0
- package/src/provider.ts +292 -0
- package/src/reflection.ts +552 -0
- package/src/sessions.ts +140 -0
- package/src/timeline.ts +208 -0
- package/src/utils.ts +91 -0
- package/src/web-security.ts +43 -0
- package/src/web.ts +724 -0
package/src/timeline.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// src/timeline.ts
|
|
2
|
+
// 情绪时间线(独立于 5 类记忆)。
|
|
3
|
+
//
|
|
4
|
+
// 设计:按时间序列记录每一次对话 / 情绪识别 / 重要事件。
|
|
5
|
+
// 存为 JSONL,每行一条。查询方便、可独立分析情绪漂移。
|
|
6
|
+
|
|
7
|
+
import { readFile, writeFile, mkdir, appendFile } from "node:fs/promises";
|
|
8
|
+
import { join, dirname } from "node:path";
|
|
9
|
+
|
|
10
|
+
export type EmotionCategory =
|
|
11
|
+
| "joy" // 开心
|
|
12
|
+
| "sadness" // 难过
|
|
13
|
+
| "anger" // 生气
|
|
14
|
+
| "fear" // 害怕 / 焦虑
|
|
15
|
+
| "surprise" // 惊讶
|
|
16
|
+
| "disgust" // 厌恶
|
|
17
|
+
| "neutral" // 平静
|
|
18
|
+
| "mixed"; // 复杂
|
|
19
|
+
|
|
20
|
+
export const EMOTION_LABEL: Record<EmotionCategory, string> = {
|
|
21
|
+
joy: "开心",
|
|
22
|
+
sadness: "难过",
|
|
23
|
+
anger: "生气",
|
|
24
|
+
fear: "焦虑",
|
|
25
|
+
surprise: "惊讶",
|
|
26
|
+
disgust: "厌恶",
|
|
27
|
+
neutral: "平静",
|
|
28
|
+
mixed: "复杂",
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const EMOTION_EMOJI: Record<EmotionCategory, string> = {
|
|
32
|
+
joy: "😊",
|
|
33
|
+
sadness: "😔",
|
|
34
|
+
anger: "😤",
|
|
35
|
+
fear: "😰",
|
|
36
|
+
surprise: "😮",
|
|
37
|
+
disgust: "😒",
|
|
38
|
+
neutral: "😐",
|
|
39
|
+
mixed: "🤔",
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type TimelineEntry = {
|
|
43
|
+
/** Unix 毫秒时间戳 */
|
|
44
|
+
ts: number;
|
|
45
|
+
/** ISO 日期(方便阅读) */
|
|
46
|
+
date: string;
|
|
47
|
+
/** 情绪类别 */
|
|
48
|
+
emotion: EmotionCategory;
|
|
49
|
+
/** 强度 0-1 */
|
|
50
|
+
intensity: number;
|
|
51
|
+
/** 触发器(可选) */
|
|
52
|
+
trigger?: string;
|
|
53
|
+
/** 用户原文片段(可选,最多 200 字) */
|
|
54
|
+
userExcerpt?: string;
|
|
55
|
+
/** 我的回应(可选,最多 200 字) */
|
|
56
|
+
myResponseExcerpt?: string;
|
|
57
|
+
/** 关联的记忆文件名(可选) */
|
|
58
|
+
relatedMemory?: string;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export type TimelineStats = {
|
|
62
|
+
totalEntries: number;
|
|
63
|
+
emotionCounts: Partial<Record<EmotionCategory, number>>;
|
|
64
|
+
/** 最近 7 天的情绪类别 */
|
|
65
|
+
recent7Days: Partial<Record<EmotionCategory, number>>;
|
|
66
|
+
/** 当前主导情绪(最近 3 条) */
|
|
67
|
+
currentDominant: EmotionCategory | null;
|
|
68
|
+
/** 平均强度(最近 7 天) */
|
|
69
|
+
avgIntensity7Days: number;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export class Timeline {
|
|
73
|
+
private filePath: string;
|
|
74
|
+
|
|
75
|
+
constructor(timelineDir: string) {
|
|
76
|
+
this.filePath = join(timelineDir, "emotional_timeline.jsonl");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async ensure(): Promise<void> {
|
|
80
|
+
await mkdir(dirname(this.filePath), { recursive: true });
|
|
81
|
+
try {
|
|
82
|
+
await readFile(this.filePath, "utf-8");
|
|
83
|
+
} catch {
|
|
84
|
+
await writeFile(this.filePath, "", "utf-8");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 追加一条时间线记录。
|
|
90
|
+
*/
|
|
91
|
+
async append(entry: Omit<TimelineEntry, "ts" | "date">): Promise<void> {
|
|
92
|
+
await this.ensure();
|
|
93
|
+
const now = new Date();
|
|
94
|
+
const full: TimelineEntry = {
|
|
95
|
+
...entry,
|
|
96
|
+
ts: now.getTime(),
|
|
97
|
+
date: now.toISOString(),
|
|
98
|
+
};
|
|
99
|
+
await appendFile(this.filePath, JSON.stringify(full) + "\n", "utf-8");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 读取全部记录(按时间正序)。
|
|
104
|
+
*/
|
|
105
|
+
async readAll(): Promise<TimelineEntry[]> {
|
|
106
|
+
await this.ensure();
|
|
107
|
+
let raw: string;
|
|
108
|
+
try {
|
|
109
|
+
raw = await readFile(this.filePath, "utf-8");
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
const entries: TimelineEntry[] = [];
|
|
114
|
+
for (const line of raw.split("\n")) {
|
|
115
|
+
const trimmed = line.trim();
|
|
116
|
+
if (!trimmed) continue;
|
|
117
|
+
try {
|
|
118
|
+
entries.push(JSON.parse(trimmed));
|
|
119
|
+
} catch {
|
|
120
|
+
// 跳过损坏的行
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return entries;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 读取最近 N 条。
|
|
128
|
+
*/
|
|
129
|
+
async readRecent(n: number): Promise<TimelineEntry[]> {
|
|
130
|
+
const all = await this.readAll();
|
|
131
|
+
return all.slice(-n);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 计算情绪统计。
|
|
136
|
+
*/
|
|
137
|
+
async getStats(): Promise<TimelineStats> {
|
|
138
|
+
const all = await this.readAll();
|
|
139
|
+
const now = Date.now();
|
|
140
|
+
const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000;
|
|
141
|
+
|
|
142
|
+
const emotionCounts: Partial<Record<EmotionCategory, number>> = {};
|
|
143
|
+
const recent7Days: Partial<Record<EmotionCategory, number>> = {};
|
|
144
|
+
let intensitySum = 0;
|
|
145
|
+
let intensityCount = 0;
|
|
146
|
+
|
|
147
|
+
for (const e of all) {
|
|
148
|
+
emotionCounts[e.emotion] = (emotionCounts[e.emotion] ?? 0) + 1;
|
|
149
|
+
if (e.ts >= sevenDaysAgo) {
|
|
150
|
+
recent7Days[e.emotion] = (recent7Days[e.emotion] ?? 0) + 1;
|
|
151
|
+
intensitySum += e.intensity;
|
|
152
|
+
intensityCount += 1;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const last3 = all.slice(-3);
|
|
157
|
+
const last3Counts: Partial<Record<EmotionCategory, number>> = {};
|
|
158
|
+
for (const e of last3) {
|
|
159
|
+
last3Counts[e.emotion] = (last3Counts[e.emotion] ?? 0) + 1;
|
|
160
|
+
}
|
|
161
|
+
const currentDominant =
|
|
162
|
+
(Object.entries(last3Counts).sort(
|
|
163
|
+
(a, b) => (b[1] ?? 0) - (a[1] ?? 0),
|
|
164
|
+
)[0]?.[0] as EmotionCategory | undefined) ?? null;
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
totalEntries: all.length,
|
|
168
|
+
emotionCounts,
|
|
169
|
+
recent7Days,
|
|
170
|
+
currentDominant,
|
|
171
|
+
avgIntensity7Days: intensityCount > 0 ? intensitySum / intensityCount : 0,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 渲染成可读的 prompt 摘要(注入到 system prompt)。
|
|
177
|
+
*/
|
|
178
|
+
async renderSummary(maxEntries: number = 5): Promise<string> {
|
|
179
|
+
const recent = await this.readRecent(maxEntries);
|
|
180
|
+
if (recent.length === 0) return "(尚无情绪记录)";
|
|
181
|
+
|
|
182
|
+
const lines = recent.map((e) => {
|
|
183
|
+
const date = new Date(e.ts).toLocaleString("zh-CN", {
|
|
184
|
+
month: "numeric",
|
|
185
|
+
day: "numeric",
|
|
186
|
+
hour: "numeric",
|
|
187
|
+
minute: "numeric",
|
|
188
|
+
});
|
|
189
|
+
const emoji = EMOTION_EMOJI[e.emotion];
|
|
190
|
+
const label = EMOTION_LABEL[e.emotion];
|
|
191
|
+
const intensity = "⚡".repeat(Math.max(1, Math.round(e.intensity * 5)));
|
|
192
|
+
const trigger = e.trigger ? ` (${e.trigger})` : "";
|
|
193
|
+
const excerpt = e.userExcerpt ? ` — "${e.userExcerpt.slice(0, 60)}…"` : "";
|
|
194
|
+
return `- ${date} ${emoji} ${label} ${intensity}${trigger}${excerpt}`;
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
const stats = await this.getStats();
|
|
198
|
+
const dominantLine = stats.currentDominant
|
|
199
|
+
? `\n\n**当前主导情绪**:${EMOTION_LABEL[stats.currentDominant]} ${EMOTION_EMOJI[stats.currentDominant]}`
|
|
200
|
+
: "";
|
|
201
|
+
|
|
202
|
+
return (
|
|
203
|
+
`## 最近情绪轨迹(最多 ${maxEntries} 条)\n\n` +
|
|
204
|
+
lines.join("\n") +
|
|
205
|
+
dominantLine
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// src/utils.ts
|
|
2
|
+
// 工具函数。
|
|
3
|
+
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 检查字符串是否是 JSON 字符串。
|
|
8
|
+
*/
|
|
9
|
+
export function isJson(str: string): boolean {
|
|
10
|
+
try {
|
|
11
|
+
JSON.parse(str);
|
|
12
|
+
return true;
|
|
13
|
+
} catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 安全地从 stdin 读取一行(处理 Ctrl+C)。
|
|
20
|
+
*/
|
|
21
|
+
export async function readLine(
|
|
22
|
+
prompt: string,
|
|
23
|
+
rl: { question: (q: string, cb: (line: string) => void) => void },
|
|
24
|
+
): Promise<string> {
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
rl.question(prompt, (line) => resolve(line));
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 简易 JSON 解析(容忍 markdown code block)。
|
|
32
|
+
*/
|
|
33
|
+
export function parseJsonLoose<T = unknown>(text: string): T | null {
|
|
34
|
+
const cleaned = text
|
|
35
|
+
.trim()
|
|
36
|
+
.replace(/^```(?:json)?\n/, "")
|
|
37
|
+
.replace(/\n```$/, "");
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(cleaned) as T;
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 等待指定毫秒。
|
|
47
|
+
*/
|
|
48
|
+
export function sleep(ms: number): Promise<void> {
|
|
49
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 极简 token 估算:中文字符按 1.5 token / 字,英文按 0.3 token / 字。
|
|
54
|
+
*
|
|
55
|
+
* 准确度不如 tiktoken,但对预算判断够用(估算偏差只影响裁剪位置,不影响正确性)。
|
|
56
|
+
* 放在 utils 而不是 compact,因为 memory.ts 的索引预算也要用它——
|
|
57
|
+
* 让 memory.ts 反向依赖 compact.ts 会把压缩逻辑拖进记忆模块的依赖图。
|
|
58
|
+
*/
|
|
59
|
+
export function estimateTokens(text: string): number {
|
|
60
|
+
if (!text) return 0;
|
|
61
|
+
let cjkChars = 0;
|
|
62
|
+
let otherChars = 0;
|
|
63
|
+
for (const ch of text) {
|
|
64
|
+
// 简单判断 CJK 字符(中日韩统一表意 + 平假/片假 + 韩文音节)
|
|
65
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
66
|
+
if (
|
|
67
|
+
(code >= 0x4e00 && code <= 0x9fff) ||
|
|
68
|
+
(code >= 0x3040 && code <= 0x309f) ||
|
|
69
|
+
(code >= 0x30a0 && code <= 0x30ff) ||
|
|
70
|
+
(code >= 0xac00 && code <= 0xd7af)
|
|
71
|
+
) {
|
|
72
|
+
cjkChars++;
|
|
73
|
+
} else {
|
|
74
|
+
otherChars++;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return Math.ceil(cjkChars * 1.5 + otherChars * 0.3);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 彩色输出(ANSI)。
|
|
82
|
+
*/
|
|
83
|
+
export const color = {
|
|
84
|
+
gray: (s: string) => `\x1b[90m${s}\x1b[0m`,
|
|
85
|
+
cyan: (s: string) => `\x1b[36m${s}\x1b[0m`,
|
|
86
|
+
yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
|
|
87
|
+
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
|
|
88
|
+
red: (s: string) => `\x1b[31m${s}\x1b[0m`,
|
|
89
|
+
bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
|
|
90
|
+
dim: (s: string) => `\x1b[2m${s}\x1b[0m`,
|
|
91
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// src/web-security.ts
|
|
2
|
+
//
|
|
3
|
+
// 网页版的网络暴露面相关的纯函数(单独成文件,方便单测直接 import
|
|
4
|
+
// —— src/web.ts 一被 import 就会启动服务器,不能在测试里直接引)。
|
|
5
|
+
//
|
|
6
|
+
// ⚠️ 背景(v0.22.0 修复的真实安全问题):
|
|
7
|
+
//
|
|
8
|
+
// Bun.serve 不写 hostname 时**默认绑 0.0.0.0**(所有网卡)。
|
|
9
|
+
// 同一局域网里任何设备都能访问这个服务,而 POST /api/send 会直接
|
|
10
|
+
// 用用户的 API key 调 LLM —— key 不会"泄露",但额度会被别人烧掉。
|
|
11
|
+
// /api/messages、/api/sessions 还会把对话历史读走,/api/clear 能删会话。
|
|
12
|
+
//
|
|
13
|
+
// 修复后的策略:
|
|
14
|
+
// 1. 默认只监听 127.0.0.1(要放开用 HOST=0.0.0.0)
|
|
15
|
+
// 2. 一旦监听**非回环**地址,必须配 EC_WEB_TOKEN,否则**拒绝启动**
|
|
16
|
+
// (fail-closed:宁可起不来,也不要默默把 key 送人)
|
|
17
|
+
// 3. 所有 /api/* 做同源检查,挡浏览器发起的 CSRF
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 是否是本机回环地址(只有这种地址才不需要鉴权)。
|
|
21
|
+
*
|
|
22
|
+
* 覆盖:127.0.0.0/8 整段、localhost、IPv6 的 ::1。
|
|
23
|
+
*/
|
|
24
|
+
export function isLoopbackHost(host: string): boolean {
|
|
25
|
+
const h = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
26
|
+
if (h === "localhost" || h === "::1" || h === "0:0:0:0:0:0:0:1") return true;
|
|
27
|
+
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 常量时间比较。
|
|
32
|
+
*
|
|
33
|
+
* 逐字符比较会在第一个不同的字节就返回,理论上能被时序攻击推出 token 前缀。
|
|
34
|
+
* 这里累加 XOR 差异,保证耗时与内容无关。
|
|
35
|
+
*/
|
|
36
|
+
export function safeEqual(a: string, b: string): boolean {
|
|
37
|
+
if (a.length !== b.length) return false;
|
|
38
|
+
let diff = 0;
|
|
39
|
+
for (let i = 0; i < a.length; i++) {
|
|
40
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
41
|
+
}
|
|
42
|
+
return diff === 0;
|
|
43
|
+
}
|