@dsh-mobile/mobile-remote 3.2.7 → 3.3.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/FAQ.md +19 -12
- package/README.md +38 -39
- package/cordis.patch.yml +8 -4
- package/docs/PRIVACY-POLICY.en.md +87 -46
- package/docs/PRIVACY-POLICY.md +87 -46
- package/docs/SUPPORT.md +5 -5
- package/docs/USER-GUIDE.zh-CN.md +562 -0
- package/lib/assistant-prefs.js +147 -0
- package/lib/auto-config.js +55 -3
- package/lib/backup.js +405 -0
- package/lib/break-reminder.js +133 -0
- package/lib/client.js +56 -10
- package/lib/config.js +94 -5
- package/lib/git-read-bundled-provider.js +12 -3
- package/lib/git-read-service.js +4 -0
- package/lib/host-compat.js +25 -0
- package/lib/http-util.js +6 -2
- package/lib/index.js +949 -70
- package/lib/memory/context.js +76 -0
- package/lib/memory/decay.js +144 -0
- package/lib/memory/extract.js +146 -0
- package/lib/memory/routes.js +198 -0
- package/lib/memory/store.js +667 -0
- package/lib/notify-copy.js +245 -0
- package/lib/permission-guide.js +184 -0
- package/lib/persona-cards.js +362 -0
- package/lib/proactive-material.js +162 -0
- package/lib/proactive.js +369 -0
- package/lib/protected-paths.js +130 -0
- package/lib/protocol.js +35 -0
- package/lib/rate-limit.js +1 -1
- package/lib/relay/connector.js +97 -12
- package/lib/relay/devices.js +14 -0
- package/lib/relay/fingerprint.js +55 -0
- package/lib/relay/identity.js +69 -0
- package/lib/relay/on-demand.js +84 -0
- package/lib/relay/phone.js +87 -12
- package/lib/reminders.js +140 -0
- package/lib/rpc-adapter.js +21 -2
- package/lib/session-rotation.js +198 -0
- package/lib/timeline.js +1 -1
- package/package.json +30 -14
- package/CHANGELOG.md +0 -1383
- package/CONTRIBUTING.md +0 -61
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
- package/docs/01-PRD.md +0 -148
- package/docs/02-architecture.md +0 -249
- package/docs/03-api.md +0 -882
- package/docs/04-security.md +0 -110
- package/docs/05-test-cases.md +0 -376
- package/docs/06-install-run.md +0 -335
- package/docs/07-user-manual.md +0 -92
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
- package/docs/09-compatibility.md +0 -201
- package/docs/11-remote-relay-guide.md +0 -86
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/APP-REVIEW-NOTES.md +0 -105
- package/docs/BRAND-ASSETS.md +0 -142
- package/docs/COMPANION-PLAN.md +0 -199
- package/docs/STORE-LAUNCH.md +0 -341
- package/docs/STORE-LISTING.md +0 -190
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 长期记忆 → agent 的动态上下文(T7 的「能召回」那一半)。
|
|
3
|
+
*
|
|
4
|
+
* 记忆库自己只负责存取,不认识 agent;这里负责把「这个会话现在该看到哪些记忆」
|
|
5
|
+
* 翻译成宿主(`@deepseek-ai/dsh-system-prompt`)的 `context` 贡献。
|
|
6
|
+
*
|
|
7
|
+
* 三条约束,缺一条这个功能就不该存在:
|
|
8
|
+
*
|
|
9
|
+
* 1. **必须按 scope 硬过滤**。过滤发生在库的 SQL 里(`scopesVisibleTo`),
|
|
10
|
+
* 这里不重新判断「这条算不算工作记忆」——那是隐私边界,不能靠调用方自觉。
|
|
11
|
+
* 2. **必须能关**。记忆会把用户原话写进磁盘,默认关闭时这里一次都不该碰库。
|
|
12
|
+
* 3. **失败不能拖垮对话**。库坏了、脱敏后为空、上下文超长 —— 一律降级成
|
|
13
|
+
* 「这一轮没有记忆」,绝不抛给宿主。
|
|
14
|
+
*
|
|
15
|
+
* 为什么用动态 context 而不是 system prompt section:记忆是**每次装配都变**的
|
|
16
|
+
* 事实,塞进 section 会让同一份提示词缓存失效;动态 context 正是为此设计的。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** 记忆上下文的贡献名。同层重名会被宿主拒绝,所以取一个不会撞的。 */
|
|
20
|
+
export const MEMORY_CONTEXT_NAME = "mobile-remote:memory";
|
|
21
|
+
|
|
22
|
+
/** 上下文块的开头。模型要靠这句话知道下面是「记得的事」而不是用户这次说的话。 */
|
|
23
|
+
const HEADER = "关于这位用户的长期记忆(来自你自己之前的记录,可能过时;与当前对话冲突时以当前对话为准):";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 造一个 `ctx.systemPrompt.context(...)` 用的 provider。
|
|
27
|
+
*
|
|
28
|
+
* @param {object} options
|
|
29
|
+
* @param {() => object|null} options.getStore 取记忆库;返回 null 表示功能没开。
|
|
30
|
+
* @param {() => string} options.getMode 当前模式(`work` / `life`)。
|
|
31
|
+
* @param {(context: object) => string} [options.queryFor] 从装配上下文里取检索词。
|
|
32
|
+
* @param {number} [options.maxChars] 整段上下文的上限。
|
|
33
|
+
* @returns {(context: object) => string}
|
|
34
|
+
*/
|
|
35
|
+
export function createMemoryContextProvider({
|
|
36
|
+
getStore,
|
|
37
|
+
getMode,
|
|
38
|
+
queryFor = () => "",
|
|
39
|
+
maxChars = 1500,
|
|
40
|
+
}) {
|
|
41
|
+
return (context) => {
|
|
42
|
+
try {
|
|
43
|
+
const store = getStore();
|
|
44
|
+
if (!store) return "";
|
|
45
|
+
const body = store.contextFor(getMode(), {
|
|
46
|
+
query: queryFor(context) ?? "",
|
|
47
|
+
maxChars,
|
|
48
|
+
});
|
|
49
|
+
if (!body) return "";
|
|
50
|
+
return `${HEADER}\n${body}`;
|
|
51
|
+
} catch {
|
|
52
|
+
// 库坏了 / 磁盘满 / 脱敏后为空:这一轮没有记忆,对话照常。
|
|
53
|
+
return "";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 把 provider 挂到宿主的 `systemPrompt` 服务上。
|
|
60
|
+
*
|
|
61
|
+
* 宿主没有这个服务(老内核、或测试里的假 ctx)时**什么都不做**:
|
|
62
|
+
* 记忆功能降级成「只能存、读不到」,而不是让整个插件加载失败。
|
|
63
|
+
*
|
|
64
|
+
* @returns {boolean} 是否挂上了
|
|
65
|
+
*/
|
|
66
|
+
export function installMemoryContext(ctx, provider) {
|
|
67
|
+
const systemPrompt = ctx.get?.("systemPrompt");
|
|
68
|
+
if (!systemPrompt || typeof systemPrompt.context !== "function") return false;
|
|
69
|
+
systemPrompt.context({
|
|
70
|
+
name: MEMORY_CONTEXT_NAME,
|
|
71
|
+
// 放在常规运行时上下文之后、工具指引之前:它是背景,不该压过仓库与系统信息。
|
|
72
|
+
order: 60,
|
|
73
|
+
text: provider,
|
|
74
|
+
});
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆的「会忘」那一半(P1-12 / P1-13)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要衰减:记忆会越攒越多,全量注入既贵又会淹掉当前任务;而"永不遗忘"
|
|
5
|
+
* 的记忆库在陪伴场景里反而失真——它会把三年前随口一句当成今天的偏好。
|
|
6
|
+
*
|
|
7
|
+
* 分成两张卡,分工必须分清(否则就是两套逻辑互相打架):
|
|
8
|
+
*
|
|
9
|
+
* - **衰减卡**:进提示词。会模糊、会遗忘。由本文件的 `retentionOf()` 算保留度。
|
|
10
|
+
* - **全量卡**:append-only,永不遗忘,**不注入提示词**,只按需检索。
|
|
11
|
+
* 某条被"想起来"一次(检索命中/被重新提到),衰减卡上的 retention 回升——
|
|
12
|
+
* 这就是 surfcore 的「查到即解冻」。
|
|
13
|
+
*
|
|
14
|
+
* 借用 FSRS(间隔重复算法)里 S/D/R 三个量的骨架,只是「受 FSRS 启发」,**不是 FSRS-5 的实现**;也只实现需要的部分,理由写在下面:
|
|
15
|
+
* (memory-brain 实现的才是真正的 FSRS-5:`R = (1 + 19/81·t/S)^-0.5`;我们的曲线见 `retentionOf`。)
|
|
16
|
+
* FSRS 是为「卡片复习调度」设计的(要算下一次复习间隔),而这里只需要回答
|
|
17
|
+
* 「这条记忆现在还该不该被注入」。所以保留 S(稳定度,天)、D(难度,1–10)、
|
|
18
|
+
* R(可提取性,0–1)三个量,丢弃复习调度与评分映射——少一大块没有用处的复杂度。
|
|
19
|
+
*
|
|
20
|
+
* 遗忘曲线用双曲(幂律型)形式 `R = 1/(1 + t/S)`,其中 t 是距上次回忆的天数,S 是衰减常数(见 `retentionOf`,
|
|
21
|
+
* 最初照搬的 `(1 + t/(9·S))^-1` 因为 S 的含义不同被改掉了)。
|
|
22
|
+
* 选它而不是指数衰减,是因为幂律在长尾上更接近人的遗忘(很久前提过的事不会
|
|
23
|
+
* 瞬间归零),这也是 memory-brain 选 FSRS 的原因。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** 稳定度初值(天):一条刚记住、没被复习过的事,默认按「大概能记住一周」算。 */
|
|
27
|
+
export const DEFAULT_STABILITY_DAYS = 7;
|
|
28
|
+
|
|
29
|
+
/** 难度初值:中位难度。写死会在被反复想起时偏低,所以由 recall 提升。 */
|
|
30
|
+
export const DEFAULT_DIFFICULTY = 5;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 低于这个保留度就不再注入提示词(但全量卡仍可检索到)。
|
|
34
|
+
*
|
|
35
|
+
* 0.5 的含义:一条记忆如果"想起来"的概率已经低于一半,把它塞进上下文
|
|
36
|
+
* 就是在用陈旧信息污染当前判断。这个值不调更低,是因为陪伴场景里
|
|
37
|
+
* 「说错话」比「少说一句」贵得多。
|
|
38
|
+
*/
|
|
39
|
+
export const FORGET_THRESHOLD = 0.5;
|
|
40
|
+
|
|
41
|
+
/** 保留度算到 0 之后仍可能被「想起来」——所以不删行,只打冻结标记。 */
|
|
42
|
+
export function isFrozen(retention) {
|
|
43
|
+
return retention < FORGET_THRESHOLD;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 遗忘曲线(FSRS 启发的双曲形式)。t 与 S 都以「天」为单位。
|
|
48
|
+
*
|
|
49
|
+
* 形状取自 FSRS:`R = (1 + t / (9·S))^-1`。但式中的 `S` 在 FSRS 里是**「记忆
|
|
50
|
+
* 稳定到 R 降到 0.9 所需的天数」**,不是"半衰期"。这一点极容易搞错:
|
|
51
|
+
* 若把 S=7 当成"7 天后还记着九成",曲线会慢得离谱(7 天 R=0.9、60 天仍 0.58),
|
|
52
|
+
* 于是衰减形同虚设——测试就是这么抓到的。
|
|
53
|
+
*
|
|
54
|
+
* 这里把"稳定度"定义为**衰减常数**(单位:天),即 R ≈ 0.5 的时间量级,
|
|
55
|
+
* 于是 R = 1/(1 + t/S):S=7 时 7 天约 0.5、30 天约 0.19、60 天约 0.10。
|
|
56
|
+
* 这更贴近陪伴场景要的行为——一周不提就该开始变淡,两个月后不再主动引用。
|
|
57
|
+
*
|
|
58
|
+
* @param {number} daysSinceRecall 距上次被想起/写入的天数
|
|
59
|
+
* @param {number} stability 衰减常数(天,越大忘得越慢)
|
|
60
|
+
* @returns {number} 0–1
|
|
61
|
+
*/
|
|
62
|
+
export function retentionOf(daysSinceRecall, stability) {
|
|
63
|
+
const t = Math.max(0, Number(daysSinceRecall) || 0);
|
|
64
|
+
const s = Math.max(0.1, Number(stability) || DEFAULT_STABILITY_DAYS);
|
|
65
|
+
return Math.max(0, Math.min(1, 1 / (1 + t / s)));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 被想起一次之后的稳定度。FSRS 的核心:难度越低、当下记得越牢,稳定度涨得越多。
|
|
70
|
+
*
|
|
71
|
+
* 这里用的是简化形式而不是完整 FSRS 的 19 参数版本:完整版需要模型输出
|
|
72
|
+
* 每次复习的评分(Again/Hard/Good/Easy),而我们没有评分来源——用户说一句
|
|
73
|
+
* 「对,就是这个」不会带等级。硬套完整公式会引入一堆恒为默认值的参数,
|
|
74
|
+
* 看起来严谨,实际等于自欺。
|
|
75
|
+
*
|
|
76
|
+
* @param {number} stability 当前稳定度(天)
|
|
77
|
+
* @param {number} difficulty 当前难度(1–10)
|
|
78
|
+
* @returns {number} 新的稳定度
|
|
79
|
+
*/
|
|
80
|
+
export function nextStability(stability, difficulty) {
|
|
81
|
+
const s = Math.max(0.1, Number(stability) || DEFAULT_STABILITY_DAYS);
|
|
82
|
+
const d = Math.max(1, Math.min(10, Number(difficulty) || DEFAULT_DIFFICULTY));
|
|
83
|
+
// 难度 1 → ×2.2;难度 10 → ×1.2。越难记住的事,复习带来的增益越小。
|
|
84
|
+
const gain = 2.2 - (d - 1) * (1 / 9) * 1.0;
|
|
85
|
+
return Math.min(3650, s * gain);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 被想起一次之后的难度。反复想起说明它其实不难记。
|
|
90
|
+
*
|
|
91
|
+
* @param {number} difficulty 当前难度(1–10)
|
|
92
|
+
*/
|
|
93
|
+
export function nextDifficulty(difficulty) {
|
|
94
|
+
const d = Math.max(1, Math.min(10, Number(difficulty) || DEFAULT_DIFFICULTY));
|
|
95
|
+
return Math.max(1, d - 0.3);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 一条记忆当前的保留度。
|
|
100
|
+
*
|
|
101
|
+
* `lastRecalledAt` 是上次「被想起」的时刻(写入也算一次想起)。
|
|
102
|
+
* 置顶的记忆不参与衰减——置顶是用户明确的"这条重要,别忘"。
|
|
103
|
+
*
|
|
104
|
+
* @param {object} row 记忆行(camelCase 或 snake_case 都接受)
|
|
105
|
+
* @param {Date} now
|
|
106
|
+
*/
|
|
107
|
+
export function retentionOfRow(row, now = new Date()) {
|
|
108
|
+
if (row?.pinned) return 1;
|
|
109
|
+
const last = Number(row?.lastRecalledAt ?? row?.last_recalled_at ?? row?.createdAt ?? row?.created_at ?? 0);
|
|
110
|
+
if (!Number.isFinite(last) || last <= 0) return 1;
|
|
111
|
+
const days = (now.getTime() - last) / 86_400_000;
|
|
112
|
+
const stability = Number(row?.stability ?? row?.stability_days ?? DEFAULT_STABILITY_DAYS);
|
|
113
|
+
return retentionOf(days, stability);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 把一批记忆分成「该注入的」与「该留在全量卡里的」。
|
|
118
|
+
*
|
|
119
|
+
* 排序:置顶优先,其次保留度高,再次最近更新。冻结的(保留度低于阈值)
|
|
120
|
+
* 不注入,但不丢——它们仍在库里,`search()` 还能查到。
|
|
121
|
+
*
|
|
122
|
+
* @param {object[]} rows
|
|
123
|
+
* @param {object} opts
|
|
124
|
+
* @param {Date} [opts.now]
|
|
125
|
+
* @param {number} [opts.limit] 最多注入多少条
|
|
126
|
+
* @param {number} [opts.threshold] 覆盖默认阈值
|
|
127
|
+
*/
|
|
128
|
+
export function partitionInjectable(rows, { now = new Date(), limit = 20, threshold = FORGET_THRESHOLD } = {}) {
|
|
129
|
+
const scored = rows.map((r) => ({ row: r, retention: retentionOfRow(r, now) }));
|
|
130
|
+
// 边界取「不低于阈值」而不是「大于」:`retention === threshold` 是一条记忆
|
|
131
|
+
// 正好卡在"想起来的机会还有一半"的那一瞬。判成冻结会让它在那一刻被提前
|
|
132
|
+
// 丢掉一次注入机会,而这次注入本来正是把它救回来的手段。
|
|
133
|
+
const isLive = (x) => Boolean(x.row.pinned) || x.retention >= threshold;
|
|
134
|
+
const live = scored.filter(isLive);
|
|
135
|
+
const frozen = scored.filter((x) => !isLive(x));
|
|
136
|
+
live.sort((a, b) => {
|
|
137
|
+
if (Boolean(a.row.pinned) !== Boolean(b.row.pinned)) return a.row.pinned ? -1 : 1;
|
|
138
|
+
if (b.retention !== a.retention) return b.retention - a.retention;
|
|
139
|
+
const au = Number(a.row.updatedAt ?? a.row.updated_at ?? 0);
|
|
140
|
+
const bu = Number(b.row.updatedAt ?? b.row.updated_at ?? 0);
|
|
141
|
+
return bu - au;
|
|
142
|
+
});
|
|
143
|
+
return { injectable: live.slice(0, limit), frozen };
|
|
144
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 从对话里自动挑出「值得长期记住」的用户陈述(T7 的写入侧)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么必须有这一层:`lib/memory/store.js` 只会存,`/api/memory` 只能手工 POST。
|
|
5
|
+
* 少了这一步,「它记得我」只在测试里成立——用户得自己去记忆页手打每一条。
|
|
6
|
+
* 这是 §3.7 已经踩过一次的同一类错:函数对、没人调用。
|
|
7
|
+
*
|
|
8
|
+
* 为什么用规则而不是让模型提取:
|
|
9
|
+
* 1. 每条对话都调一次模型是持续成本,而且记忆功能默认关闭,打开的人不该突然
|
|
10
|
+
* 开始为每轮对话多付一次调用;
|
|
11
|
+
* 2. 规则可单测、可解释、可预测。用户能看懂「为什么这条被记住了」,
|
|
12
|
+
* 这对一个会写进磁盘、跨会话复用的功能是硬要求;
|
|
13
|
+
* 3. 误记的代价高于漏记:记错了要靠用户手动删,漏了下一轮还会被说出来。
|
|
14
|
+
* 所以这里的判据故意保守——只收**用户自己明确陈述**的偏好与事实。
|
|
15
|
+
*
|
|
16
|
+
* 不做的事:不推断、不总结、不从助手的话里取信息、不把工单式指令当记忆
|
|
17
|
+
* ("帮我改一下登录页" 是任务,不是关于这个人的事实)。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** 一条候选记忆。`text` 已去掉触发词,只留事实本身。 */
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {object} MemoryCandidate
|
|
23
|
+
* @property {string} text 去掉触发词后的事实陈述
|
|
24
|
+
* @property {"work"|"life"|"shared"} scope 归属
|
|
25
|
+
* @property {number} confidence 0–1,规则越明确越高
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 触发词表。每条是「用户用自己的话陈述了一件持久事实」的句式。
|
|
30
|
+
*
|
|
31
|
+
* 刻意不收录:
|
|
32
|
+
* - 「我要 / 帮我 / 请」——那是任务指令,不是关于用户的持久事实;
|
|
33
|
+
* - 「现在 / 这次 / 今天」开头的临时状态——除非同时命中下面的偏好词。
|
|
34
|
+
*/
|
|
35
|
+
const PATTERNS = [
|
|
36
|
+
// 明确的偏好陈述
|
|
37
|
+
{ re: /^(?:我)?(?:比较)?(?:喜欢|偏好|更愿意|习惯用|习惯)(.+)$/, scope: "shared", confidence: 0.9 },
|
|
38
|
+
{ re: /^(?:我)?(?:不喜欢|讨厌|受不了|不想用)(.+)$/, scope: "shared", confidence: 0.9 },
|
|
39
|
+
// 明确的自述事实
|
|
40
|
+
{ re: /^(?:我)?(?:是|在做|从事)(.{2,40}?)(?:工程师|开发|设计|产品|学生|老师)?$/, scope: "shared", confidence: 0.6 },
|
|
41
|
+
{ re: /^(?:我)?(?:在|住)(.{2,20}?)(?:工作|生活|上班)$/, scope: "life", confidence: 0.7 },
|
|
42
|
+
// 长期约束 / 边界(这类最该记住:忘了就会反复踩)
|
|
43
|
+
{ re: /^(?:请)?(?:以后|今后|之后)(?:都|一直|一律)?(.+)$/, scope: "shared", confidence: 0.85 },
|
|
44
|
+
{ re: /^(?:我)?(?:不(?:要|想|希望))(?:你)?(.+)$/, scope: "shared", confidence: 0.7 },
|
|
45
|
+
// 工作范围的持久事实
|
|
46
|
+
{ re: /^(?:我们)?(?:项目|团队|公司)(?:用|是|在)(.+)$/, scope: "work", confidence: 0.75 },
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
/** 太短的不算事实("我喜欢" 本身没内容),太长的多半是叙述而不是陈述。 */
|
|
50
|
+
const MIN_TEXT = 3;
|
|
51
|
+
const MAX_TEXT = 120;
|
|
52
|
+
|
|
53
|
+
/** 一条记忆最多这么长——与 store 的单条截断口径一致(300)。 */
|
|
54
|
+
const MAX_STORED = 200;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 这些词一出现就说明是**当次任务**而不是持久事实。
|
|
58
|
+
* 例:「我喜欢这样改」是在说这次改动,不是在说他的偏好。
|
|
59
|
+
*/
|
|
60
|
+
const TRANSIENT = /(?:这样|这次|这个版本|这一版|刚才|现在先|暂时|先这么)/;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 判断一句话值不值得记,返回候选或 null。
|
|
64
|
+
*
|
|
65
|
+
* @param {string} raw 用户原话(单行、已 trim)
|
|
66
|
+
* @returns {MemoryCandidate|null}
|
|
67
|
+
*/
|
|
68
|
+
export function extractMemory(raw) {
|
|
69
|
+
const text = String(raw ?? "").replace(/\s+/g, " ").trim();
|
|
70
|
+
if (text.length < MIN_TEXT) return null;
|
|
71
|
+
// 问句不是陈述:用户在问「我喜欢什么」,我们并不因此知道答案。
|
|
72
|
+
if (/[??]\s*$/.test(text)) return null;
|
|
73
|
+
// 代码 / 命令 / 路径:是操作内容,不是关于人的事实。
|
|
74
|
+
if (/^[\s`$>#/]/.test(text) || /```/.test(text)) return null;
|
|
75
|
+
if (TRANSIENT.test(text)) return null;
|
|
76
|
+
// 一条里塞了好几句的,多半是叙述,不拆也不记——拆错比漏记更糟。
|
|
77
|
+
if (text.split(/[。!!;;]/).filter((s) => s.trim() !== "").length > 1) return null;
|
|
78
|
+
|
|
79
|
+
for (const { re, scope, confidence } of PATTERNS) {
|
|
80
|
+
const m = re.exec(text);
|
|
81
|
+
if (!m) continue;
|
|
82
|
+
// 用整句作记忆正文:去掉主语会丢掉「谁的偏好」这层信息,而捕获组
|
|
83
|
+
// 在不同句式下不稳定("以后都……" 的组里常常只有一个副词)。
|
|
84
|
+
const body = text.slice(0, MAX_STORED);
|
|
85
|
+
if (body.replace(/[^\p{L}\p{N}]/gu, "").length < MIN_TEXT) return null;
|
|
86
|
+
return { text: body, scope, confidence };
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 从一段用户发言里挑出候选(一句话最多一条)。
|
|
93
|
+
*
|
|
94
|
+
* 只处理**用户**说的话:助手的话不是关于用户的证据。
|
|
95
|
+
*
|
|
96
|
+
* @param {{text: string, mode?: "work"|"life"}} input
|
|
97
|
+
* @returns {MemoryCandidate[]}
|
|
98
|
+
*/
|
|
99
|
+
export function extractMemories({ text, mode = "work" }) {
|
|
100
|
+
const lines = String(text ?? "")
|
|
101
|
+
.split(/\r?\n/)
|
|
102
|
+
.map((l) => l.trim())
|
|
103
|
+
.filter((l) => l !== "");
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const line of lines) {
|
|
106
|
+
const hit = extractMemory(line);
|
|
107
|
+
if (!hit) continue;
|
|
108
|
+
// 生活模式下不产生工作记忆:用户在生活模式里说「我们项目用 pnpm」,
|
|
109
|
+
// 那条属于 work,写进去之后生活模式自己也读不到,只会污染库。
|
|
110
|
+
if (mode === "life" && hit.scope === "work") continue;
|
|
111
|
+
// 同一条里重复的句式只留一条。
|
|
112
|
+
if (out.some((o) => o.text === hit.text)) continue;
|
|
113
|
+
out.push(hit);
|
|
114
|
+
}
|
|
115
|
+
// 一次发言最多记 3 条:再多说明这段话不是「陈述事实」而是长文。
|
|
116
|
+
return out.slice(0, 3);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 把候选写进记忆库。写入失败绝不能影响对话——这是本函数的唯一契约。
|
|
121
|
+
*
|
|
122
|
+
* @param {object} e
|
|
123
|
+
* @param {{add: Function}} e.store 记忆库
|
|
124
|
+
* @param {MemoryCandidate[]} e.candidates
|
|
125
|
+
* @param {{sessionId?: string|null, origin?: string|null}} [e.meta] 来源信息
|
|
126
|
+
* @returns {number} 实际写入条数
|
|
127
|
+
*/
|
|
128
|
+
export function recordMemories({ store, candidates, meta = {} }) {
|
|
129
|
+
if (!store || !Array.isArray(candidates) || candidates.length === 0) return 0;
|
|
130
|
+
let written = 0;
|
|
131
|
+
for (const c of candidates) {
|
|
132
|
+
try {
|
|
133
|
+
store.add({
|
|
134
|
+
scope: c.scope,
|
|
135
|
+
text: c.text,
|
|
136
|
+
source: "conversation",
|
|
137
|
+
sessionId: meta.sessionId ?? null,
|
|
138
|
+
origin: meta.origin ?? null,
|
|
139
|
+
});
|
|
140
|
+
written++;
|
|
141
|
+
} catch {
|
|
142
|
+
// 单条失败(脱敏后为空、scope 非法)不影响其余几条,也不影响对话。
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return written;
|
|
146
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆管理接口(T7/T8 的服务端半)。
|
|
3
|
+
*
|
|
4
|
+
* 与 store.js 的分工:那边是库与检索,这边只做 HTTP 形状转换与参数校验。
|
|
5
|
+
* 状态码刻意不用 200 一把梭:App 要能区分「非法 scope」(400)、「找不到」(404)
|
|
6
|
+
* 与「服务端没开记忆」(503),否则界面上只能显示一整段错误文本。
|
|
7
|
+
*
|
|
8
|
+
* 端点:
|
|
9
|
+
* GET /api/memory?mode=work|life&q=... 列出(q 非空则按 BM25 相关性)
|
|
10
|
+
* POST /api/memory 新增 {scope,text,origin?}
|
|
11
|
+
* PATCH /api/memory/:id 编辑 {text?} / 改 scope {scope?}
|
|
12
|
+
* DELETE /api/memory/:id 删除(T-63:硬删除,库、WAL、存档里都不留原文)
|
|
13
|
+
* DELETE /api/memory?all=1 删除全部记忆(记忆关着也能删:直接删文件)
|
|
14
|
+
* GET /api/memory/export 导出全部现存记忆(删掉的不在里面)
|
|
15
|
+
*/
|
|
16
|
+
import { readBody, sendError, sendJson } from "../http-util.js";
|
|
17
|
+
import { normalizeScope } from "./store.js";
|
|
18
|
+
|
|
19
|
+
const MAX_TEXT = 4000;
|
|
20
|
+
|
|
21
|
+
/** 只接受这两个模式值:未知值不猜,按 work 处理会泄漏生活模式的边界假设。 */
|
|
22
|
+
function normalizeMode(value) {
|
|
23
|
+
return value === "life" ? "life" : "work";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function badRequest(res, detail) {
|
|
27
|
+
sendError(res, 400, "bad-request", detail);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} deps
|
|
32
|
+
* @param {() => object | null} deps.store 返回当前记忆库(null = 用户关掉了记忆)
|
|
33
|
+
* @param {() => number} [deps.wipe] 记忆库没打开时删除全部记忆文件(T-63),返回删掉的文件数
|
|
34
|
+
* @param {() => void} [deps.onDeleteAll] 删除全部之后清掉还没写进库的东西(等待提取的本轮原话等)
|
|
35
|
+
*/
|
|
36
|
+
export function createMemoryRoutes({ store, wipe = () => 0, onDeleteAll = () => {} }) {
|
|
37
|
+
/**
|
|
38
|
+
* 取记忆库。三种结果必须分开,否则「库打不开」会被渲染成「你还没有记忆」:
|
|
39
|
+
* { kind: "ok", store } 可用
|
|
40
|
+
* { kind: "off" } 用户关掉了(配置里没有这一项)
|
|
41
|
+
* { kind: "error", error }打不开(磁盘满、权限、库损坏)——要说得出原因
|
|
42
|
+
*/
|
|
43
|
+
const current = () => {
|
|
44
|
+
try {
|
|
45
|
+
const s = store();
|
|
46
|
+
return s ? { kind: "ok", store: s } : { kind: "off" };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return { kind: "error", error };
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
return async function handleMemory(req, res, url, rest, method) {
|
|
53
|
+
const lookup = current();
|
|
54
|
+
// 「删除全部记忆」(T-63):记忆关着或库打不开时也要能删——用户关掉记忆之后
|
|
55
|
+
// 想把留下的数据清掉,正是最该成功的那一次。`all=1` 必须显式给出。
|
|
56
|
+
if (rest === "/memory" && method === "DELETE") {
|
|
57
|
+
if (url.searchParams.get("all") !== "1") {
|
|
58
|
+
badRequest(res, "删除全部记忆需要 ?all=1 / deleting all memory needs ?all=1");
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
// 先清掉等待提取的内容(T-63 fix):否则本轮结束时它又会被写回库里。
|
|
63
|
+
onDeleteAll();
|
|
64
|
+
if (lookup.kind === "ok") {
|
|
65
|
+
sendJson(res, 200, { ok: true, removed: lookup.store.removeAll() });
|
|
66
|
+
} else {
|
|
67
|
+
sendJson(res, 200, { ok: true, removed: 0, filesRemoved: wipe() });
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
sendError(res, 500, "memory-delete-failed", err?.message ?? String(err));
|
|
71
|
+
}
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (lookup.kind !== "ok") {
|
|
75
|
+
// 记忆是可选的:打不开时其它功能照常,这一块明确不可用并带上原因。
|
|
76
|
+
const reason =
|
|
77
|
+
lookup.kind === "off"
|
|
78
|
+
? "记忆未启用"
|
|
79
|
+
: `记忆库打不开:${lookup.error?.message ?? lookup.error}`;
|
|
80
|
+
sendError(res, 503, "memory-unavailable", reason);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const s = lookup.store;
|
|
84
|
+
|
|
85
|
+
// 导出必须在 /:id 之前判断,否则会被当成 id="export"
|
|
86
|
+
if (rest === "/memory/export") {
|
|
87
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
88
|
+
sendError(res, 405, "method-not-allowed");
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
sendJson(res, 200, { items: s.exportAll() });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (rest === "/memory") {
|
|
96
|
+
if (method === "GET" || method === "HEAD") {
|
|
97
|
+
const mode = normalizeMode(url.searchParams.get("mode"));
|
|
98
|
+
const q = (url.searchParams.get("q") ?? "").trim();
|
|
99
|
+
const items = q ? s.search(q, { mode, limit: 50 }) : s.listVisible(mode);
|
|
100
|
+
if (q) s.markRecalled(items.map((m) => m.id));
|
|
101
|
+
sendJson(res, 200, { mode, items, total: s.countVisible(mode) });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (method === "POST") {
|
|
105
|
+
let body;
|
|
106
|
+
try {
|
|
107
|
+
body = JSON.parse(await readBody(req));
|
|
108
|
+
} catch {
|
|
109
|
+
badRequest(res, "请求体不是合法 JSON");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const text = typeof body?.text === "string" ? body.text : "";
|
|
113
|
+
if (text.trim() === "") {
|
|
114
|
+
badRequest(res, "text 不能为空");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (text.length > MAX_TEXT) {
|
|
118
|
+
badRequest(res, `text 超过 ${MAX_TEXT} 字符`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const scope = normalizeScope(body?.scope);
|
|
122
|
+
if (!scope) {
|
|
123
|
+
badRequest(res, "scope 必须是 work / life / shared");
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const source = body?.source === "manual" ? "manual" : "conversation";
|
|
127
|
+
try {
|
|
128
|
+
const item = s.add({
|
|
129
|
+
scope,
|
|
130
|
+
text,
|
|
131
|
+
source,
|
|
132
|
+
sessionId: typeof body?.sessionId === "string" ? body.sessionId : null,
|
|
133
|
+
origin: typeof body?.origin === "string" ? body.origin : null,
|
|
134
|
+
});
|
|
135
|
+
sendJson(res, 200, { item });
|
|
136
|
+
} catch (err) {
|
|
137
|
+
badRequest(res, err?.message ?? "写入失败");
|
|
138
|
+
}
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
sendError(res, 405, "method-not-allowed");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const idMatch = /^\/memory\/(\d+)$/.exec(rest);
|
|
146
|
+
if (!idMatch) {
|
|
147
|
+
sendError(res, 404, "not-found");
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const id = Number(idMatch[1]);
|
|
151
|
+
if (!s.get(id)) {
|
|
152
|
+
sendError(res, 404, "memory-not-found");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (method === "DELETE") {
|
|
157
|
+
s.remove(id);
|
|
158
|
+
sendJson(res, 200, { ok: true });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (method === "PATCH") {
|
|
162
|
+
let body;
|
|
163
|
+
try {
|
|
164
|
+
body = JSON.parse(await readBody(req));
|
|
165
|
+
} catch {
|
|
166
|
+
badRequest(res, "请求体不是合法 JSON");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
if (typeof body?.text === "string") {
|
|
171
|
+
if (body.text.trim() === "") {
|
|
172
|
+
badRequest(res, "text 不能为空");
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (body.text.length > MAX_TEXT) {
|
|
176
|
+
badRequest(res, `text 超过 ${MAX_TEXT} 字符`);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
s.edit(id, body.text);
|
|
180
|
+
}
|
|
181
|
+
if (body?.scope !== undefined) {
|
|
182
|
+
const scope = normalizeScope(body.scope);
|
|
183
|
+
if (!scope) {
|
|
184
|
+
badRequest(res, "scope 必须是 work / life / shared");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
s.setScope(id, scope);
|
|
188
|
+
}
|
|
189
|
+
} catch (err) {
|
|
190
|
+
badRequest(res, err?.message ?? "更新失败");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
sendJson(res, 200, { item: s.get(id) });
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
sendError(res, 405, "method-not-allowed");
|
|
197
|
+
};
|
|
198
|
+
}
|