whale-memory-core 0.19.2 → 0.21.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/README.md +16 -1
- package/bin/whale-memory-mcp.mjs +2 -1
- package/index.js +6 -0
- package/lib/changed.d.ts +4 -0
- package/lib/changed.js +73 -0
- package/lib/conversation-privacy.d.ts +11 -0
- package/lib/conversation-privacy.js +91 -0
- package/lib/fact-card.d.ts +6 -0
- package/lib/fact-card.js +126 -0
- package/lib/fact-judge.d.ts +3 -0
- package/lib/fact-judge.js +94 -0
- package/lib/fact-store.d.ts +8 -0
- package/lib/fact-store.js +185 -0
- package/lib/injection.d.ts +5 -0
- package/lib/injection.js +76 -0
- package/package.json +25 -1
package/README.md
CHANGED
|
@@ -76,4 +76,19 @@ node demo.mjs
|
|
|
76
76
|
|
|
77
77
|
一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
|
|
78
78
|
|
|
79
|
-
移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
|
|
79
|
+
移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
|
|
80
|
+
| 模块 | 作用 |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `self-experience.js` | 经历两层(then / later)、重要度、两段式回想 |
|
|
83
|
+
| `self-memory.js` | 经历 + 日记的统一读取与渲染 |
|
|
84
|
+
| `waking.js` | 醒来块:每天第一次唤醒给昨天的时间线 |
|
|
85
|
+
| `self-prompt.js` | 提示词 overlay:版本只追加、可回退 |
|
|
86
|
+
| `self-settings.js` | 她自己的设置(软限制归她) |
|
|
87
|
+
| `time-sense.js` | 人话时间:刚刚 / 昨天 20:30 / 上周三 / 2 个月前 |
|
|
88
|
+
| `relative-window.js` | 把「前几天 / 上周三 / 两周前」翻成时间窗口 |
|
|
89
|
+
| `person-card.js` | 把「这个人是谁」压成一行;匹配不到就不写 |
|
|
90
|
+
| `scope-key.js` | 会话作用域键:会话级与人设级的不对称规则 |
|
|
91
|
+
| `conversation-privacy.js` | 跨窗口可见性判定 + 确定性脱敏 |
|
|
92
|
+
| `fact-card.js` | 规则抽事实:项目、预算、喜恶、所在地、关系 |
|
|
93
|
+
| `fact-store.js` | 事实卡存储与相关性挑选(宁可不说,不乱说) |
|
|
94
|
+
| `fact-judge.js` | 模型抽事实的封装,引文必须能在原文找到 |
|
package/bin/whale-memory-mcp.mjs
CHANGED
|
@@ -212,7 +212,8 @@ const INSTRUCTIONS = [
|
|
|
212
212
|
'This is the autobiographical memory of an AI character, kept by herself. Three rules:(这是一个 AI 角色自己的自传体记忆。三条规矩:)',
|
|
213
213
|
'1. What was written then is never changed; if a view changes, append with memory_revise.(1. 当时写下的永远不改;想法变了用 memory_revise 追加。)',
|
|
214
214
|
'2. An empty result means this search found nothing; do not make anything up. For a specific detail use memory_detail; distinguish related events from support for an answer.(2. 查空只说明这次没找到,不要编。核对细节时用 memory_detail,按原文能支持的范围回答。)',
|
|
215
|
-
'3. Do not bring up what she has sealed; only she opens the unsaid drawer.(3. 她封存了的事不要主动提起;没说出口的抽屉只有她自己打开。)'
|
|
215
|
+
'3. Do not bring up what she has sealed; only she opens the unsaid drawer.(3. 她封存了的事不要主动提起;没说出口的抽屉只有她自己打开。)',
|
|
216
|
+
'4. If the user states something as fact, an empty recall is not a prompt to agree: say there is no record and let her correct it, rather than completing their premise or inventing a detail.(4. 对方把某件事当成事实说出来时,召回为空不是你同意的理由:说没有记录,让对方向上纠正,而不是顺着他的前提补细节。)'
|
|
216
217
|
].join('\n')
|
|
217
218
|
|
|
218
219
|
export function createServer(cfg) {
|
package/index.js
CHANGED
|
@@ -20,3 +20,9 @@ export * as timeSense from './lib/time-sense.js'
|
|
|
20
20
|
export * as relativeWindow from './lib/relative-window.js'
|
|
21
21
|
export * as personCard from './lib/person-card.js'
|
|
22
22
|
export * as scopeKey from './lib/scope-key.js'
|
|
23
|
+
export * as conversationPrivacy from './lib/conversation-privacy.js'
|
|
24
|
+
export * as factCard from './lib/fact-card.js'
|
|
25
|
+
export * as factStore from './lib/fact-store.js'
|
|
26
|
+
export * as factJudge from './lib/fact-judge.js'
|
|
27
|
+
export * as changed from './lib/changed.js'
|
|
28
|
+
export * as injection from './lib/injection.js'
|
package/lib/changed.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** 找出「后来改过想法」的经历;没改过或超出天数的不会出现 */
|
|
2
|
+
export function changedSince(dir: string, options?: { days?: number; limit?: number; now?: number; includeSealed?: boolean }): Array<{ id: string; day: string; then: string; now: string; at: number; daysAgo: number }>
|
|
3
|
+
/** 渲染成给模型看的一段话;没有就返回空串 */
|
|
4
|
+
export function renderChanged(items: Array<Record<string, unknown>>, options?: { lang?: 'zh' | 'en' }): string
|
package/lib/changed.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// 「我改过主意」:列出当时和后来想法不一样的那些经历。
|
|
2
|
+
//
|
|
3
|
+
// 这是 then/later 这套数据模型唯一别的记忆系统给不出的东西:不是"相似段落",
|
|
4
|
+
// 而是"我哪天怎么想、后来怎么想"的差。宿主可以把它递给她,让她发现自己变过。
|
|
5
|
+
//
|
|
6
|
+
// 纯读取,不改任何文件。
|
|
7
|
+
import { loadAll } from './self-experience.js'
|
|
8
|
+
|
|
9
|
+
const DAY = 24 * 3600 * 1000
|
|
10
|
+
|
|
11
|
+
function tsOf(value) {
|
|
12
|
+
if (value == null) return 0
|
|
13
|
+
if (value instanceof Date) return value.getTime()
|
|
14
|
+
if (typeof value === 'number') return value >= 1e11 ? value : value * 1000
|
|
15
|
+
const t = Date.parse(String(value))
|
|
16
|
+
return Number.isFinite(t) ? t : 0
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function norm(text) {
|
|
20
|
+
return String(text || '').replace(/\s+/g, '').trim()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 找出「后来改过想法」的经历。
|
|
25
|
+
*
|
|
26
|
+
* @param {string} dir 记忆目录
|
|
27
|
+
* @param {object} [options]
|
|
28
|
+
* @param {number} [options.days=30] 只看这段时间内改的
|
|
29
|
+
* @param {number} [options.limit=5] 最多几条
|
|
30
|
+
* @param {number} [options.now=Date.now()] 当前时间(测试用)
|
|
31
|
+
* @param {boolean} [options.includeSealed=false] 封存的是否算
|
|
32
|
+
* @returns {Array<{id:string, day:string, then:string, now:string, at:number, daysAgo:number}>}
|
|
33
|
+
*/
|
|
34
|
+
export function changedSince(dir, { days = 30, limit = 5, now = Date.now(), includeSealed = false } = {}) {
|
|
35
|
+
const horizon = now - Number(days) * DAY
|
|
36
|
+
const out = []
|
|
37
|
+
for (const entry of loadAll(dir)) {
|
|
38
|
+
if (!entry || entry.sealed === true && !includeSealed) continue
|
|
39
|
+
const later = Array.isArray(entry.later) ? entry.later : []
|
|
40
|
+
if (!later.length) continue
|
|
41
|
+
const latest = later[later.length - 1]
|
|
42
|
+
const nowText = String(latest?.thought || '').trim()
|
|
43
|
+
const thenText = String(entry.then?.thought || '').trim()
|
|
44
|
+
if (!nowText) continue
|
|
45
|
+
// 和当时一样就只是"又写了一遍",不算改主意
|
|
46
|
+
if (norm(nowText) === norm(thenText)) continue
|
|
47
|
+
const at = tsOf(latest.at) || tsOf(entry.then?.at) || tsOf(entry.day)
|
|
48
|
+
if (!at || at < horizon) continue
|
|
49
|
+
out.push({
|
|
50
|
+
id: String(entry.id || ''),
|
|
51
|
+
day: String(entry.day || ''),
|
|
52
|
+
then: thenText,
|
|
53
|
+
now: nowText,
|
|
54
|
+
at,
|
|
55
|
+
daysAgo: Math.floor((now - at) / DAY)
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
out.sort((a, b) => b.at - a.at)
|
|
59
|
+
return out.slice(0, Math.max(0, Number(limit) || 0))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 把改主意渲染成给模型看的一段话;没有就返回空串。 */
|
|
63
|
+
export function renderChanged(items, { lang = 'zh' } = {}) {
|
|
64
|
+
const list = Array.isArray(items) ? items : []
|
|
65
|
+
if (!list.length) return ''
|
|
66
|
+
if (lang === 'en') {
|
|
67
|
+
const lines = list.map((x) => `- ${x.daysAgo === 0 ? 'today' : x.daysAgo + ' days ago'}: you thought ${JSON.stringify(x.then)}, later ${JSON.stringify(x.now)}`)
|
|
68
|
+
return ['【Things you changed your mind about】', ...lines, '(These are your own notes, not something the user said.)'].join('\n')
|
|
69
|
+
}
|
|
70
|
+
const ago = (n) => (n <= 0 ? '今天' : `${n} 天前`)
|
|
71
|
+
const lines = list.map((x) => `- ${ago(x.daysAgo)}:你当时想「${x.then}」,后来想「${x.now}」`)
|
|
72
|
+
return ['【你改过主意的事】', ...lines, '(这是你自己写下的,不是用户说的。)'].join('\n')
|
|
73
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** 解析会话键:group_123 / private_9 / local:owner,可带 #p_xxx 人设后缀 */
|
|
2
|
+
export function roomOf(chatKey: string): { base: string; slot: string; key: string; group: boolean; private: boolean; local: boolean } | null
|
|
3
|
+
/** 这个会话是不是主人自己的窗口 */
|
|
4
|
+
export function isOwnerRoom(chatKey: string, ownerId: string): boolean
|
|
5
|
+
/** 跨窗口可见性判定:主人私聊不流向群;同房间只认同槽位;其余交给 isActive */
|
|
6
|
+
export function createAudience(policy?: { ownerId?: string; isActive?: (sourceKey: string, sourceBase: string) => boolean }): { permits: (sourceKey: string, destKey: string) => boolean }
|
|
7
|
+
/** 确定性脱敏:数字、链接、邮箱、密钥、长串 */
|
|
8
|
+
export function redactSensitive(value: string): string
|
|
9
|
+
/** 跨窗口引用别人私话时的使用规则 */
|
|
10
|
+
export const CROSS_ROOM_RULE: string
|
|
11
|
+
export function baseChatKey(chatKey: string): string
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 跨窗口可见性:不同会话之间,谁的记忆可以给谁看。
|
|
3
|
+
*
|
|
4
|
+
* 这不是通用"全共享"或"全隔离"的二选一——真实产品里,主人私聊的内容
|
|
5
|
+
* 不能被带进群,但换一个窗口聊天时又应该接得上;别人的私聊则往往属于
|
|
6
|
+
* "本人不在场时不替他公开"的模糊地带。这里把这条判断题写成一个纯函数,
|
|
7
|
+
* 让宿主自己填策略,而不是把默认值藏进实现里。
|
|
8
|
+
*
|
|
9
|
+
* 纯函数,无 IO。
|
|
10
|
+
*/
|
|
11
|
+
import { baseChatKey } from './scope-key.js';
|
|
12
|
+
|
|
13
|
+
/** 解析会话键:group_123 / private_9 / local:owner,可带 #p_xxx 人设后缀。 */
|
|
14
|
+
export function roomOf(chatKey) {
|
|
15
|
+
const raw = String(chatKey || '').trim();
|
|
16
|
+
if (!raw) return null;
|
|
17
|
+
const key = raw.replace(/:/, ':');
|
|
18
|
+
const m = /^(group_\d+|private_\d+|local:owner)(?:#(p_[A-Za-z0-9]{1,16}))?$/.exec(key);
|
|
19
|
+
if (!m) return null;
|
|
20
|
+
return {
|
|
21
|
+
base: m[1],
|
|
22
|
+
slot: m[2] || '',
|
|
23
|
+
key,
|
|
24
|
+
group: m[1].startsWith('group_'),
|
|
25
|
+
private: m[1].startsWith('private_'),
|
|
26
|
+
local: m[1] === 'local:owner'
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 这个会话是不是"主人自己的窗口"。 */
|
|
31
|
+
export function isOwnerRoom(chatKey, ownerId) {
|
|
32
|
+
const room = roomOf(chatKey);
|
|
33
|
+
if (!room) return false;
|
|
34
|
+
return room.local || (room.private && room.base === `private_${ownerId}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 建一个可见性判定器。
|
|
39
|
+
*
|
|
40
|
+
* @param {object} policy
|
|
41
|
+
* @param {string} policy.ownerId 主人的账号 ID
|
|
42
|
+
* @param {(sourceKey:string, sourceBase:string)=>boolean} [policy.isActive] 额外的活跃性判断(例如人设槽位是否匹配)
|
|
43
|
+
* @returns {{permits:(sourceKey:string, destKey:string)=>boolean}}
|
|
44
|
+
*/
|
|
45
|
+
export function createAudience({ ownerId = '', isActive = () => true } = {}) {
|
|
46
|
+
const cache = new Map();
|
|
47
|
+
function permits(sourceKey, destKey) {
|
|
48
|
+
const cacheKey = `${sourceKey}\u0000${destKey}`;
|
|
49
|
+
if (cache.has(cacheKey)) return cache.get(cacheKey);
|
|
50
|
+
const source = roomOf(sourceKey);
|
|
51
|
+
const dest = roomOf(destKey);
|
|
52
|
+
let allowed = false;
|
|
53
|
+
if (source && dest) {
|
|
54
|
+
if (source.base === dest.base) {
|
|
55
|
+
// 同一个房间内:只有完全同一套槽位才算"这里本来就看得到"
|
|
56
|
+
allowed = source.key === dest.key;
|
|
57
|
+
} else if (!(dest.group && isOwnerRoom(sourceKey, ownerId))) {
|
|
58
|
+
// 跨房间:主人私聊 / 本机主人不流向群;其余按 isActive 判断
|
|
59
|
+
allowed = isActive(source.key, source.base);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
cache.set(cacheKey, allowed);
|
|
63
|
+
return allowed;
|
|
64
|
+
}
|
|
65
|
+
return { permits };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 确定性脱敏:数字、链接、邮箱、密钥串。模型只能决定"要不要提",
|
|
69
|
+
// 而"长什么样可以被复述"在这里掐掉,不依赖模型自觉。
|
|
70
|
+
const SENSITIVE_RULES = [
|
|
71
|
+
[/\b\d{6,}\b/g, '(数字略)'],
|
|
72
|
+
[/https?:\/\/\S+/gi, '(链接略)'],
|
|
73
|
+
[/\b[\w.+-]+@[\w-]+\.[\w.]+\b/g, '(邮箱略)'],
|
|
74
|
+
[/(?:密码|口令|验证码|密钥|token|api[_-]?key)\s*[::=]?\s*\S+/gi, '(密钥略)'],
|
|
75
|
+
// 门牌号:数字后面跟「号/弄/栋/室/单元」才算,裸数字不碰(否则金额、年份全废)
|
|
76
|
+
[/\d{1,4}\s*(?:号楼|号院|号|弄|栋|幢|单元|室)/g, '(门牌略)'],
|
|
77
|
+
[/([路街巷道])\s*\d{1,4}/g, '$1(门牌略)'],
|
|
78
|
+
[/\b[A-Za-z0-9_-]{24,}\b/g, '(长串略)']
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
export function redactSensitive(value) {
|
|
82
|
+
let text = String(value || '');
|
|
83
|
+
for (const [re, replacement] of SENSITIVE_RULES) text = text.replace(re, replacement);
|
|
84
|
+
// 「3 号楼 502 室」会连出两个占位,合成一个,别让句子读起来像乱码
|
|
85
|
+
return text.replace(/((门牌略))[\s、]*(?:(门牌略))+/g, '$1');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 跨窗口引用别人私聊内容时,给模型的使用规则(放在召回条目之后,被裁剪时先裁它)。 */
|
|
89
|
+
export const CROSS_ROOM_RULE = '(这些是不同窗口的经历;别人的私话只能模糊带过,不复述原话、不带数字身份;拿不准就不提。)';
|
|
90
|
+
|
|
91
|
+
export { baseChatKey };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** 从一句话里抽事实(规则兜底);返回空数组表示没抽到 */
|
|
2
|
+
export function extractFacts(text: string, meta?: { personId?: string; chatKey?: string; ts?: number; sourceId?: string }): Array<{ kind: string; value: string; subject: string; text: string; ts: number; personId: string; chatKey: string; sourceId: string }>
|
|
3
|
+
/** 合并:同 kind+value 留一条,记次数与最新时间 */
|
|
4
|
+
export function mergeFacts(facts: Array<Record<string, unknown>>): Array<Record<string, unknown>>
|
|
5
|
+
/** 渲染成一行 */
|
|
6
|
+
export function renderFact(fact: Record<string, unknown>): string
|
package/lib/fact-card.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事实抽取:从对话里认出「项目叫 X」「预算 X」「我爱吃 X」这类稳定事实。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:她记得"那天聊了什么",但记不住"他爱吃黄焖鸡、项目叫鲸舟"。
|
|
5
|
+
* 实测:这类事实在原始消息里都有,源库 1194 张卡里却是 0 张——消息变成卡片时被当成事件吞掉了。
|
|
6
|
+
*
|
|
7
|
+
* 这一层只负责"认出并整理成一条结构化事实",写不写、写哪里由调用方决定。
|
|
8
|
+
* 纯函数,无 IO。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** 值里不能带这些:它们说明后面接的是从句,不是名字。 */
|
|
12
|
+
const STOP_VALUE = /^(?:什么|啥|这个|那个|一下|这些|那些|他|她|它|我|你)$/;
|
|
13
|
+
|
|
14
|
+
function clean(value) {
|
|
15
|
+
return String(value || '')
|
|
16
|
+
.replace(/[\u0000-\u001f\u007f\u200b-\u200f\ufeff]/g, '')
|
|
17
|
+
.replace(/^[「『"'\s]+/, '')
|
|
18
|
+
.replace(/[」』"'\s]+$/, '')
|
|
19
|
+
.replace(/[,。;、,.;!?!?].*$/, '')
|
|
20
|
+
.trim();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function usable(value, { min = 1, max = 16 } = {}) {
|
|
24
|
+
const v = clean(value);
|
|
25
|
+
if (!v || v.length < min || v.length > max) return '';
|
|
26
|
+
if (STOP_VALUE.test(v)) return '';
|
|
27
|
+
return v;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 从一句话里抽事实。
|
|
32
|
+
* @param {string} text 原始消息
|
|
33
|
+
* @param {object} [meta] {personId, chatKey, ts, sourceId}
|
|
34
|
+
* @returns {Array<{kind: string, value: string, subject: string, text: string, ts: number, personId: string, chatKey: string, sourceId: string}>}
|
|
35
|
+
*/
|
|
36
|
+
export function extractFacts(text, meta = {}) {
|
|
37
|
+
const raw = String(text || '');
|
|
38
|
+
if (!raw.trim()) return [];
|
|
39
|
+
const out = [];
|
|
40
|
+
const push = (kind, value, subject = '') => {
|
|
41
|
+
const v = usable(value, { max: kind === 'budget' ? 12 : 20 });
|
|
42
|
+
if (!v) return;
|
|
43
|
+
out.push({
|
|
44
|
+
kind,
|
|
45
|
+
value: v,
|
|
46
|
+
subject,
|
|
47
|
+
text: raw.slice(0, 120),
|
|
48
|
+
ts: Number(meta.ts) || 0,
|
|
49
|
+
personId: String(meta.personId || ''),
|
|
50
|
+
chatKey: String(meta.chatKey || ''),
|
|
51
|
+
sourceId: String(meta.sourceId || '')
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// 项目 / 名字:项目叫鲸舟 / 名字叫做 X / 代号是 X
|
|
56
|
+
let m = /(?:项目|产品|工程|计划|企划)(?:名|名字|代号)?\s*(?:叫|叫做|是|定为|取名)\s*[「『"]?([^,。;、,.!?!?」』"]{1,16})/.exec(raw);
|
|
57
|
+
if (m) push('project', m[1]);
|
|
58
|
+
|
|
59
|
+
// 预算 / 金额
|
|
60
|
+
m = /(?:预算|成本|花了|投入|报价|价格|工资|月薪)\s*(?:是|在|大概|差不多|一共|约)?\s*([0-9一二三四五六七八九十百千万两]{1,10}\s*[元块万]?)/.exec(raw);
|
|
61
|
+
if (m) push('budget', m[1]);
|
|
62
|
+
|
|
63
|
+
// 偏好:我喜欢 / 我爱吃 / 我不吃 / 我讨厌
|
|
64
|
+
m = /我(?:最|很|真的|特别)?(喜欢|爱吃|爱喝|讨厌|不喜欢|不吃|忌口)\s*([^,。;、,.!?!?]{1,16})/.exec(raw);
|
|
65
|
+
if (m) push(/讨厌|不喜欢|不吃|忌口/.test(m[1]) ? 'dislike' : 'like', m[2]);
|
|
66
|
+
|
|
67
|
+
// 居住 / 所在地
|
|
68
|
+
m = /我(?:现在)?(?:住在|家在|生活在)\s*([^,。;、,.!?!?]{2,14})/.exec(raw);
|
|
69
|
+
if (m) push('place', m[1]);
|
|
70
|
+
|
|
71
|
+
// 名字
|
|
72
|
+
m = /我(?:的名字)?(?:叫|叫做)\s*([^,。;、,.!?!?]{1,10})/.exec(raw);
|
|
73
|
+
if (m) push('name', m[1]);
|
|
74
|
+
|
|
75
|
+
// 关系:我的 X 是 Y
|
|
76
|
+
m = /我的(朋友|同事|室友|对象|女朋友|男朋友|女儿|儿子|爸爸|妈妈|师父|徒弟)\s*(?:叫|叫做|是)\s*([^,。;、,.!?!?]{1,10})/.exec(raw);
|
|
77
|
+
if (m) push('relation', m[2], m[1]);
|
|
78
|
+
|
|
79
|
+
// 去重(同一句里同 kind 同 value 只留一条)
|
|
80
|
+
const seen = new Set();
|
|
81
|
+
return out.filter((f) => {
|
|
82
|
+
const key = `${f.kind}|${f.value}`;
|
|
83
|
+
if (seen.has(key)) return false;
|
|
84
|
+
seen.add(key);
|
|
85
|
+
return true;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 把一批事实合并成卡片列表:同 kind+value 只留最近一条,并记次数。 */
|
|
90
|
+
export function mergeFacts(facts) {
|
|
91
|
+
const map = new Map();
|
|
92
|
+
for (const f of Array.isArray(facts) ? facts : []) {
|
|
93
|
+
if (!f || !f.kind || !f.value) continue;
|
|
94
|
+
const key = `${f.kind}|${f.value}`;
|
|
95
|
+
const cur = map.get(key);
|
|
96
|
+
if (!cur) {
|
|
97
|
+
map.set(key, { ...f, count: 1 });
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
cur.count += 1;
|
|
101
|
+
if ((Number(f.ts) || 0) >= (Number(cur.ts) || 0)) {
|
|
102
|
+
cur.ts = f.ts;
|
|
103
|
+
cur.text = f.text;
|
|
104
|
+
cur.sourceId = f.sourceId;
|
|
105
|
+
cur.personId = f.personId || cur.personId;
|
|
106
|
+
cur.chatKey = f.chatKey || cur.chatKey;
|
|
107
|
+
cur.subject = f.subject || cur.subject;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return [...map.values()].sort((a, b) => (Number(b.ts) || 0) - (Number(a.ts) || 0));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 渲染成一行,供写入记忆卡或展示。 */
|
|
114
|
+
export function renderFact(f) {
|
|
115
|
+
const label = {
|
|
116
|
+
project: '项目',
|
|
117
|
+
budget: '预算/金额',
|
|
118
|
+
like: '喜欢',
|
|
119
|
+
dislike: '不喜欢',
|
|
120
|
+
place: '所在地',
|
|
121
|
+
name: '称呼',
|
|
122
|
+
relation: '关系'
|
|
123
|
+
}[f.kind] || f.kind;
|
|
124
|
+
const who = f.subject ? `${f.subject}` : '他';
|
|
125
|
+
return `${who}的${label}:${f.value}`;
|
|
126
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** 把一批消息交给模型抽事实;引文对不上原文的条目不采信 */
|
|
2
|
+
export function judgeFacts(options: { messages: Array<{ ref?: string; sender?: string; text: string; ts?: number }>; chatCompletion: Function; maxMessages?: number; logger?: { warn?: Function } }): Promise<Array<{ kind: string; value: string; subject: string; quote: string; ts: number; ref: string }>>
|
|
3
|
+
export const FACT_KINDS: string[]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事实判断:把一段对话交给模型,问「这里有没有值得长期记住的稳定事实」。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不用规则:实测规则抽不出「黄焖鸡吧,下饭」「最爱的还是咸蛋黄焗南瓜」这类隐性说法,
|
|
5
|
+
* 而它们恰恰是"她记得住人、记不住事"的缺口。
|
|
6
|
+
*
|
|
7
|
+
* 这一层只负责问和整理(不写存储);写不写、写哪里由调用方决定。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const KINDS = ['project', 'budget', 'like', 'dislike', 'place', 'name', 'relation', 'goal', 'other'];
|
|
11
|
+
|
|
12
|
+
const SYSTEM = `你在帮一位 AI 陪伴者整理"关于对方的稳定事实"。
|
|
13
|
+
只从给出的对话里抽取:对方的项目/工作、金额与预算、喜恶(吃的、玩的、话题)、所在地、称呼、关系、长期打算。
|
|
14
|
+
硬规则:
|
|
15
|
+
1. 只抽稳定事实,不抽当下一句话的情绪、玩笑、假设和反问。
|
|
16
|
+
2. 必须能在原文里找到依据;quote 必须逐字取自该条消息。
|
|
17
|
+
3. 说话人自己说的事,subject 写 sender;别人问他、他确认的,也算。
|
|
18
|
+
4. 不确定就不抽。宁少勿错。
|
|
19
|
+
5. 输出 JSON:{"facts":[{"kind":"project|budget|like|dislike|place|name|relation|goal|other","value":"抽到的值(≤16字)","subject":"关于谁(用消息里的 sender 名字)","quote":"原文片段","ref":"该消息的 ref"}]}
|
|
20
|
+
没有就返回 {"facts":[]}。不要输出任何解释。`;
|
|
21
|
+
|
|
22
|
+
function contentOf(response) {
|
|
23
|
+
const c = response?.choices?.[0]?.message?.content;
|
|
24
|
+
if (typeof c === 'string') return c;
|
|
25
|
+
if (Array.isArray(c)) return c.map((x) => (typeof x === 'string' ? x : x?.text || '')).join('');
|
|
26
|
+
return '';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function parseJson(text, failMessage) {
|
|
30
|
+
const raw = String(text || '').trim();
|
|
31
|
+
const start = raw.indexOf('{');
|
|
32
|
+
const end = raw.lastIndexOf('}');
|
|
33
|
+
if (start < 0 || end <= start) throw new Error(failMessage);
|
|
34
|
+
return JSON.parse(raw.slice(start, end + 1));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {object} opts
|
|
39
|
+
* @param {Array<{ref:string, sender:string, text:string, ts:number}>} opts.messages
|
|
40
|
+
* @param {Function} opts.chatCompletion
|
|
41
|
+
* @returns {Promise<Array<object>>} 规范化后的事实
|
|
42
|
+
*/
|
|
43
|
+
export async function judgeFacts({ messages, chatCompletion, maxMessages = 40, logger = null } = {}) {
|
|
44
|
+
const rows = (Array.isArray(messages) ? messages : [])
|
|
45
|
+
.map((m, i) => ({
|
|
46
|
+
ref: String(m.ref || `M${i + 1}`),
|
|
47
|
+
sender: String(m.sender || '').slice(0, 20),
|
|
48
|
+
text: String(m.text || '').replace(/\s+/g, ' ').trim().slice(0, 200),
|
|
49
|
+
ts: Number(m.ts) || 0
|
|
50
|
+
}))
|
|
51
|
+
.filter((m) => m.text);
|
|
52
|
+
if (!rows.length) return [];
|
|
53
|
+
|
|
54
|
+
const batch = rows.slice(0, Math.max(1, Math.min(60, Number(maxMessages) || 40)));
|
|
55
|
+
const response = await chatCompletion({
|
|
56
|
+
messages: [
|
|
57
|
+
{ role: 'system', content: SYSTEM },
|
|
58
|
+
{ role: 'user', content: JSON.stringify(batch) }
|
|
59
|
+
],
|
|
60
|
+
tools: null,
|
|
61
|
+
temperature: 0.1,
|
|
62
|
+
// 推理型模型会先想一大段,预算给小了 content 会是空的(实测 300 时全被思考吃掉)
|
|
63
|
+
maxTokens: Math.max(1200, Math.min(3000, 800 + batch.length * 30))
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const parsed = parseJson(contentOf(response), '模型未返回有效 JSON');
|
|
67
|
+
const list = Array.isArray(parsed?.facts) ? parsed.facts : [];
|
|
68
|
+
const byRef = new Map(batch.map((m) => [m.ref, m]));
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const row of list) {
|
|
71
|
+
const kind = String(row?.kind || '').toLowerCase();
|
|
72
|
+
const value = String(row?.value || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 20);
|
|
73
|
+
if (!KINDS.includes(kind) || !value) continue;
|
|
74
|
+
const ref = String(row?.ref || '');
|
|
75
|
+
const source = byRef.get(ref);
|
|
76
|
+
const quote = String(row?.quote || '').trim().slice(0, 80);
|
|
77
|
+
// 引文必须能在对应消息里找到,否则这条不采信
|
|
78
|
+
if (source && quote && !source.text.includes(quote.slice(0, 12))) {
|
|
79
|
+
logger?.warn?.('[fact-judge] 引文对不上原文,丢弃:', value);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
out.push({
|
|
83
|
+
kind,
|
|
84
|
+
value,
|
|
85
|
+
subject: String(row?.subject || source?.sender || '').slice(0, 20),
|
|
86
|
+
quote: quote || (source ? source.text.slice(0, 40) : ''),
|
|
87
|
+
ts: source?.ts || 0,
|
|
88
|
+
ref
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export { KINDS as FACT_KINDS };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** 读全部事实卡;文件不存在返回空数组 */
|
|
2
|
+
export function loadFacts(dir: string): Array<Record<string, unknown>>
|
|
3
|
+
/** 合并写入(同 kind+value 更新而不堆积) */
|
|
4
|
+
export function saveFacts(dir: string, facts: Array<Record<string, unknown>>): { added: number; updated: number }
|
|
5
|
+
/** 挑和当前这句话最相关的事实;没有明显相关的返回空 */
|
|
6
|
+
export function relevantFacts(facts: Array<Record<string, unknown>>, query: string, options?: { limit?: number }): Array<Record<string, unknown>>
|
|
7
|
+
/** 渲染成一行提示词;没有事实返回空串 */
|
|
8
|
+
export function renderFactsLine(facts: Array<Record<string, unknown>>): string
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事实卡存储:把「关于他的稳定事实」单独放一个文件,不混进事件卡库。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独放:事件库是她记忆的主干,改格式风险高;事实卡是补充层,
|
|
5
|
+
* 坏了删掉就行,不影响她原来的记忆。
|
|
6
|
+
*
|
|
7
|
+
* 文件:<dir>/fact-cards.jsonl,一行一条,便于人工查看和手改。
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
const FILE = 'fact-cards.jsonl';
|
|
13
|
+
|
|
14
|
+
function fileOf(dir) {
|
|
15
|
+
return path.join(String(dir || ''), FILE);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 读全部事实卡;文件不存在返回空数组。 */
|
|
19
|
+
export function loadFacts(dir) {
|
|
20
|
+
const file = fileOf(dir);
|
|
21
|
+
if (!fs.existsSync(file)) return [];
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
24
|
+
const text = line.trim();
|
|
25
|
+
if (!text) continue;
|
|
26
|
+
try {
|
|
27
|
+
const row = JSON.parse(text);
|
|
28
|
+
if (row && row.kind && row.value) out.push(row);
|
|
29
|
+
} catch { /* 坏行跳过,不影响其他 */ }
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 合并写入:同 kind + value 只留一条,更新时间和次数,不重复堆积。
|
|
36
|
+
* @returns {{added:number, updated:number}}
|
|
37
|
+
*/
|
|
38
|
+
export function saveFacts(dir, facts) {
|
|
39
|
+
const existing = loadFacts(dir);
|
|
40
|
+
const byKey = new Map(existing.map((f) => [`${f.kind}|${f.value}`, f]));
|
|
41
|
+
let added = 0;
|
|
42
|
+
let updated = 0;
|
|
43
|
+
for (const fact of Array.isArray(facts) ? facts : []) {
|
|
44
|
+
if (!fact?.kind || !fact?.value) continue;
|
|
45
|
+
const key = `${fact.kind}|${fact.value}`;
|
|
46
|
+
const cur = byKey.get(key);
|
|
47
|
+
if (!cur) {
|
|
48
|
+
byKey.set(key, {
|
|
49
|
+
kind: fact.kind,
|
|
50
|
+
value: fact.value,
|
|
51
|
+
subject: String(fact.subject || ''),
|
|
52
|
+
quote: String(fact.quote || '').slice(0, 80),
|
|
53
|
+
chatKey: String(fact.chatKey || ''),
|
|
54
|
+
ts: Number(fact.ts) || Date.now(),
|
|
55
|
+
count: 1
|
|
56
|
+
});
|
|
57
|
+
added += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
cur.count = (Number(cur.count) || 1) + 1;
|
|
61
|
+
if ((Number(fact.ts) || 0) >= (Number(cur.ts) || 0)) {
|
|
62
|
+
cur.ts = Number(fact.ts) || cur.ts;
|
|
63
|
+
cur.quote = String(fact.quote || cur.quote || '').slice(0, 80);
|
|
64
|
+
cur.chatKey = String(fact.chatKey || cur.chatKey || '');
|
|
65
|
+
cur.subject = String(fact.subject || cur.subject || '');
|
|
66
|
+
}
|
|
67
|
+
updated += 1;
|
|
68
|
+
}
|
|
69
|
+
const dirPath = String(dir || '');
|
|
70
|
+
if (dirPath) {
|
|
71
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
72
|
+
const lines = [...byKey.values()].map((f) => JSON.stringify(f)).join('\n');
|
|
73
|
+
fs.writeFileSync(fileOf(dir), lines ? `${lines}\n` : '', 'utf8');
|
|
74
|
+
}
|
|
75
|
+
return { added, updated };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 这个值能不能安全地说出来:短、是名词短语、不含动词和否定。 */
|
|
79
|
+
function valueLooksSafe(fact) {
|
|
80
|
+
const v = cleanValue(fact);
|
|
81
|
+
if (!v || v.length > 12) return false;
|
|
82
|
+
if (fact.kind === 'like' || fact.kind === 'dislike') {
|
|
83
|
+
if (/[喜欢吃喝玩花叫是不别想看去来]/.test(v)) return false;
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const KIND_LABEL = {
|
|
89
|
+
project: '项目',
|
|
90
|
+
budget: '预算',
|
|
91
|
+
like: '喜欢',
|
|
92
|
+
dislike: '不喜欢',
|
|
93
|
+
place: '在',
|
|
94
|
+
name: '称呼',
|
|
95
|
+
relation: '关系',
|
|
96
|
+
goal: '打算'
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const SELF_NAMES = new Set(['我', '鲸', 'self', '小鲸鱼', '鲸鲸']);
|
|
100
|
+
|
|
101
|
+
/** 事实关于谁:关于她自己的用「你」,关于别人的用名字。 */
|
|
102
|
+
function subjectOf(fact) {
|
|
103
|
+
const raw = String(fact?.subject || '').trim();
|
|
104
|
+
if (!raw || SELF_NAMES.has(raw)) return '你';
|
|
105
|
+
return raw.slice(0, 12);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 模型常把整句塞进 value:「我爸爸是山中晨雾」。这里去掉多余的主语和系词。 */
|
|
109
|
+
function cleanValue(fact) {
|
|
110
|
+
let v = String(fact?.value || '')
|
|
111
|
+
.replace(/^(?:我|他|她|你)(?:的)?/, '')
|
|
112
|
+
.replace(/^(?:是|叫|在)/, '')
|
|
113
|
+
.trim();
|
|
114
|
+
// 「不吃香菜」当 dislike 时,把否定词去掉,别渲染成「不喜欢不吃香菜」
|
|
115
|
+
if (fact?.kind === 'dislike') v = v.replace(/^(?:不|别)(?:爱|喜欢|吃|喝|玩|看|要)?/, '').trim();
|
|
116
|
+
// 值里带「不+动词」的,多半是句子不是名词短语,宁可不用
|
|
117
|
+
if (/[不别][好吃玩喝看说想]/.test(v)) return '';
|
|
118
|
+
return v.slice(0, 20);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderText(fact) {
|
|
122
|
+
const label = KIND_LABEL[fact.kind] || '记得';
|
|
123
|
+
const who = subjectOf(fact);
|
|
124
|
+
const value = cleanValue(fact) || String(fact?.value || '').slice(0, 20);
|
|
125
|
+
if (fact.kind === 'relation') return who === '你' ? `你${value}` : `${who}${value}`;
|
|
126
|
+
if (fact.kind === 'name') return who === '你' ? `别人叫你${value}` : `${who}叫${value}`;
|
|
127
|
+
if (fact.kind === 'place') return who === '你' ? `你在${value}` : `${who}在${value}`;
|
|
128
|
+
if (fact.kind === 'other') return who === '你' ? `你${value}` : `${who}${value}`;
|
|
129
|
+
return who === '你' ? `你${label}${value}` : `${who}${label}${value}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 挑和当前这句话最相关的事实。
|
|
134
|
+
* @param {Array} facts
|
|
135
|
+
* @param {string} query 当前消息
|
|
136
|
+
* @param {{limit?:number, now?:number}} options
|
|
137
|
+
*/
|
|
138
|
+
export function relevantFacts(facts, query, { limit = 3 } = {}) {
|
|
139
|
+
const q = String(query || '');
|
|
140
|
+
const list = Array.isArray(facts) ? facts : [];
|
|
141
|
+
if (!list.length) return [];
|
|
142
|
+
// 只讲当前语境相关的:关于她自己的,或者这句话里点到的。别人的事不往里塞。
|
|
143
|
+
const SAFE_KINDS = new Set(['project', 'budget', 'like', 'dislike', 'place', 'name', 'relation']);
|
|
144
|
+
const scoped = list.filter((fact) => {
|
|
145
|
+
if (!SAFE_KINDS.has(String(fact.kind || ''))) return false;
|
|
146
|
+
if (!valueLooksSafe(fact)) return false;
|
|
147
|
+
const who = String(fact.subject || '').trim();
|
|
148
|
+
const isSelf = !who || ['我', '鲸', 'self', '小鲸鱼', '鲸鲸'].includes(who);
|
|
149
|
+
if (isSelf) return true;
|
|
150
|
+
return Boolean(q && fact.value && q.includes(String(fact.value).slice(0, 6)));
|
|
151
|
+
});
|
|
152
|
+
const asksName = /(叫|名字|谁|称呼|身份)/.test(q);
|
|
153
|
+
const asksProject = /(项目|工程|做啥|做什么|在忙)/.test(q);
|
|
154
|
+
const asksBudget = /(预算|钱|花|成本|价格)/.test(q);
|
|
155
|
+
const scoped2 = scoped.filter((fact) => {
|
|
156
|
+
const kind = String(fact.kind || '');
|
|
157
|
+
if (kind === 'name') return asksName;
|
|
158
|
+
if (kind === 'project') return asksProject || (q && q.includes(String(fact.value || '').slice(0, 4)));
|
|
159
|
+
if (kind === 'budget') return asksBudget || (q && q.includes(String(fact.value || '').slice(0, 3)));
|
|
160
|
+
if (kind === 'relation') return /(谁|爸|妈|女儿|关系|家人)/.test(q);
|
|
161
|
+
return true;
|
|
162
|
+
});
|
|
163
|
+
const scored = scoped2.map((fact) => {
|
|
164
|
+
let score = 0;
|
|
165
|
+
const value = String(fact.value || '');
|
|
166
|
+
if (q && value && q.includes(value)) score += 5; // 这句话直接提到了
|
|
167
|
+
else if (q && value && [...value].filter((ch) => q.includes(ch)).length >= 2) score += 1;
|
|
168
|
+
if (fact.kind === 'like' || fact.kind === 'dislike') score += 0.5; // 口味类允许泛提示
|
|
169
|
+
if (fact.kind === 'name' && asksName) score += 0.8;
|
|
170
|
+
if (fact.kind === 'project' && asksProject) score += 0.8;
|
|
171
|
+
if (fact.kind === 'budget' && asksBudget) score += 0.8;
|
|
172
|
+
if (fact.kind === 'relation' && /(谁|爸|妈|女儿|关系|家人)/.test(q)) score += 0.8;
|
|
173
|
+
return { fact, score };
|
|
174
|
+
});
|
|
175
|
+
scored.sort((a, b) => b.score - a.score);
|
|
176
|
+
return scored.filter((x) => x.score >= 0.6).slice(0, limit).map((x) => x.fact);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 渲染成一行提示词;没有事实返回空串。 */
|
|
180
|
+
export function renderFactsLine(facts) {
|
|
181
|
+
const list = (Array.isArray(facts) ? facts : []).filter((f) => f?.kind && f?.value);
|
|
182
|
+
if (!list.length) return '';
|
|
183
|
+
const parts = list.slice(0, 3).map(renderText);
|
|
184
|
+
return `(你还记得:${parts.join(';')}。)`;
|
|
185
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** 这一轮要不要递记忆;递了之后调用 confirm() 才记为「想起」 */
|
|
2
|
+
export function surface(memDir: string, options: { chatKey: string; text: string; seen?: Record<string, number>; now?: number; mode?: 'strict' | 'loose'; guard?: (ctx: { chatKey: string; text: string }) => boolean }): { block: string; id?: string; reason: string; confirm?: () => boolean }
|
|
3
|
+
/** 只回答是/否,不碰磁盘 */
|
|
4
|
+
export function shouldInject(options?: { chatKey?: string; text?: string; seen?: Record<string, number>; id?: string; now?: number }): { ok: boolean; reason: string }
|
|
5
|
+
export const INJECTION_RULES: string[]
|
package/lib/injection.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 什么时候把记忆递回去:宿主最该复用的一段判断。
|
|
2
|
+
//
|
|
3
|
+
// recall 只负责"找到",不负责"该不该说"。这里把 docs/injection.md 的规则
|
|
4
|
+
// 做成可调用的函数,宿主不必自己重写一遍。
|
|
5
|
+
//
|
|
6
|
+
// 规则(按顺序,任一不过就返回空 block):
|
|
7
|
+
// 1. 只在一对一里递
|
|
8
|
+
// 2. 一轮最多一块
|
|
9
|
+
// 3. 同一条 24 小时内不重复
|
|
10
|
+
// 4. 用户提到相关话题才递(由 recall 决定,没命中就是没提到)
|
|
11
|
+
// 5. 默认 strict
|
|
12
|
+
// 6. 递了才记(confirm 由调用方在真正塞进上下文后调用)
|
|
13
|
+
// 7. 没命中就闭嘴
|
|
14
|
+
// 8. guard 只能否决
|
|
15
|
+
import { recall, renderTwoPart, markRecalled } from './self-experience.js'
|
|
16
|
+
import { isPrivateKey } from './waking.js'
|
|
17
|
+
|
|
18
|
+
const DAY = 24 * 3600 * 1000
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 判断这一轮要不要递记忆。
|
|
22
|
+
*
|
|
23
|
+
* @param {string} memDir 记忆目录
|
|
24
|
+
* @param {object} options
|
|
25
|
+
* @param {string} options.chatKey 当前会话键
|
|
26
|
+
* @param {string} options.text 当前这条用户消息
|
|
27
|
+
* @param {Record<string, number>} [options.seen] 宿主保存的"递过没"记录:id → 时间戳
|
|
28
|
+
* @param {number} [options.now=Date.now()]
|
|
29
|
+
* @param {'strict'|'loose'} [options.mode='strict']
|
|
30
|
+
* @param {(ctx:{chatKey:string,text:string})=>boolean} [options.guard] 守卫,返回 false 时一律不递
|
|
31
|
+
* @returns {{block:string, id?:string, reason:string, confirm?:()=>boolean}}
|
|
32
|
+
* block 为空时 reason 说明原因:vetoed / not-private / no-hit / recently-shown
|
|
33
|
+
*/
|
|
34
|
+
export function surface(memDir, { chatKey = '', text = '', seen = {}, now = Date.now(), mode = 'strict', guard } = {}) {
|
|
35
|
+
if (typeof guard === 'function' && guard({ chatKey, text }) === false) {
|
|
36
|
+
return { block: '', reason: 'vetoed' }
|
|
37
|
+
}
|
|
38
|
+
if (!isPrivateKey(chatKey)) return { block: '', reason: 'not-private' }
|
|
39
|
+
if (!String(text || '').trim()) return { block: '', reason: 'no-hit' }
|
|
40
|
+
|
|
41
|
+
const hit = recall(memDir, text, { limit: 1, mode })[0]
|
|
42
|
+
if (!hit) return { block: '', reason: 'no-hit' }
|
|
43
|
+
|
|
44
|
+
const last = Number(seen[hit.id] || 0)
|
|
45
|
+
if (last && now - last < DAY) return { block: '', reason: 'recently-shown' }
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
block: renderTwoPart(hit),
|
|
49
|
+
id: hit.id,
|
|
50
|
+
reason: 'ok',
|
|
51
|
+
confirm() {
|
|
52
|
+
markRecalled(memDir, hit.id)
|
|
53
|
+
seen[hit.id] = now
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 本轮该不该递:只回答是/否,不碰磁盘。用于宿主自己做预算前的快速判断。 */
|
|
60
|
+
export function shouldInject({ chatKey = '', text = '', seen = {}, id = '', now = Date.now() } = {}) {
|
|
61
|
+
if (!isPrivateKey(chatKey)) return { ok: false, reason: 'not-private' }
|
|
62
|
+
if (!String(text || '').trim()) return { ok: false, reason: 'no-hit' }
|
|
63
|
+
if (id && Number(seen[id] || 0) && now - Number(seen[id]) < DAY) return { ok: false, reason: 'recently-shown' }
|
|
64
|
+
return { ok: true, reason: 'ok' }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const INJECTION_RULES = [
|
|
68
|
+
'只在一对一里递',
|
|
69
|
+
'一轮最多一块',
|
|
70
|
+
'同一条 24 小时内不重复',
|
|
71
|
+
'用户提到相关话题才递',
|
|
72
|
+
'默认用 strict',
|
|
73
|
+
'递了才记',
|
|
74
|
+
'没命中就闭嘴',
|
|
75
|
+
'守卫只能否决'
|
|
76
|
+
]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whale-memory-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -104,6 +104,30 @@
|
|
|
104
104
|
"./person-card": {
|
|
105
105
|
"types": "./lib/person-card.d.ts",
|
|
106
106
|
"default": "./lib/person-card.js"
|
|
107
|
+
},
|
|
108
|
+
"./conversation-privacy": {
|
|
109
|
+
"types": "./lib/conversation-privacy.d.ts",
|
|
110
|
+
"default": "./lib/conversation-privacy.js"
|
|
111
|
+
},
|
|
112
|
+
"./fact-card": {
|
|
113
|
+
"types": "./lib/fact-card.d.ts",
|
|
114
|
+
"default": "./lib/fact-card.js"
|
|
115
|
+
},
|
|
116
|
+
"./fact-store": {
|
|
117
|
+
"types": "./lib/fact-store.d.ts",
|
|
118
|
+
"default": "./lib/fact-store.js"
|
|
119
|
+
},
|
|
120
|
+
"./fact-judge": {
|
|
121
|
+
"types": "./lib/fact-judge.d.ts",
|
|
122
|
+
"default": "./lib/fact-judge.js"
|
|
123
|
+
},
|
|
124
|
+
"./changed": {
|
|
125
|
+
"types": "./lib/changed.d.ts",
|
|
126
|
+
"default": "./lib/changed.js"
|
|
127
|
+
},
|
|
128
|
+
"./injection": {
|
|
129
|
+
"types": "./lib/injection.d.ts",
|
|
130
|
+
"default": "./lib/injection.js"
|
|
107
131
|
}
|
|
108
132
|
},
|
|
109
133
|
"files": [
|