whale-memory-core 0.20.0 → 0.21.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/README.md +3 -3
- package/bin/whale-memory-mcp.mjs +29 -5
- package/index.d.ts +7 -0
- package/index.js +2 -0
- package/lib/archive.d.ts +19 -0
- package/lib/archive.js +267 -14
- package/lib/book.js +34 -3
- package/lib/changed.d.ts +4 -0
- package/lib/changed.js +76 -0
- package/lib/conversation-privacy.js +43 -15
- package/lib/fact-store.js +56 -15
- package/lib/file-lock.d.ts +4 -1
- package/lib/file-lock.js +151 -13
- package/lib/injection.d.ts +5 -0
- package/lib/injection.js +82 -0
- package/lib/query-match.js +67 -18
- package/lib/scope-key.d.ts +4 -0
- package/lib/scope-key.js +34 -0
- package/lib/seal-events.d.ts +2 -2
- package/lib/seal-events.js +26 -5
- package/lib/self-experience.d.ts +4 -1
- package/lib/self-experience.js +138 -52
- package/lib/self-prompt.js +22 -5
- package/lib/unfinished-events.d.ts +2 -0
- package/lib/waking.js +6 -3
- package/package.json +9 -1
|
@@ -6,43 +6,67 @@
|
|
|
6
6
|
* "本人不在场时不替他公开"的模糊地带。这里把这条判断题写成一个纯函数,
|
|
7
7
|
* 让宿主自己填策略,而不是把默认值藏进实现里。
|
|
8
8
|
*
|
|
9
|
+
* 会话键的解析和"这是不是一对一的私聊"都交给 scope-key.js:
|
|
10
|
+
* 两边必须认同一套写法,否则一个入口放行、另一个入口拒绝。
|
|
11
|
+
*
|
|
9
12
|
* 纯函数,无 IO。
|
|
10
13
|
*/
|
|
11
|
-
import { baseChatKey } from './scope-key.js';
|
|
14
|
+
import { baseChatKey, isGroupScope, isPrivateScope } from './scope-key.js';
|
|
15
|
+
|
|
16
|
+
// 认得出来的房间写法:群 / 私聊都接受 `_` 和 `:` 两种分隔符;
|
|
17
|
+
// 本机主人窗口是 local:owner / local_owner。私聊的另一半是账号 ID,不限定是纯数字。
|
|
18
|
+
const GROUP_BASE = /^group[:_]\d+$/i;
|
|
19
|
+
const PRIVATE_BASE = /^private[:_](.+)$/i;
|
|
20
|
+
const LOCAL_BASE = /^local[:_]owner$/i;
|
|
12
21
|
|
|
13
22
|
/** 解析会话键:group_123 / private_9 / local:owner,可带 #p_xxx 人设后缀。 */
|
|
14
23
|
export function roomOf(chatKey) {
|
|
15
24
|
const raw = String(chatKey || '').trim();
|
|
16
25
|
if (!raw) return null;
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
26
|
+
const base = baseChatKey(raw);
|
|
27
|
+
if (!base) return null;
|
|
28
|
+
const slot = base === raw ? '' : raw.slice(base.length + 1);
|
|
29
|
+
const local = LOCAL_BASE.test(base);
|
|
30
|
+
// 带群标记的(private:group_123、local_group_1……)私聊写法不算私聊房间:
|
|
31
|
+
// 宁可认不出,也不要把"外面套了 private"的群当成一对一。
|
|
32
|
+
const priv = !local && PRIVATE_BASE.test(base) && isPrivateScope(base);
|
|
33
|
+
const group = !local && !priv && GROUP_BASE.test(base) && isGroupScope(base);
|
|
34
|
+
if (!local && !priv && !group) return null;
|
|
20
35
|
return {
|
|
21
|
-
base
|
|
22
|
-
slot
|
|
23
|
-
key,
|
|
24
|
-
group
|
|
25
|
-
private:
|
|
26
|
-
local
|
|
36
|
+
base,
|
|
37
|
+
slot,
|
|
38
|
+
key: raw,
|
|
39
|
+
group,
|
|
40
|
+
private: priv,
|
|
41
|
+
local
|
|
27
42
|
};
|
|
28
43
|
}
|
|
29
44
|
|
|
30
|
-
/** 这个会话是不是"主人自己的窗口"
|
|
45
|
+
/** 这个会话是不是"主人自己的窗口"。缺 ownerId 时谁都不算主人。 */
|
|
31
46
|
export function isOwnerRoom(chatKey, ownerId) {
|
|
32
47
|
const room = roomOf(chatKey);
|
|
33
48
|
if (!room) return false;
|
|
34
|
-
|
|
49
|
+
if (room.local) return true;
|
|
50
|
+
const owner = String(ownerId ?? '').trim();
|
|
51
|
+
if (!owner) return false;
|
|
52
|
+
const m = PRIVATE_BASE.exec(room.base);
|
|
53
|
+
return Boolean(room.private && m && m[1] === owner);
|
|
35
54
|
}
|
|
36
55
|
|
|
37
56
|
/**
|
|
38
57
|
* 建一个可见性判定器。
|
|
39
58
|
*
|
|
59
|
+
* 没有 ownerId 时一律不放行(fail closed):认不出哪间是主人的私聊,
|
|
60
|
+
* 就没法判断"这个人不在场时能不能替他说",宁可什么都不给。
|
|
61
|
+
*
|
|
40
62
|
* @param {object} policy
|
|
41
|
-
* @param {string} policy.ownerId 主人的账号 ID
|
|
63
|
+
* @param {string} policy.ownerId 主人的账号 ID;缺省时判定器拒绝一切
|
|
42
64
|
* @param {(sourceKey:string, sourceBase:string)=>boolean} [policy.isActive] 额外的活跃性判断(例如人设槽位是否匹配)
|
|
43
65
|
* @returns {{permits:(sourceKey:string, destKey:string)=>boolean}}
|
|
44
66
|
*/
|
|
45
67
|
export function createAudience({ ownerId = '', isActive = () => true } = {}) {
|
|
68
|
+
const owner = String(ownerId ?? '').trim();
|
|
69
|
+
if (!owner) return { permits: () => false };
|
|
46
70
|
const cache = new Map();
|
|
47
71
|
function permits(sourceKey, destKey) {
|
|
48
72
|
const cacheKey = `${sourceKey}\u0000${destKey}`;
|
|
@@ -54,7 +78,7 @@ export function createAudience({ ownerId = '', isActive = () => true } = {}) {
|
|
|
54
78
|
if (source.base === dest.base) {
|
|
55
79
|
// 同一个房间内:只有完全同一套槽位才算"这里本来就看得到"
|
|
56
80
|
allowed = source.key === dest.key;
|
|
57
|
-
} else if (!(dest.group && isOwnerRoom(sourceKey,
|
|
81
|
+
} else if (!(dest.group && isOwnerRoom(sourceKey, owner))) {
|
|
58
82
|
// 跨房间:主人私聊 / 本机主人不流向群;其余按 isActive 判断
|
|
59
83
|
allowed = isActive(source.key, source.base);
|
|
60
84
|
}
|
|
@@ -72,13 +96,17 @@ const SENSITIVE_RULES = [
|
|
|
72
96
|
[/https?:\/\/\S+/gi, '(链接略)'],
|
|
73
97
|
[/\b[\w.+-]+@[\w-]+\.[\w.]+\b/g, '(邮箱略)'],
|
|
74
98
|
[/(?:密码|口令|验证码|密钥|token|api[_-]?key)\s*[::=]?\s*\S+/gi, '(密钥略)'],
|
|
99
|
+
// 门牌号:数字后面跟「号/弄/栋/室/单元」才算,裸数字不碰(否则金额、年份全废)
|
|
100
|
+
[/\d{1,4}\s*(?:号楼|号院|号|弄|栋|幢|单元|室)/g, '(门牌略)'],
|
|
101
|
+
[/([路街巷道])\s*\d{1,4}/g, '$1(门牌略)'],
|
|
75
102
|
[/\b[A-Za-z0-9_-]{24,}\b/g, '(长串略)']
|
|
76
103
|
];
|
|
77
104
|
|
|
78
105
|
export function redactSensitive(value) {
|
|
79
106
|
let text = String(value || '');
|
|
80
107
|
for (const [re, replacement] of SENSITIVE_RULES) text = text.replace(re, replacement);
|
|
81
|
-
|
|
108
|
+
// 「3 号楼 502 室」会连出两个占位,合成一个,别让句子读起来像乱码
|
|
109
|
+
return text.replace(/((门牌略))[\s、]*(?:(门牌略))+/g, '$1');
|
|
82
110
|
}
|
|
83
111
|
|
|
84
112
|
/** 跨窗口引用别人私聊内容时,给模型的使用规则(放在召回条目之后,被裁剪时先裁它)。 */
|
package/lib/fact-store.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
|
+
import { withFileLock, writeFileAtomic } from './file-lock.js';
|
|
11
12
|
|
|
12
13
|
const FILE = 'fact-cards.jsonl';
|
|
13
14
|
|
|
@@ -15,6 +16,23 @@ function fileOf(dir) {
|
|
|
15
16
|
return path.join(String(dir || ''), FILE);
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
// 上次写到一半崩掉留下的临时文件:拿到锁以后清掉(锁保证没有别的写者在用)。
|
|
20
|
+
function cleanupTemps(file) {
|
|
21
|
+
const dir = path.dirname(file);
|
|
22
|
+
const prefix = path.basename(file) + '.tmp-';
|
|
23
|
+
let names = [];
|
|
24
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
25
|
+
for (const name of names) {
|
|
26
|
+
if (!name.startsWith(prefix)) continue;
|
|
27
|
+
try { fs.rmSync(path.join(dir, name), { force: true }); } catch { /* 下一轮再清 */ }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function serializeFacts(rows) {
|
|
32
|
+
const lines = rows.map((f) => JSON.stringify(f)).join('\n');
|
|
33
|
+
return lines ? `${lines}\n` : '';
|
|
34
|
+
}
|
|
35
|
+
|
|
18
36
|
/** 读全部事实卡;文件不存在返回空数组。 */
|
|
19
37
|
export function loadFacts(dir) {
|
|
20
38
|
const file = fileOf(dir);
|
|
@@ -32,25 +50,49 @@ export function loadFacts(dir) {
|
|
|
32
50
|
}
|
|
33
51
|
|
|
34
52
|
/**
|
|
35
|
-
* 合并写入:同 kind + value 只留一条,更新时间和次数,不重复堆积。
|
|
53
|
+
* 合并写入:同 kind + value + 主体 只留一条,更新时间和次数,不重复堆积。
|
|
54
|
+
* 主体必须进合并键:Alice 喜欢咖啡和 Bob 喜欢咖啡是两条事实,不能合成一个人。
|
|
55
|
+
*
|
|
56
|
+
* 并发安全:整段「重读 → 合并 → 写回」都在 file-lock 里,写回走临时文件 + fsync + rename;
|
|
57
|
+
* 并发写不会互相覆盖,写到一半崩掉也不会把正式文件写成半截。
|
|
36
58
|
* @returns {{added:number, updated:number}}
|
|
37
59
|
*/
|
|
38
60
|
export function saveFacts(dir, facts) {
|
|
39
|
-
const
|
|
40
|
-
const
|
|
61
|
+
const dirPath = String(dir || '');
|
|
62
|
+
const incoming = Array.isArray(facts) ? facts : [];
|
|
63
|
+
if (!dirPath) {
|
|
64
|
+
const merged = mergeFacts([], incoming);
|
|
65
|
+
return { added: merged.added, updated: merged.updated };
|
|
66
|
+
}
|
|
67
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
68
|
+
const file = fileOf(dirPath);
|
|
69
|
+
return withFileLock(file + '.lock', () => {
|
|
70
|
+
const merged = mergeFacts(loadFacts(dirPath), incoming);
|
|
71
|
+
cleanupTemps(file);
|
|
72
|
+
writeFileAtomic(file, serializeFacts(merged.rows));
|
|
73
|
+
return { added: merged.added, updated: merged.updated };
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function mergeFacts(existing, facts) {
|
|
78
|
+
const keyOf = (f) => `${f.kind}|${String(f.subject || '').trim()}|${f.value}`;
|
|
79
|
+
const byKey = new Map(existing.map((f) => [keyOf(f), f]));
|
|
41
80
|
let added = 0;
|
|
42
81
|
let updated = 0;
|
|
43
82
|
for (const fact of Array.isArray(facts) ? facts : []) {
|
|
44
83
|
if (!fact?.kind || !fact?.value) continue;
|
|
45
|
-
const
|
|
84
|
+
const subject = String(fact.subject || '').trim();
|
|
85
|
+
const key = `${fact.kind}|${subject}|${fact.value}`;
|
|
86
|
+
const chatKey = String(fact.chatKey || '');
|
|
46
87
|
const cur = byKey.get(key);
|
|
47
88
|
if (!cur) {
|
|
48
89
|
byKey.set(key, {
|
|
49
90
|
kind: fact.kind,
|
|
50
91
|
value: fact.value,
|
|
51
|
-
subject
|
|
92
|
+
subject,
|
|
52
93
|
quote: String(fact.quote || '').slice(0, 80),
|
|
53
|
-
chatKey
|
|
94
|
+
chatKey,
|
|
95
|
+
sources: chatKey ? [chatKey] : [],
|
|
54
96
|
ts: Number(fact.ts) || Date.now(),
|
|
55
97
|
count: 1
|
|
56
98
|
});
|
|
@@ -58,21 +100,20 @@ export function saveFacts(dir, facts) {
|
|
|
58
100
|
continue;
|
|
59
101
|
}
|
|
60
102
|
cur.count = (Number(cur.count) || 1) + 1;
|
|
103
|
+
// 会话来源单独留一份:同一主体在不同会话里说过,不能只记住最后一次。
|
|
104
|
+
if (chatKey) {
|
|
105
|
+
const sources = Array.isArray(cur.sources) ? cur.sources : (cur.chatKey ? [cur.chatKey] : []);
|
|
106
|
+
if (!sources.includes(chatKey)) sources.push(chatKey);
|
|
107
|
+
cur.sources = sources;
|
|
108
|
+
cur.chatKey = chatKey;
|
|
109
|
+
}
|
|
61
110
|
if ((Number(fact.ts) || 0) >= (Number(cur.ts) || 0)) {
|
|
62
111
|
cur.ts = Number(fact.ts) || cur.ts;
|
|
63
112
|
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
113
|
}
|
|
67
114
|
updated += 1;
|
|
68
115
|
}
|
|
69
|
-
|
|
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 };
|
|
116
|
+
return { rows: [...byKey.values()], added, updated };
|
|
76
117
|
}
|
|
77
118
|
|
|
78
119
|
/** 这个值能不能安全地说出来:短、是名词短语、不含动词和否定。 */
|
package/lib/file-lock.d.ts
CHANGED
|
@@ -1 +1,4 @@
|
|
|
1
|
-
export function withFileLock<T>(lockPath: string, fn: () => T, opts?: { timeoutMs?: number }): T
|
|
1
|
+
export function withFileLock<T>(lockPath: string, fn: () => T, opts?: { timeoutMs?: number }): T
|
|
2
|
+
|
|
3
|
+
/** 原子写文件(临时文件 + fsync + rename):写成功返回目标路径,失败抛错且不留临时文件 */
|
|
4
|
+
export function writeFileAtomic(file: string, data: string | Uint8Array): string
|
package/lib/file-lock.js
CHANGED
|
@@ -1,27 +1,165 @@
|
|
|
1
1
|
// 跨进程文件锁:mkdir 独占 + 忙等重试;Windows 上并发 mkdir/rm 会短暂 EPERM/ENOENT,按“忙”处理
|
|
2
|
+
//
|
|
3
|
+
// 抢锁规则(2026-11 修):
|
|
4
|
+
// - 锁目录里写 owner.json(pid + hostname + token + 心跳时间),抢锁时先看持有者是否还活着。
|
|
5
|
+
// - 同一台机器:用 pid 存活校验(process.kill(pid, 0))。持有者还活着就绝不抢,哪怕锁很旧。
|
|
6
|
+
// - 别的机器/认不出持有者:用心跳判断;心跳过期才回收。心跳只在拿到锁时写一次,
|
|
7
|
+
// 所以跨机共享目录上的长任务仍可能被误判——跨机写入应在更高层串行化。
|
|
8
|
+
// - 回收先原子 rename 成 tombstone,只有一个竞争者能 rename 成功,避免两个写入者同时进入。
|
|
9
|
+
// - 释放时核对 token,只删自己的锁,不误删别人刚抢到的锁。
|
|
2
10
|
import fs from 'node:fs'
|
|
3
11
|
import path from 'node:path'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import crypto from 'node:crypto'
|
|
4
14
|
|
|
5
15
|
const BUSY = new Set(['EEXIST', 'EPERM', 'ENOENT', 'EBUSY', 'EACCES'])
|
|
16
|
+
const OWNER_FILE = 'owner.json'
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 3000
|
|
18
|
+
const DEFAULT_STALE_MS = 10000
|
|
19
|
+
const DEFAULT_POLL_MS = 20
|
|
20
|
+
const LOCKED_MESSAGE = 'The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)'
|
|
6
21
|
|
|
7
|
-
|
|
22
|
+
// 临时文件 + fsync + rename 原子替换。中途崩了只会留下 <file>.tmp-*,正式文件保持旧内容。
|
|
23
|
+
export function writeFileAtomic(file, data) {
|
|
24
|
+
const target = String(file)
|
|
25
|
+
const dir = path.dirname(target)
|
|
26
|
+
const tmp = target + '.tmp-' + process.pid + '-' + crypto.randomUUID()
|
|
27
|
+
let fd
|
|
28
|
+
try {
|
|
29
|
+
fd = fs.openSync(tmp, 'w')
|
|
30
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')
|
|
31
|
+
let offset = 0
|
|
32
|
+
while (offset < buf.length) offset += fs.writeSync(fd, buf, offset, buf.length - offset)
|
|
33
|
+
fs.fsyncSync(fd)
|
|
34
|
+
fs.closeSync(fd)
|
|
35
|
+
fd = undefined
|
|
36
|
+
renameWithRetry(tmp, target)
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (fd !== undefined) { try { fs.closeSync(fd) } catch { } }
|
|
39
|
+
try { fs.rmSync(tmp, { force: true }) } catch { }
|
|
40
|
+
throw error
|
|
41
|
+
}
|
|
42
|
+
// 目录项也落盘(POSIX 上才有意义;Windows 打开目录会失败,静默跳过)
|
|
43
|
+
try {
|
|
44
|
+
const dirFd = fs.openSync(dir, 'r')
|
|
45
|
+
try { fs.fsyncSync(dirFd) } finally { fs.closeSync(dirFd) }
|
|
46
|
+
} catch { }
|
|
47
|
+
return target
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function renameWithRetry(from, to) {
|
|
51
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
52
|
+
try { return fs.renameSync(from, to) } catch (error) {
|
|
53
|
+
if (attempt >= 9 || !BUSY.has(error.code)) throw error
|
|
54
|
+
sleep(10)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function withFileLock(lockPath, fn, { timeoutMs = DEFAULT_TIMEOUT_MS, staleMs = DEFAULT_STALE_MS, pollMs = DEFAULT_POLL_MS } = {}) {
|
|
60
|
+
const waitMs = Number.isFinite(timeoutMs) && timeoutMs >= 0 ? timeoutMs : DEFAULT_TIMEOUT_MS
|
|
61
|
+
const staleAfter = Number.isFinite(staleMs) && staleMs >= 0 ? staleMs : DEFAULT_STALE_MS
|
|
62
|
+
const interval = Number.isFinite(pollMs) && pollMs > 0 ? pollMs : DEFAULT_POLL_MS
|
|
63
|
+
const token = crypto.randomUUID()
|
|
64
|
+
const owner = {
|
|
65
|
+
pid: process.pid,
|
|
66
|
+
hostname: os.hostname(),
|
|
67
|
+
token,
|
|
68
|
+
acquiredAt: Date.now(),
|
|
69
|
+
heartbeatAt: Date.now()
|
|
70
|
+
}
|
|
8
71
|
const start = Date.now()
|
|
9
72
|
for (;;) {
|
|
73
|
+
if (acquire(lockPath, owner)) break
|
|
74
|
+
// 过时锁只在持有者已退出(或跨机心跳过期)时回收;活着就继续等。
|
|
75
|
+
tryReclaimIfStale(lockPath, staleAfter)
|
|
76
|
+
if (Date.now() - start >= waitMs) throw new Error(LOCKED_MESSAGE)
|
|
77
|
+
sleep(interval)
|
|
78
|
+
}
|
|
79
|
+
try { return fn() } finally { release(lockPath, token) }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function acquire(lockPath, owner) {
|
|
83
|
+
try {
|
|
84
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true })
|
|
85
|
+
fs.mkdirSync(lockPath)
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.code === 'EEXIST') return false
|
|
88
|
+
if (BUSY.has(error.code)) return false
|
|
89
|
+
throw error
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
fs.writeFileSync(path.join(lockPath, OWNER_FILE), JSON.stringify(owner), 'utf8')
|
|
93
|
+
} catch (error) {
|
|
94
|
+
try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { }
|
|
95
|
+
throw error
|
|
96
|
+
}
|
|
97
|
+
return true
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function readOwner(lockPath) {
|
|
101
|
+
try {
|
|
102
|
+
const row = JSON.parse(fs.readFileSync(path.join(lockPath, OWNER_FILE), 'utf8'))
|
|
103
|
+
return row && typeof row === 'object' ? row : null
|
|
104
|
+
} catch { return null }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 'alive' | 'dead' | 'unknown'(别的机器、字段缺失、旧版锁目录)
|
|
108
|
+
function ownerStatus(owner) {
|
|
109
|
+
const pid = Number(owner?.pid)
|
|
110
|
+
const hostname = typeof owner?.hostname === 'string' ? owner.hostname : ''
|
|
111
|
+
const sameHost = hostname === '' ? pid === process.pid : hostname === os.hostname()
|
|
112
|
+
if (sameHost) {
|
|
113
|
+
if (!Number.isInteger(pid) || pid <= 0) return 'unknown'
|
|
114
|
+
if (pid === process.pid) return 'alive'
|
|
10
115
|
try {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
const st = fs.statSync(lockPath)
|
|
18
|
-
if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lockPath, { recursive: true, force: true }); continue }
|
|
19
|
-
} catch { /* 锁刚被释放 */ }
|
|
20
|
-
if (Date.now() - start > timeoutMs) throw new Error('The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)')
|
|
21
|
-
sleep(20)
|
|
116
|
+
process.kill(pid, 0)
|
|
117
|
+
return 'alive'
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (error.code === 'EPERM') return 'alive' // 系统进程/权限不足:当成活着,宁可等
|
|
120
|
+
if (error.code === 'ESRCH') return 'dead'
|
|
121
|
+
return 'unknown'
|
|
22
122
|
}
|
|
23
123
|
}
|
|
24
|
-
|
|
124
|
+
return 'unknown'
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 返回 true 表示这轮尝试过回收(或锁已经不在),调用方睡一下再重试
|
|
128
|
+
function tryReclaimIfStale(lockPath, staleMs) {
|
|
129
|
+
let stats
|
|
130
|
+
try { stats = fs.statSync(lockPath) } catch { return true }
|
|
131
|
+
const now = Date.now()
|
|
132
|
+
const age = now - stats.mtimeMs
|
|
133
|
+
const owner = readOwner(lockPath)
|
|
134
|
+
if (owner) {
|
|
135
|
+
const status = ownerStatus(owner)
|
|
136
|
+
if (status === 'alive') return false
|
|
137
|
+
if (status === 'dead') return takeOver(lockPath)
|
|
138
|
+
const beat = Number(owner.heartbeatAt) || Number(owner.acquiredAt) || stats.mtimeMs
|
|
139
|
+
if (now - beat <= staleMs) return false
|
|
140
|
+
return takeOver(lockPath)
|
|
141
|
+
}
|
|
142
|
+
if (age <= staleMs) return false
|
|
143
|
+
return takeOver(lockPath)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function takeOver(lockPath) {
|
|
147
|
+
const tombstone = lockPath + '.stale-' + process.pid + '-' + crypto.randomUUID()
|
|
148
|
+
try {
|
|
149
|
+
fs.renameSync(lockPath, tombstone)
|
|
150
|
+
} catch {
|
|
151
|
+
// 另一个竞争者先回收了(ENOENT),或 Windows 上暂时不让改名;下一轮再看
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
try { fs.rmSync(tombstone, { recursive: true, force: true }) } catch { }
|
|
155
|
+
return true
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function release(lockPath, token) {
|
|
159
|
+
const owner = readOwner(lockPath)
|
|
160
|
+
// 锁已经被别人回收/替换时不能删:只释放自己拿到的这一把。
|
|
161
|
+
if (!owner || owner.token !== token) return
|
|
162
|
+
try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { }
|
|
25
163
|
}
|
|
26
164
|
|
|
27
165
|
// 阻塞式小睡,不空转 CPU;Node 主线程允许 Atomics.wait
|
|
@@ -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,82 @@
|
|
|
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
|
+
let confirmed = false
|
|
48
|
+
return {
|
|
49
|
+
block: renderTwoPart(hit),
|
|
50
|
+
id: hit.id,
|
|
51
|
+
reason: 'ok',
|
|
52
|
+
confirm() {
|
|
53
|
+
// 同一次展示只记一次:宿主重试或重复确认不会把想起次数加成 2。
|
|
54
|
+
if (confirmed) return true
|
|
55
|
+
// 落盘失败要如实返回 false,并且不占掉 seen,下次还能再试。
|
|
56
|
+
const wrote = markRecalled(memDir, hit.id)
|
|
57
|
+
if (!wrote) return false
|
|
58
|
+
seen[hit.id] = now
|
|
59
|
+
confirmed = true
|
|
60
|
+
return true
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 本轮该不该递:只回答是/否,不碰磁盘。用于宿主自己做预算前的快速判断。 */
|
|
66
|
+
export function shouldInject({ chatKey = '', text = '', seen = {}, id = '', now = Date.now() } = {}) {
|
|
67
|
+
if (!isPrivateKey(chatKey)) return { ok: false, reason: 'not-private' }
|
|
68
|
+
if (!String(text || '').trim()) return { ok: false, reason: 'no-hit' }
|
|
69
|
+
if (id && Number(seen[id] || 0) && now - Number(seen[id]) < DAY) return { ok: false, reason: 'recently-shown' }
|
|
70
|
+
return { ok: true, reason: 'ok' }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const INJECTION_RULES = [
|
|
74
|
+
'只在一对一里递',
|
|
75
|
+
'一轮最多一块',
|
|
76
|
+
'同一条 24 小时内不重复',
|
|
77
|
+
'用户提到相关话题才递',
|
|
78
|
+
'默认用 strict',
|
|
79
|
+
'递了才记',
|
|
80
|
+
'没命中就闭嘴',
|
|
81
|
+
'守卫只能否决'
|
|
82
|
+
]
|
package/lib/query-match.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
// 查询匹配:self-experience 与 self-memory 共用同一套口径,防编造的门槛只在这里定义
|
|
2
|
-
//
|
|
2
|
+
// 中文等按相邻两字切;拉丁字母按整词切、也按整词匹配(不切成字母对,否则 "the" 会命中一切;
|
|
3
|
+
// 也不能拿子串去命中,否则 "art" 会命中 "started"、"he" 会命中 "the");统一小写
|
|
4
|
+
//
|
|
5
|
+
// ⚠️ 适用边界:这套口径用来在「她自己的经历」里找工作——候选集是她自己的记忆,先验很强。
|
|
6
|
+
// 别拿它当跨窗口/跨房间的检索门槛:那边的候选集大得多、先验弱得多,1 个内容词命中
|
|
7
|
+
// 就从「勉强能召回」变成「噪声发生器」。实测 15 轮真实样本 0 条有用,见 docs/pitfalls.md 第 10 条。
|
|
3
8
|
|
|
4
9
|
// 高频但不携带信息的词:不参与重叠计算,避免「今天/什么/我的」把不相关的东西拉进来
|
|
5
10
|
const STOP = new Set([
|
|
@@ -19,18 +24,27 @@ export function normalizeText(s) {
|
|
|
19
24
|
return String(s || '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
|
|
20
25
|
}
|
|
21
26
|
|
|
27
|
+
// 拉丁词按整词比:normalizeText 会把空格抹掉,抹完再 includes 就成了子串比。
|
|
28
|
+
// 这里单独把原文切成小写整词,只用来和拉丁词对词
|
|
29
|
+
export function wordTokens(s) {
|
|
30
|
+
return new Set(String(s || '').toLowerCase().match(/[a-z]+/g) || [])
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const LATIN_TERM = /^[a-z]+$/
|
|
34
|
+
|
|
22
35
|
// 查询 → 待匹配的词:拉丁字母连写成词,其余(汉字、数字等)按相邻两字切
|
|
23
36
|
export function queryTerms(q) {
|
|
24
37
|
const lower = String(q || '').toLowerCase()
|
|
25
38
|
const cleaned = normalizeText(lower)
|
|
26
39
|
const terms = new Set()
|
|
27
40
|
for (const w of lower.match(/[a-z]+/g) || []) {
|
|
28
|
-
if (w.length >= 2 && !STOP.has(w)) terms.add(w)
|
|
41
|
+
if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) terms.add(w)
|
|
29
42
|
}
|
|
30
43
|
for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
|
|
31
44
|
for (let i = 0; i + 2 <= run.length; i++) {
|
|
32
45
|
const g = run.slice(i, i + 2)
|
|
33
|
-
|
|
46
|
+
// 垫话本身不携带内容:「说说 / 上次 / 之前」这类两字组单独命中,不该把一段记忆叫出来
|
|
47
|
+
if (!STOP.has(g) && !FILLER.has(g)) terms.add(g)
|
|
34
48
|
}
|
|
35
49
|
}
|
|
36
50
|
return { cleaned, terms }
|
|
@@ -38,7 +52,7 @@ export function queryTerms(q) {
|
|
|
38
52
|
|
|
39
53
|
// 只起语法作用的单字:算「查询里有多少意思被这段记忆接住了」时不计入
|
|
40
54
|
const STOP_CHARS = new Set([...'的了吗呢吧啊呀么着过在里那这个些次段事就也都还又很把被给跟和与及或是有我你他她它们嘛啦哦呃'])
|
|
41
|
-
// 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP
|
|
55
|
+
// 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP(旧口径不受影响)
|
|
42
56
|
const FILLER = new Set([
|
|
43
57
|
'怎么样', '怎样', '上次', '之前', '最近', '说说', '讲讲', '聊聊', '说过', '提过', '讲过', '记不记得', '还记得',
|
|
44
58
|
'跟我', '说的', '讲的', '提到', '那件', '那次', '那段', '那天', '那个时候',
|
|
@@ -52,12 +66,20 @@ const SKIP_LENS = [...new Set([...SKIP_WORDS].filter((w) => !/[a-z]/.test(w)).ma
|
|
|
52
66
|
const ISOLATED_LEN = 60
|
|
53
67
|
// 可以跟在内容字右边、算作"连着"的助词和语气词
|
|
54
68
|
const SUFFIX = new Set([...'了的吗呢吧啊呀么着过'])
|
|
69
|
+
// 没有相邻内容字可以作证的单字(通常是「的 / 了」后面那个名词,如「守灯人的猫」的「猫」):
|
|
70
|
+
// 它没出现却按 KEY_WEIGHT 份算——那句话里单独的那个名词不在,就不是把这件事想起来了。
|
|
71
|
+
// 否则「守灯人的猫」会以 3/4 的覆盖率把「守灯人」那条叫出来,而那条根本没有猫。
|
|
72
|
+
const KEY_WEIGHT = 1.5
|
|
73
|
+
// 询问、数量用字:它们是"在问什么",不是这条经历欠她的内容,缺了不算前提错(「交给谁」不该被拦下)
|
|
74
|
+
const NOT_KEY = new Set([...'谁哪几什么多少一二三四五六七八九十百千万半两个只件种样点咋啥'])
|
|
55
75
|
|
|
56
76
|
// 查询里要被接住的单位:拉丁字母按整词;其余按单字,并记下它左右两个两字组(用来判断是不是连着出现)
|
|
57
77
|
export function contentUnits(q) {
|
|
58
78
|
const lower = String(q || '').toLowerCase()
|
|
59
79
|
const units = []
|
|
60
|
-
for (const w of lower.match(/[a-z]+/g) || [])
|
|
80
|
+
for (const w of lower.match(/[a-z]+/g) || []) {
|
|
81
|
+
if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) units.push({ u: w, word: true, pairs: [] })
|
|
82
|
+
}
|
|
61
83
|
for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
|
|
62
84
|
const skip = new Set()
|
|
63
85
|
for (let i = 0; i < run.length; i++) for (const L of SKIP_LENS) if (i + L <= run.length && SKIP_WORDS.has(run.slice(i, i + L))) for (let k = i; k < i + L; k++) skip.add(k)
|
|
@@ -74,36 +96,63 @@ export function contentUnits(q) {
|
|
|
74
96
|
}
|
|
75
97
|
|
|
76
98
|
// 覆盖率:查询里的意思有几成在这段记忆里找得到(0~1)
|
|
77
|
-
//
|
|
78
|
-
//
|
|
99
|
+
// 和左右任一个内容字连着出现 → 1 分
|
|
100
|
+
// 只是单独出现 → 0.5 × min(1, 60 / 记忆长度) 分(孤立单字没有邻字作证,不能白送满分)
|
|
101
|
+
// 没有 → 0 分
|
|
102
|
+
// 拉丁词只有整词出现才得分(art 不命中 started,he 不命中 the)
|
|
103
|
+
// 孤立单字没出现时按 KEY_WEIGHT 份算:关键那个单独的名词不在,就不是这件事
|
|
79
104
|
export function coverage(units, text) {
|
|
80
105
|
if (!units.length) return 0
|
|
81
106
|
const t = normalizeText(text)
|
|
107
|
+
const words = wordTokens(text)
|
|
108
|
+
// 查询只剩一个内容单元时(「夜里」:里是虚词不算,只剩「夜」),它出现就是全部意思都在;
|
|
109
|
+
// 不给这个豁免的话,「夜里」会被自己的孤立半份压到 0.5,连它自己那条都招不回来
|
|
110
|
+
const whole = units.length === 1
|
|
82
111
|
let got = 0
|
|
112
|
+
let total = 0
|
|
83
113
|
for (const x of units) {
|
|
84
|
-
if (
|
|
85
|
-
|
|
86
|
-
|
|
114
|
+
if (x.word) {
|
|
115
|
+
total += 1
|
|
116
|
+
if (words.has(x.u)) got += 1
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const isolated = !x.pairs.length
|
|
120
|
+
if (!isolated) {
|
|
121
|
+
total += 1
|
|
122
|
+
if (x.pairs.some((p) => t.includes(p))) got += 1
|
|
123
|
+
else if (t.includes(x.u)) got += 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
const here = t.includes(x.u)
|
|
127
|
+
if (here) got += whole ? 1 : 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
|
|
128
|
+
// 出现了只说半份;没出现又是个实在的名词,就多算半份,把覆盖率压向门槛以下
|
|
129
|
+
total += !here && !NOT_KEY.has(x.u) ? KEY_WEIGHT : 1
|
|
87
130
|
}
|
|
88
|
-
return got /
|
|
131
|
+
return total ? got / total : 0
|
|
89
132
|
}
|
|
90
133
|
|
|
91
134
|
// strict 的门槛:至少对上一个两字词(有个落脚点),并且查询的意思至少有这么多被接住
|
|
92
135
|
export const MIN_COVER = 0.7
|
|
136
|
+
// loose 也有最低比例,只是比 strict 低:一段长问句里只碰上一个词,不该把不相干的东西叫出来
|
|
137
|
+
export const LOOSE_MIN_RATIO = 0.34
|
|
93
138
|
|
|
94
139
|
// mode='strict':长查询(≥8 字)要求 ≥minRatio 的词命中,宁可不召回也不硬凑
|
|
95
|
-
// mode='loose'
|
|
140
|
+
// mode='loose':比 strict 松,但比例门槛还在(否则一个垫话两字组就能召回一整段)
|
|
96
141
|
export function requiredOverlap({ cleaned, terms }, { mode = 'strict', minOverlap = 1, minRatio = 0.6 } = {}) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
142
|
+
if (String(cleaned || '').length < 8) return minOverlap
|
|
143
|
+
const ratio = mode === 'loose' ? Math.min(minRatio, LOOSE_MIN_RATIO) : minRatio
|
|
144
|
+
return Math.max(minOverlap, Math.ceil(terms.size * ratio))
|
|
100
145
|
}
|
|
101
146
|
|
|
102
|
-
//
|
|
147
|
+
// 文本里命中了哪些词(拉丁词按整词比;中文两字组按归一化后的文本比)
|
|
103
148
|
export function matchedTerms(terms, text) {
|
|
104
149
|
const t = normalizeText(text)
|
|
105
150
|
const out = new Set()
|
|
106
151
|
if (!t) return out
|
|
107
|
-
|
|
152
|
+
const words = wordTokens(text)
|
|
153
|
+
for (const g of terms) {
|
|
154
|
+
if (LATIN_TERM.test(g)) { if (words.has(g)) out.add(g); continue }
|
|
155
|
+
if (t.includes(g)) out.add(g)
|
|
156
|
+
}
|
|
108
157
|
return out
|
|
109
|
-
}
|
|
158
|
+
}
|
package/lib/scope-key.d.ts
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
export function baseChatKey(chatKey: string): string
|
|
3
3
|
/** 这个键是不是人设级 */
|
|
4
4
|
export function isPersonaScoped(chatKey: string): boolean
|
|
5
|
+
/** 这个键是不是群 / 公共场景(group_1、qq:group:1、private:group_123、群聊……) */
|
|
6
|
+
export function isGroupScope(chatKey: string): boolean
|
|
7
|
+
/** 这个键是不是认得出来的一对一私聊;带群标记或认不出的一律 false(宁可不给) */
|
|
8
|
+
export function isPrivateScope(chatKey: string): boolean
|
|
5
9
|
/** 一次查询应覆盖的键:人设级 = [人设键, 会话键];会话级 = [会话键](不反向并入,避免串台) */
|
|
6
10
|
export function scopeKeysFor(chatKey: string): string[]
|
|
7
11
|
/** 记录是否落在查询范围内 */
|