@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.
- package/ARCHITECTURE.md +787 -0
- package/LICENSE +201 -0
- package/README.en.md +441 -0
- package/README.md +459 -2
- package/dist/mcp/index.js +37287 -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 +43 -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 +239 -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 +1008 -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.ts +624 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/mcp/logger.ts
|
|
2
|
+
//
|
|
3
|
+
// MCP server 的日志。
|
|
4
|
+
//
|
|
5
|
+
// ⚠️ 关键约束:走 stdio 传输时,**stdout 是 JSON-RPC 的专属通道**。
|
|
6
|
+
// 只要有一行 console.log 打到 stdout,客户端就会收到非法 JSON,直接崩。
|
|
7
|
+
//
|
|
8
|
+
// 所以:
|
|
9
|
+
// 1. 本模块所有日志一律走 console.error(stderr)
|
|
10
|
+
// 2. 入口处调用 protectStdout(),把残留的 console.log / console.info
|
|
11
|
+
// 劫持到 stderr —— 防止现有代码里的 console.log 漏网
|
|
12
|
+
|
|
13
|
+
const PREFIX = "[rememberme-mcp]";
|
|
14
|
+
|
|
15
|
+
export const log = {
|
|
16
|
+
info: (...args: unknown[]) => console.error(PREFIX, ...args),
|
|
17
|
+
warn: (...args: unknown[]) => console.error(PREFIX, "WARN", ...args),
|
|
18
|
+
error: (...args: unknown[]) => console.error(PREFIX, "ERROR", ...args),
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 把 console.log / console.info / console.debug 劫持到 stderr。
|
|
23
|
+
*
|
|
24
|
+
* 幂等;只影响当前进程。
|
|
25
|
+
*/
|
|
26
|
+
export function protectStdout(): void {
|
|
27
|
+
const stderr = console.error.bind(console);
|
|
28
|
+
console.log = stderr;
|
|
29
|
+
console.info = stderr;
|
|
30
|
+
console.debug = stderr;
|
|
31
|
+
console.warn = stderr;
|
|
32
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// src/mcp/provider.ts
|
|
2
|
+
//
|
|
3
|
+
// MCP server 自己的 LLM provider。
|
|
4
|
+
//
|
|
5
|
+
// 为什么 server 要自己持 key:
|
|
6
|
+
// - MCP 官方在 2026-07-28 规范修订(SEP-2577)里废弃了 sampling,
|
|
7
|
+
// 推荐的迁移路径就是「server 直接调 LLM provider API」。
|
|
8
|
+
// - 实际上几乎所有客户端都不声明 sampling 能力(实测 Claude Code 2.1.326:
|
|
9
|
+
// capabilities = { elicitation, roots },无 sampling),
|
|
10
|
+
// 只有 VS Code 是文档+实测都对得上的少数派。
|
|
11
|
+
//
|
|
12
|
+
// 好消息:**用的是和现有 RememberMe(Web/CLI)完全同一份 settings.json**。
|
|
13
|
+
// 仓库版(bun run src/mcp/index.ts)→ 已经在用 RememberMe 的用户零额外配置。
|
|
14
|
+
// npm 版(npx)→ 包目录在 node_modules/ 里,找不到仓库那份,
|
|
15
|
+
// 需要 ~/.rememberme/settings.json(或 REMEMBERME_SETTINGS 指过去)。
|
|
16
|
+
//
|
|
17
|
+
// 惰性创建:没有 key 时 server 照样能启动(只读工具可用),
|
|
18
|
+
// 写工具会返回一条清楚的错误说明,而不是让整个 server 起不来。
|
|
19
|
+
|
|
20
|
+
import { loadProjectEnv, pickDefaultModel } from "../bootstrap.ts";
|
|
21
|
+
import { createProvider, type ModelProvider } from "../provider.ts";
|
|
22
|
+
import { resolveSettingsPath } from "./config.ts";
|
|
23
|
+
import { log } from "./logger.ts";
|
|
24
|
+
|
|
25
|
+
let cached: ModelProvider | null = null;
|
|
26
|
+
let cachedError: string | null = null;
|
|
27
|
+
let envLoaded = false;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 「没有可用凭据」时给用户看的提示。
|
|
31
|
+
*
|
|
32
|
+
* 为什么需要单独判一次:Anthropic SDK 的构造函数**不校验 key**(传 undefined 也不报错),
|
|
33
|
+
* 所以没有 key 时 createProvider() 照样返回一个 provider → providerStatus().ok === true →
|
|
34
|
+
* 下面那句友好提示永远不会显示,用户实际看到的是调用时的 401。
|
|
35
|
+
*
|
|
36
|
+
* 提前判掉,用户就能直接知道该去哪儿配 key。
|
|
37
|
+
*/
|
|
38
|
+
const NO_CREDENTIAL_ERROR =
|
|
39
|
+
"未配置 API key。请在 ~/.rememberme/settings.json 或项目 settings.json 里设置 " +
|
|
40
|
+
"ANTHROPIC_API_KEY(以及可选的 ANTHROPIC_BASE_URL / ANTHROPIC_MODEL)。";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 有没有任何可用的凭据。
|
|
44
|
+
*
|
|
45
|
+
* 注意 loadProjectEnv() 会无条件删掉 ANTHROPIC_AUTH_TOKEN
|
|
46
|
+
* (SDK 优先读它,会绕开 settings.json 里的 ANTHROPIC_API_KEY 导致 401),
|
|
47
|
+
* 所以这里只认 ANTHROPIC_API_KEY / OPENAI_API_KEY。
|
|
48
|
+
*/
|
|
49
|
+
function hasCredential(): boolean {
|
|
50
|
+
return (
|
|
51
|
+
!!process.env.ANTHROPIC_API_KEY?.trim() ||
|
|
52
|
+
!!process.env.OPENAI_API_KEY?.trim()
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 载入 LLM 配置(只做一次)。
|
|
58
|
+
*
|
|
59
|
+
* loadProjectEnv 会用 settings.json 覆盖 shell 环境变量,
|
|
60
|
+
* 并且**清掉 ANTHROPIC_AUTH_TOKEN** —— 那很重要:
|
|
61
|
+
* Anthropic SDK 同时读到 apiKey 和 authToken 会发两种认证头,
|
|
62
|
+
* 网关认不出来就 401。
|
|
63
|
+
*/
|
|
64
|
+
function loadEnvOnce(): void {
|
|
65
|
+
if (envLoaded) return;
|
|
66
|
+
envLoaded = true;
|
|
67
|
+
const settingsPath = resolveSettingsPath();
|
|
68
|
+
if (settingsPath) {
|
|
69
|
+
loadProjectEnv({ settingsPath });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 拿到 provider;没有可用配置时返回 null。 */
|
|
74
|
+
export function getProvider(): ModelProvider | null {
|
|
75
|
+
if (cached) return cached;
|
|
76
|
+
if (cachedError) return null;
|
|
77
|
+
|
|
78
|
+
// 只读模式:不调用 LLM。给不想让 server 花 API 额度的用户 / 测试用。
|
|
79
|
+
if (process.env.REMEMBERME_MCP_DISABLE_LLM === "1") {
|
|
80
|
+
cachedError = "已通过 REMEMBERME_MCP_DISABLE_LLM=1 禁用 LLM 调用(只读模式)";
|
|
81
|
+
log.warn(cachedError);
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
loadEnvOnce();
|
|
87
|
+
|
|
88
|
+
// 没有任何凭据 → 直接判为「没配置」,别等 API 调用时甩一个 401 出来
|
|
89
|
+
if (!hasCredential()) {
|
|
90
|
+
cachedError = NO_CREDENTIAL_ERROR;
|
|
91
|
+
log.warn(cachedError);
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const model = pickDefaultModel();
|
|
96
|
+
// 与 src/index.ts 的逻辑保持一致:
|
|
97
|
+
// 模型名是 claude* 或者有 Anthropic 兼容配置 → 走 anthropic provider
|
|
98
|
+
const provider =
|
|
99
|
+
model.startsWith("claude") ||
|
|
100
|
+
process.env.ANTHROPIC_API_KEY ||
|
|
101
|
+
process.env.ANTHROPIC_BASE_URL
|
|
102
|
+
? createProvider({
|
|
103
|
+
kind: "anthropic",
|
|
104
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
105
|
+
model,
|
|
106
|
+
})
|
|
107
|
+
: createProvider();
|
|
108
|
+
cached = provider;
|
|
109
|
+
log.info(`LLM provider 就绪:${provider.name} / ${provider.model}`);
|
|
110
|
+
return provider;
|
|
111
|
+
} catch (e) {
|
|
112
|
+
cachedError = (e as Error).message;
|
|
113
|
+
log.warn("没有可用的 LLM 配置:", cachedError);
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** provider 状态(给健康检查工具用)。 */
|
|
119
|
+
export function providerStatus(): {
|
|
120
|
+
ok: boolean;
|
|
121
|
+
model?: string;
|
|
122
|
+
error?: string;
|
|
123
|
+
} {
|
|
124
|
+
const p = getProvider();
|
|
125
|
+
if (p) return { ok: true, model: p.model };
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
error: cachedError ?? NO_CREDENTIAL_ERROR,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 清掉缓存(provider / 错误 / env 已加载标记)。
|
|
134
|
+
*
|
|
135
|
+
* 给测试用:provider 是模块级单例,测「有 key」和「没 key」两条路径时需要复位。
|
|
136
|
+
*/
|
|
137
|
+
export function resetProviderCache(): void {
|
|
138
|
+
cached = null;
|
|
139
|
+
cachedError = null;
|
|
140
|
+
envLoaded = false;
|
|
141
|
+
}
|
|
142
|
+
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// src/mcp/server.ts
|
|
2
|
+
//
|
|
3
|
+
// RememberMe 的 MCP server。
|
|
4
|
+
//
|
|
5
|
+
// **单一路径**(不再有双路径):
|
|
6
|
+
//
|
|
7
|
+
// 写工具只有 record_turn 一个。
|
|
8
|
+
// 宿主只判断「这轮值不值得记」(条件式调用 → 实测可靠);
|
|
9
|
+
// 「记成什么」由 server 负责:缓冲攒够 → server 调自己的 LLM 抽取,
|
|
10
|
+
// 用 RememberMe 原版的 extractMemoryCandidates()。
|
|
11
|
+
//
|
|
12
|
+
// 为什么不用 MCP 的 sampling(server 借宿主的模型):
|
|
13
|
+
// - MCP 官方在 2026-07-28 规范修订(SEP-2577)里废弃了 sampling,
|
|
14
|
+
// 推荐的迁移路径就是「server 直接调 LLM provider API」。
|
|
15
|
+
// - 实际上几乎所有客户端都不声明 sampling 能力(实测 Claude Code 2.1.326:
|
|
16
|
+
// capabilities = { elicitation, roots },无 sampling);只有 VS Code 是例外。
|
|
17
|
+
// - 好处:**不用能力协商**,所有客户端行为一致,工具集固定 4 个。
|
|
18
|
+
//
|
|
19
|
+
// 读工具:list_memories / read_memory / read_profile
|
|
20
|
+
|
|
21
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
22
|
+
import { registerMemoryTools } from "./tools/memory.ts";
|
|
23
|
+
import { registerReadProfileTool } from "./tools/profile.ts";
|
|
24
|
+
import { registerRecordTurnTool } from "./tools/record-turn.ts";
|
|
25
|
+
import { INSTRUCTIONS } from "./instructions.ts";
|
|
26
|
+
import { log } from "./logger.ts";
|
|
27
|
+
|
|
28
|
+
export const SERVER_NAME = "rememberme";
|
|
29
|
+
export const SERVER_VERSION = "0.22.0";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 创建 MCP server(不连接 transport —— 便于测试)。
|
|
33
|
+
*/
|
|
34
|
+
export function createServer(): McpServer {
|
|
35
|
+
const server = new McpServer(
|
|
36
|
+
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
37
|
+
{ instructions: INSTRUCTIONS },
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
// ---- 读工具 ----
|
|
41
|
+
registerMemoryTools(server);
|
|
42
|
+
registerReadProfileTool(server);
|
|
43
|
+
|
|
44
|
+
// ---- 唯一的写工具 ----
|
|
45
|
+
registerRecordTurnTool(server);
|
|
46
|
+
|
|
47
|
+
log.info(
|
|
48
|
+
`MCP server 就绪:${SERVER_NAME} v${SERVER_VERSION}(4 个工具)`,
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
return server;
|
|
52
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// src/mcp/tools/memory.ts
|
|
2
|
+
//
|
|
3
|
+
// 记忆读取工具:list_memories / read_memory
|
|
4
|
+
//
|
|
5
|
+
// 注意 read_memory 的实现:
|
|
6
|
+
// **不能**用 readMemoryFile(dir, `${type}/${name}`) —— resolveMemoryPath()
|
|
7
|
+
// 拼路径时漏了 .md 后缀(已在 src/memory.ts 修复,但这里直接用 scanMemory
|
|
8
|
+
// + 精确匹配更稳,也不依赖那个函数的边界行为)。
|
|
9
|
+
|
|
10
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { scanMemory, formatManifest, type MemoryFile } from "../../memory.ts";
|
|
13
|
+
import { paths } from "../config.ts";
|
|
14
|
+
import { log } from "../logger.ts";
|
|
15
|
+
|
|
16
|
+
export function registerMemoryTools(server: McpServer): void {
|
|
17
|
+
// ---- list_memories ----
|
|
18
|
+
server.registerTool(
|
|
19
|
+
"list_memories",
|
|
20
|
+
{
|
|
21
|
+
title: "列出全部长期记忆",
|
|
22
|
+
description:
|
|
23
|
+
"列出用户的所有长期记忆(情绪模式 / 生活事件 / 外部资源),含名称与一句话描述。" +
|
|
24
|
+
"当用户提到过去、之前、记得什么,或你需要了解用户的长期背景时调用。" +
|
|
25
|
+
"返回全部条目;拿到列表后再用 read_memory 取需要的那条的完整内容。",
|
|
26
|
+
inputSchema: {
|
|
27
|
+
type: z
|
|
28
|
+
.enum(["emotion", "event", "reference"])
|
|
29
|
+
.optional()
|
|
30
|
+
.describe("可选。按类型过滤;不填表示列出全部。"),
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
async (args) => {
|
|
34
|
+
try {
|
|
35
|
+
const all = await scanMemory(paths.memory);
|
|
36
|
+
const files: MemoryFile[] = args.type
|
|
37
|
+
? all.filter((f) => f.subtype === args.type)
|
|
38
|
+
: all;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
content: [
|
|
42
|
+
{
|
|
43
|
+
type: "text",
|
|
44
|
+
text:
|
|
45
|
+
files.length === 0
|
|
46
|
+
? "(没有匹配的记忆文件)"
|
|
47
|
+
: `找到 ${files.length} 条记忆:\n\n${formatManifest(files)}`,
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
structuredContent: {
|
|
51
|
+
memories: files.map((f) => ({
|
|
52
|
+
type: f.subtype,
|
|
53
|
+
name: f.name,
|
|
54
|
+
description: f.description,
|
|
55
|
+
date: new Date(f.mtimeMs).toISOString().slice(0, 10),
|
|
56
|
+
})),
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
} catch (e) {
|
|
60
|
+
log.error("list_memories 失败:", (e as Error).message);
|
|
61
|
+
return {
|
|
62
|
+
content: [
|
|
63
|
+
{ type: "text", text: `读取记忆失败:${(e as Error).message}` },
|
|
64
|
+
],
|
|
65
|
+
isError: true,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
// ---- read_memory ----
|
|
72
|
+
server.registerTool(
|
|
73
|
+
"read_memory",
|
|
74
|
+
{
|
|
75
|
+
title: "读取单条记忆的完整内容",
|
|
76
|
+
description:
|
|
77
|
+
"读取一条长期记忆的完整正文(含触发条件、表现、证据、时间、情感影响等结构化字段)。" +
|
|
78
|
+
"list_memories 之后,对真正相关的条目调用本工具获取完整信息。",
|
|
79
|
+
inputSchema: {
|
|
80
|
+
type: z
|
|
81
|
+
.enum(["emotion", "event", "reference"])
|
|
82
|
+
.describe("记忆类型:emotion=情绪模式,event=生活事件,reference=外部资源。"),
|
|
83
|
+
name: z.string().describe("记忆名(如 work-burnout),不含 .md 后缀。"),
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
async (args) => {
|
|
87
|
+
try {
|
|
88
|
+
const all = await scanMemory(paths.memory);
|
|
89
|
+
const file = all.find(
|
|
90
|
+
(f) => f.subtype === args.type && f.filename === args.name,
|
|
91
|
+
);
|
|
92
|
+
if (!file) {
|
|
93
|
+
return {
|
|
94
|
+
content: [
|
|
95
|
+
{
|
|
96
|
+
type: "text",
|
|
97
|
+
text:
|
|
98
|
+
`记忆不存在:${args.type}/${args.name}。` +
|
|
99
|
+
`可用条目:${all.map((f) => `${f.subtype}/${f.filename}`).join(", ")}`,
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
isError: true,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
content: [{ type: "text", text: file.body }],
|
|
107
|
+
structuredContent: {
|
|
108
|
+
type: file.subtype,
|
|
109
|
+
name: file.name,
|
|
110
|
+
description: file.description,
|
|
111
|
+
body: file.body,
|
|
112
|
+
fields: file.fields,
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
} catch (e) {
|
|
116
|
+
log.error("read_memory 失败:", (e as Error).message);
|
|
117
|
+
return {
|
|
118
|
+
content: [
|
|
119
|
+
{ type: "text", text: `读取记忆失败:${(e as Error).message}` },
|
|
120
|
+
],
|
|
121
|
+
isError: true,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
);
|
|
126
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// src/mcp/tools/profile.ts
|
|
2
|
+
//
|
|
3
|
+
// 画像工具:read_profile(只读)
|
|
4
|
+
//
|
|
5
|
+
// 为什么**不**暴露 update_profile:
|
|
6
|
+
// 画像更新由 server 内部复用现有的 maybeUpdateProfile() 完成
|
|
7
|
+
// (和 Web/CLI 完全同一条代码路径:段1/2/6 由 LLM 抽取,段3/4/5 派生重算)。
|
|
8
|
+
// 宿主不需要学一套「怎么写画像段」的规则 —— 工具更少、宿主负担更小。
|
|
9
|
+
//
|
|
10
|
+
// 顺带说明:段 3 关注议题 / 段 4 已知偏好与禁忌 / 段 5 长期情绪基线 是**派生段**
|
|
11
|
+
// (由 syncFromSources 从 memory/ + learned-prefs 重算),外部写入会被覆盖。
|
|
12
|
+
|
|
13
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import { loadProfile } from "../../profile.ts";
|
|
16
|
+
import { paths } from "../config.ts";
|
|
17
|
+
import { log } from "../logger.ts";
|
|
18
|
+
|
|
19
|
+
export function registerReadProfileTool(server: McpServer): void {
|
|
20
|
+
server.registerTool(
|
|
21
|
+
"read_profile",
|
|
22
|
+
{
|
|
23
|
+
title: "读取用户画像",
|
|
24
|
+
description:
|
|
25
|
+
"读取用户的长期画像(基本信息、沟通风格、关注议题、已知偏好与禁忌、长期情绪基线、近期变化)。" +
|
|
26
|
+
"当用户问「我是谁 / 我的偏好 / 我是什么样的人」时调用。",
|
|
27
|
+
inputSchema: {
|
|
28
|
+
section: z
|
|
29
|
+
.enum([
|
|
30
|
+
"基本信息",
|
|
31
|
+
"沟通风格",
|
|
32
|
+
"关注议题",
|
|
33
|
+
"已知偏好与禁忌",
|
|
34
|
+
"长期情绪基线",
|
|
35
|
+
"近期变化",
|
|
36
|
+
])
|
|
37
|
+
.optional()
|
|
38
|
+
.describe("可选。只读取指定段;不填表示读取全部 6 段。"),
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
async (args) => {
|
|
42
|
+
try {
|
|
43
|
+
const profile = await loadProfile(paths.data, {
|
|
44
|
+
memoryDir: paths.memory,
|
|
45
|
+
});
|
|
46
|
+
const sections = args.section
|
|
47
|
+
? { [args.section]: profile.sections[args.section] ?? "" }
|
|
48
|
+
: profile.sections;
|
|
49
|
+
const text = Object.entries(sections)
|
|
50
|
+
.map(([k, v]) => `## ${k}\n${v || "(暂无)"}`)
|
|
51
|
+
.join("\n\n");
|
|
52
|
+
return {
|
|
53
|
+
content: [{ type: "text", text }],
|
|
54
|
+
structuredContent: { sections },
|
|
55
|
+
};
|
|
56
|
+
} catch (e) {
|
|
57
|
+
log.error("read_profile 失败:", (e as Error).message);
|
|
58
|
+
return {
|
|
59
|
+
content: [
|
|
60
|
+
{ type: "text", text: `读取画像失败:${(e as Error).message}` },
|
|
61
|
+
],
|
|
62
|
+
isError: true,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
);
|
|
67
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// src/mcp/tools/record-turn.ts
|
|
2
|
+
//
|
|
3
|
+
// record_turn —— 唯一的写工具。
|
|
4
|
+
//
|
|
5
|
+
// 设计要点(来自 experiments/mcp-probe 的实测结论):
|
|
6
|
+
//
|
|
7
|
+
// 1. 宿主只判断「这轮值不值得记」,**条件式调用**。
|
|
8
|
+
// 实测证明「每轮都调一个工具」对 LLM 不可靠 —— 模型漏调时意识不到自己漏了。
|
|
9
|
+
//
|
|
10
|
+
// 2. 「记成什么」由 server 决定:缓冲攒够 → server 调自己的 LLM 做抽取,
|
|
11
|
+
// 用的是 RememberMe 原版的 extractMemoryCandidates()(prompt、JSON 解析、
|
|
12
|
+
// ≥2 证据校验全部零改动)。
|
|
13
|
+
// —— 这也是 MCP 官方 SEP-2577 废弃 sampling 后推荐的迁移方向。
|
|
14
|
+
//
|
|
15
|
+
// 3. 画像更新复用现有的 maybeUpdateProfile()(和 Web/CLI 完全同一条路径),
|
|
16
|
+
// 所以宿主不需要额外学一套「怎么写画像段」的规则。
|
|
17
|
+
//
|
|
18
|
+
// 4. 没写出时**保留缓冲** —— 一次出现可能是某个模式的第 1 次,
|
|
19
|
+
// 清掉就永远等不到第 2 次了。
|
|
20
|
+
|
|
21
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
import {
|
|
24
|
+
extractMemoryCandidates,
|
|
25
|
+
saveMemoryCandidate,
|
|
26
|
+
type AnyMemoryCandidate,
|
|
27
|
+
} from "../../memory-extract.ts";
|
|
28
|
+
import { maybeUpdateProfile } from "../../profile.ts";
|
|
29
|
+
import { scanMemory } from "../../memory.ts";
|
|
30
|
+
import { paths } from "../config.ts";
|
|
31
|
+
import { getProvider, providerStatus } from "../provider.ts";
|
|
32
|
+
import { log } from "../logger.ts";
|
|
33
|
+
|
|
34
|
+
/** 缓冲里攒够几条"值得记"的记录就抽取(够 2 条证据才能归纳成模式) */
|
|
35
|
+
const EXTRACT_BUFFER_THRESHOLD = 2;
|
|
36
|
+
/** 缓冲上限(没写出时保留,防止无限增长) */
|
|
37
|
+
const MAX_BUFFER = 10;
|
|
38
|
+
|
|
39
|
+
type PendingTurn = {
|
|
40
|
+
userMessage: string;
|
|
41
|
+
assistantReply?: string;
|
|
42
|
+
emotion?: string;
|
|
43
|
+
intensity?: number;
|
|
44
|
+
trigger?: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export function registerRecordTurnTool(server: McpServer): void {
|
|
48
|
+
const pending: PendingTurn[] = [];
|
|
49
|
+
|
|
50
|
+
server.registerTool(
|
|
51
|
+
"record_turn",
|
|
52
|
+
{
|
|
53
|
+
title: "记录这一轮值得记住的内容",
|
|
54
|
+
description:
|
|
55
|
+
"当这一轮有值得长期记住的内容时调用:用户明确要求记住、出现重大生活事件、" +
|
|
56
|
+
"或又一次出现同类情绪反应。" +
|
|
57
|
+
"你只负责判断「值不值得记」并如实转达;具体记成什么、归纳成什么模式," +
|
|
58
|
+
"由记忆系统按它自己的规则决定,你不需要自己写记忆内容。",
|
|
59
|
+
inputSchema: {
|
|
60
|
+
user_message: z.string().describe("用户这轮说的话(原文)"),
|
|
61
|
+
assistant_reply: z
|
|
62
|
+
.string()
|
|
63
|
+
.optional()
|
|
64
|
+
.describe("你这轮的回复(如果有)"),
|
|
65
|
+
emotion: z
|
|
66
|
+
.string()
|
|
67
|
+
.optional()
|
|
68
|
+
.describe("你这轮判断出的用户情绪类别(可选)"),
|
|
69
|
+
intensity: z
|
|
70
|
+
.number()
|
|
71
|
+
.min(0)
|
|
72
|
+
.max(1)
|
|
73
|
+
.optional()
|
|
74
|
+
.describe("情绪强度 0-1(可选)"),
|
|
75
|
+
trigger: z.string().optional().describe("情绪触发原因(可选)"),
|
|
76
|
+
definite: z
|
|
77
|
+
.boolean()
|
|
78
|
+
.optional()
|
|
79
|
+
.describe(
|
|
80
|
+
"true = 用户明确要求记住,或发生了明确的重大事件(立即抽取并落盘);" +
|
|
81
|
+
"false 或不填 = 只是又一次出现同类情绪(先攒着,攒够了再归纳成模式)。",
|
|
82
|
+
),
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
async (args) => {
|
|
86
|
+
try {
|
|
87
|
+
pending.push({
|
|
88
|
+
userMessage: args.user_message,
|
|
89
|
+
assistantReply: args.assistant_reply,
|
|
90
|
+
emotion: args.emotion,
|
|
91
|
+
intensity: args.intensity,
|
|
92
|
+
trigger: args.trigger,
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const buffered = pending.length;
|
|
96
|
+
// 抽取时机:
|
|
97
|
+
// definite=true(用户明确要求 / 重大事件)→ 立即抽
|
|
98
|
+
// 攒够 2 次同类出现 → 抽(够 2 条证据才能归纳成模式)
|
|
99
|
+
//
|
|
100
|
+
// 不用「情绪强度 ≥ 0.7」单独触发:缓冲里装的都是宿主已判定为「值得记」的
|
|
101
|
+
// 轮次,只有一条时抽了必然凑不够证据、白白消耗一次 LLM 调用,还会把它冲掉。
|
|
102
|
+
const shouldExtract =
|
|
103
|
+
args.definite === true || buffered >= EXTRACT_BUFFER_THRESHOLD;
|
|
104
|
+
|
|
105
|
+
if (!shouldExtract) {
|
|
106
|
+
// 画像更新:复用现有实现,fire-and-forget(和 Web/CLI 同一条路径)
|
|
107
|
+
void updateProfileInBackground();
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
content: [
|
|
111
|
+
{
|
|
112
|
+
type: "text",
|
|
113
|
+
text: `已记录(缓冲 ${buffered} 条,攒够 ${EXTRACT_BUFFER_THRESHOLD} 条或用户明确要求时抽取)。`,
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
structuredContent: {
|
|
117
|
+
buffered,
|
|
118
|
+
willExtract: false,
|
|
119
|
+
written: [],
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---- server 调自己的 LLM 做抽取 ----
|
|
125
|
+
const provider = getProvider();
|
|
126
|
+
if (!provider) {
|
|
127
|
+
const status = providerStatus();
|
|
128
|
+
return {
|
|
129
|
+
content: [
|
|
130
|
+
{
|
|
131
|
+
type: "text",
|
|
132
|
+
text:
|
|
133
|
+
`无法抽取记忆:没有可用的 LLM 配置。\n${status.error ?? ""}\n` +
|
|
134
|
+
`(缓冲已保留,配置好 key 后下一轮会重试。)`,
|
|
135
|
+
},
|
|
136
|
+
],
|
|
137
|
+
isError: true,
|
|
138
|
+
structuredContent: { buffered, willExtract: true, written: [] },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const existing = await scanMemory(paths.memory);
|
|
143
|
+
const convo: { role: "user" | "assistant"; content: string }[] = [];
|
|
144
|
+
for (const p of pending) {
|
|
145
|
+
convo.push({ role: "user", content: p.userMessage });
|
|
146
|
+
if (p.assistantReply) {
|
|
147
|
+
convo.push({ role: "assistant", content: p.assistantReply });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let candidates: AnyMemoryCandidate[] = [];
|
|
152
|
+
try {
|
|
153
|
+
candidates = await extractMemoryCandidates(provider, convo, existing);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
// LLM 调用失败 → 不丢缓冲,下轮再试
|
|
156
|
+
log.error("抽取失败:", (e as Error).message);
|
|
157
|
+
return {
|
|
158
|
+
content: [
|
|
159
|
+
{
|
|
160
|
+
type: "text",
|
|
161
|
+
text: `抽取失败(${(e as Error).message})。缓冲已保留,下轮再试。`,
|
|
162
|
+
},
|
|
163
|
+
],
|
|
164
|
+
isError: true,
|
|
165
|
+
structuredContent: { buffered, willExtract: true, written: [] },
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const written: { type: string; name: string; action: string }[] = [];
|
|
170
|
+
for (const c of candidates) {
|
|
171
|
+
const r = await saveMemoryCandidate(paths.memory, c);
|
|
172
|
+
written.push({
|
|
173
|
+
type: c.type,
|
|
174
|
+
name:
|
|
175
|
+
r.action === "new" ? c.name : (r.existingFile?.name ?? c.name),
|
|
176
|
+
action: r.action,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (written.length > 0) {
|
|
181
|
+
pending.length = 0;
|
|
182
|
+
} else {
|
|
183
|
+
// 宁缺毋滥 → 没写出。**保留缓冲**:这一条可能是某个模式的第 1 次出现,
|
|
184
|
+
// 清掉就永远等不到第 2 次了。上限兜底,防止无限增长。
|
|
185
|
+
if (pending.length > MAX_BUFFER) {
|
|
186
|
+
pending.splice(0, pending.length - MAX_BUFFER);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
void updateProfileInBackground();
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
content: [
|
|
194
|
+
{
|
|
195
|
+
type: "text",
|
|
196
|
+
text:
|
|
197
|
+
written.length > 0
|
|
198
|
+
? `已抽取并写入 ${written.length} 条记忆:${written
|
|
199
|
+
.map((w) => `${w.type}/${w.name}(${w.action})`)
|
|
200
|
+
.join(", ")}`
|
|
201
|
+
: `已回顾 ${buffered} 条记录,暂不足以归纳成模式(已保留,等下一次出现)。`,
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
structuredContent: { buffered, willExtract: true, written },
|
|
205
|
+
};
|
|
206
|
+
} catch (e) {
|
|
207
|
+
log.error("record_turn 失败:", (e as Error).message);
|
|
208
|
+
return {
|
|
209
|
+
content: [
|
|
210
|
+
{ type: "text", text: `记录失败:${(e as Error).message}` },
|
|
211
|
+
],
|
|
212
|
+
isError: true,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 画像更新 —— 复用现有的 maybeUpdateProfile()。
|
|
220
|
+
*
|
|
221
|
+
* 和 Web/CLI 是同一条代码路径(段1/2/6 由 LLM 抽取,段3/4/5 派生重算)。
|
|
222
|
+
* fire-and-forget:不阻塞宿主这一轮。
|
|
223
|
+
*/
|
|
224
|
+
async function updateProfileInBackground(): Promise<void> {
|
|
225
|
+
const provider = getProvider();
|
|
226
|
+
if (!provider) return;
|
|
227
|
+
const convo = pending
|
|
228
|
+
.slice(-6)
|
|
229
|
+
.map((p) => ({ role: "user" as const, content: p.userMessage }));
|
|
230
|
+
if (convo.length === 0) return;
|
|
231
|
+
try {
|
|
232
|
+
await maybeUpdateProfile(paths.data, provider, convo, {
|
|
233
|
+
memoryDir: paths.memory,
|
|
234
|
+
});
|
|
235
|
+
} catch (e) {
|
|
236
|
+
log.warn("画像更新失败:", (e as Error).message);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|