dsh-fish-soul 0.18.10 → 0.18.12
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 +1 -1
- package/lib/behavior.js +2 -1
- package/lib/channels/douyin.js +15 -5
- package/lib/channels/vendor/douyin-bridge/douyin-dm.mjs +5 -0
- package/lib/channels/vendor/douyin-bridge/media.mjs +56 -0
- package/lib/chat-archive-fts.js +92 -0
- package/lib/chat-archive.js +32 -3
- package/lib/client.soul.js +13 -4
- package/lib/db.js +8 -1
- package/lib/gateway-media.js +4 -1
- package/lib/gateway.js +89 -3
- package/lib/index.js +33 -1
- package/lib/life.js +24 -5
- package/lib/mood-guard.js +69 -0
- package/lib/routes-soul.js +4 -0
- package/lib/slang.js +21 -16
- package/lib/soul-memory.js +21 -4
- package/lib/tts-text.js +71 -0
- package/package.json +3 -3
package/README.md
CHANGED
package/lib/behavior.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { getKv, setKv } from './db.js';
|
|
13
13
|
import { segmentsToText, sanitizeName } from './channels/onebot.js';
|
|
14
14
|
import { insertMemory, getMood, setMood, relTime } from './soul-memory.js';
|
|
15
|
+
import { MOOD_STATE_GUARD } from './mood-guard.js';
|
|
15
16
|
import { recallSync, vectorRanks, excludedMemories } from './retrieval.js';
|
|
16
17
|
|
|
17
18
|
const num = (x, d, lo, hi) => { const n = Number(x); return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : d; };
|
|
@@ -767,7 +768,7 @@ export function behaviorLines({ db, getConfig, session, known, tone, now, diary,
|
|
|
767
768
|
const last = known[known.length - 1];
|
|
768
769
|
const p = moodProfile({ tone, mood: last ? getMood(db, last.ownerId, now) : null });
|
|
769
770
|
const own = moodStyle(moods, p);
|
|
770
|
-
if (p.hint) out.push(`[你现在的状态] ${p.hint}——体现在回复的快慢、长短和语气上,别直接说出来。${own ? `${own}。` : ''}`);
|
|
771
|
+
if (p.hint) out.push(`[你现在的状态] ${p.hint}——体现在回复的快慢、长短和语气上,别直接说出来。${own ? `${own}。` : ''}${MOOD_STATE_GUARD}`);
|
|
771
772
|
}
|
|
772
773
|
// 去 AI 味:发出去以后再删只能删漏网的,先在提示里压一压(参考 MaiBot 的默认说话风格)
|
|
773
774
|
if (cfg.outFilter.enabled && session.channel !== 'dsh') {
|
package/lib/channels/douyin.js
CHANGED
|
@@ -113,6 +113,10 @@ export function convTimeMs(s, now = new Date()) {
|
|
|
113
113
|
|
|
114
114
|
/** 抖音私信里一条消息的指纹(对比窗口用):谁发的 + 正文 + 媒体(图片地址去掉会变的签名参数)。 */
|
|
115
115
|
export function messageFingerprint(m) {
|
|
116
|
+
// 分享卡片按平台作品 ID 认:DOM 路只拿得到作者名,同作者的两张不同卡片会撞成同一个指纹。
|
|
117
|
+
// 保留 me/peer 这一维(null 与 false 同按对方算,和下面的规则一致)。
|
|
118
|
+
const card = String(m?.shareAweme ?? '').trim();
|
|
119
|
+
if (card !== '') return sha1(`card|${m?.fromMe === true ? 'me' : 'peer'}|${card}`).slice(0, 16);
|
|
116
120
|
const media = m?.media ?? {};
|
|
117
121
|
let src = String(media.data || media.src || '');
|
|
118
122
|
if (src.startsWith('data:')) src = sha1(src).slice(0, 16);
|
|
@@ -210,11 +214,17 @@ export function messageIdFor(m, { print = '', occ = 0, fallbackTime = Date.now()
|
|
|
210
214
|
const timeMs = rawTime > 1e12 ? rawTime : rawTime > 1e9 ? rawTime * 1000 : fallbackTime;
|
|
211
215
|
const seq = String(m?.seq ?? '').trim();
|
|
212
216
|
const day = dayKey || new Date().toISOString().slice(0, 10);
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
217
|
+
// 分享卡片提到最前:DOM 路的「时间」是从「刚刚 / N 分钟前」反解出来的,每轮询一次就变一个值,
|
|
218
|
+
// 拿它当 ID 等于 UNIQUE(channel_id, message_id) 完全失效(真机:一张卡入库 13 次、回了 13 遍)。
|
|
219
|
+
// 作品 ID 跨轮询稳定、跨卡片唯一,比 seq 还准(DOM 路本来就没有 seq)。
|
|
220
|
+
const card = String(m?.shareAweme ?? '').trim();
|
|
221
|
+
const messageId = card !== ''
|
|
222
|
+
? `c${card}-${occ}`
|
|
223
|
+
: seq !== ''
|
|
224
|
+
? `s${seq}`
|
|
225
|
+
: hasTime
|
|
226
|
+
? `${print}-${timeMs}-${occ}`
|
|
227
|
+
: `${print}-${day}-${occ}`;
|
|
218
228
|
return { timeMs, messageId };
|
|
219
229
|
}
|
|
220
230
|
|
|
@@ -694,6 +694,9 @@ async function readDMDom({ browser, limit = 30, uname = '', scrollBack = 0 }) {
|
|
|
694
694
|
media.height = dim.h
|
|
695
695
|
} else if (type === 'share') {
|
|
696
696
|
media.title = textOf(box, 'MessageItemShareAwemeauthorName') || text
|
|
697
|
+
// 平台作品 ID:去重键和「同作者不同卡片」的区分都靠它(拿不到就空着,上层退回老规则)
|
|
698
|
+
const shareId = shareItemIdOf(box)
|
|
699
|
+
if (shareId) media.shareAweme = shareId
|
|
697
700
|
}
|
|
698
701
|
|
|
699
702
|
// 文本类没正文 → 忽略;**媒体类照样要**
|
|
@@ -706,6 +709,8 @@ async function readDMDom({ browser, limit = 30, uname = '', scrollBack = 0 }) {
|
|
|
706
709
|
type,
|
|
707
710
|
text: text.slice(0, 500),
|
|
708
711
|
media,
|
|
712
|
+
// 分享卡片的平台作品 ID(别的类型是空串)。上层按它做稳定去重。
|
|
713
|
+
shareAweme: type === 'share' ? String(media.shareAweme || '') : '',
|
|
709
714
|
senderName,
|
|
710
715
|
// ⭐ 从气泡上的时间文字反解出来的时间(0 = 认不出)。
|
|
711
716
|
// 上层拿它当去重键,**不能**再用 Date.now() —— 那样每读一次就换一个 ID,
|
|
@@ -56,6 +56,55 @@ export const MEDIA = {
|
|
|
56
56
|
*
|
|
57
57
|
* @returns {string} JS 源码(IIFE)
|
|
58
58
|
*/
|
|
59
|
+
/**
|
|
60
|
+
* 分享卡片里平台自己的作品 ID(itemId)。
|
|
61
|
+
*
|
|
62
|
+
* 🔴 为什么非要它:DOM 路以前只拿到作者名(innerText),没有作品 ID ⇒
|
|
63
|
+
* ① 同一作者的两张不同卡片指纹一模一样,会互相吞;
|
|
64
|
+
* ② 卡片没有平台消息号,去重键只能退化成「指纹-反解时间-occ」,而反解时间来自
|
|
65
|
+
* 「刚刚 / N 分钟前」这种**相对**标签 —— 每轮询一次就换一个值
|
|
66
|
+
* ⇒ UNIQUE(channel_id, message_id) 完全失效,同一张卡反复入库、反复触发回复。
|
|
67
|
+
*
|
|
68
|
+
* 走 React props 拿平台 itemId:跨轮询稳定、跨卡片唯一。
|
|
69
|
+
* 这个函数同时被页面脚本(经 `${String(shareItemIdOf)}` 注入)和测试直接调用 —— 只有一份实现。
|
|
70
|
+
*
|
|
71
|
+
* @param {object} box 消息气泡节点(会从它和它内部卡片容器往上找 6 层 props)
|
|
72
|
+
* @returns {string} 作品 ID;认不出唯一一个就返回空串(宁可退回老规则,也不猜错的)
|
|
73
|
+
*/
|
|
74
|
+
export function shareItemIdOf(box) {
|
|
75
|
+
const found = new Set();
|
|
76
|
+
const walk = (value, depth, seen) => {
|
|
77
|
+
if (!value || typeof value !== 'object' || depth > 7 || seen.has(value)) return;
|
|
78
|
+
seen.add(value);
|
|
79
|
+
const message = value.message;
|
|
80
|
+
if (message && typeof message === 'object') {
|
|
81
|
+
const parsed = message.parsedContent || {};
|
|
82
|
+
const id = String(parsed.itemId || parsed.aweme_id || '');
|
|
83
|
+
if (/^\d{8,20}$/.test(id)) found.add(id);
|
|
84
|
+
}
|
|
85
|
+
for (const key of Object.keys(value)) {
|
|
86
|
+
if (key === '_owner' || key === '_store' || key === 'ref' || key === 'message') continue;
|
|
87
|
+
if (typeof value[key] === 'object') walk(value[key], depth + 1, seen);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
// 从卡片容器本身和消息外层各往上找:真机里 props 挂在卡片内层节点上,只从外层找够不到。
|
|
91
|
+
const holders = [box];
|
|
92
|
+
const needle = 'MessageItemShareAwemecontainer';
|
|
93
|
+
const clsOf = (el) => String((el && el.className) || '');
|
|
94
|
+
if (box && !clsOf(box).includes(needle) && box.querySelectorAll) {
|
|
95
|
+
for (const el of box.querySelectorAll('div,span,a')) {
|
|
96
|
+
if (clsOf(el).includes(needle)) { holders.push(el); break; }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
for (const start of holders) {
|
|
100
|
+
let node = start;
|
|
101
|
+
for (let i = 0; i < 6 && node; i++, node = node.parentElement) {
|
|
102
|
+
for (const key of Object.keys(node).filter((k) => k.startsWith('__reactProps'))) walk(node[key], 0, new Set());
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return found.size === 1 ? [...found][0] : '';
|
|
106
|
+
}
|
|
107
|
+
|
|
59
108
|
export function pageMediaHelper() {
|
|
60
109
|
// ⚠️ 这里面**不能出现反引号** —— `browser.eval` 用的是模板字符串,
|
|
61
110
|
// 裸反引号会把外层模板截断(踩过:`SyntaxError: missing ) after argument list`)。
|
|
@@ -129,6 +178,9 @@ export function pageMediaHelper() {
|
|
|
129
178
|
return { w: Math.round(r.width), h: Math.round(r.height) }
|
|
130
179
|
}
|
|
131
180
|
|
|
181
|
+
// 分享卡片的平台作品 ID(源码与模块里的 shareItemIdOf 是同一份)
|
|
182
|
+
const shareItemIdOf = ${String(shareItemIdOf)}
|
|
183
|
+
|
|
132
184
|
// 语音时长(秒)
|
|
133
185
|
const voiceSeconds = (box) => {
|
|
134
186
|
const raw = textOf(box, 'MessageItemAudioduration') || textOf(box, 'MessageItemAudiovoiceText')
|
|
@@ -317,6 +369,10 @@ export function mergeMessages(api, dom) {
|
|
|
317
369
|
let ai = 0
|
|
318
370
|
for (const d of domList) {
|
|
319
371
|
if (d.type && d.type !== MEDIA.TEXT) {
|
|
372
|
+
// 分享卡片:接口路已经报过同一个作品 ID 的话,这份是同一张卡的第二份读数,丢掉。
|
|
373
|
+
// 两路各推一份 ⇒ 指纹不同 ⇒ 上层当成两条新消息 ⇒ 同一张卡回两次。
|
|
374
|
+
const card = String(d.shareAweme || '')
|
|
375
|
+
if (card !== '' && apiList.some((a) => String(a.shareAweme || '') === card)) continue
|
|
320
376
|
// 媒体消息:插到当前 API 位置
|
|
321
377
|
out.push(d)
|
|
322
378
|
continue
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chat-archive.js 的 FTS5 检索层(PR1:原文可检索)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么:chat_text 只有按时间的索引,没有任何检索能力 —— Dream / 模型想核对
|
|
5
|
+
* 「他上次到底说没说过这句话」只能按时间窗捞。anima-brain 的 evidence 层证明
|
|
6
|
+
* 了「原文不可变 + 独立 FTS 索引」是可行的形状:原文层永不改写,检索走
|
|
7
|
+
* 预分词的 FTS5,命中返回带片段的行而不是整段。
|
|
8
|
+
*
|
|
9
|
+
* 分词复用 segment.js 的 tokenizeForBm25(Intl.Segmenter,零依赖)——
|
|
10
|
+
* 存「空格分隔的词项串」而不是原文:FTS5 默认 unicode61 分词器对中文按字切,
|
|
11
|
+
* 直接存原文会让查询「考试」对不上存的「考 试」。查询侧用 queryForBm25
|
|
12
|
+
* 出同一套词项(含拆字低权重补项),两边对得上。
|
|
13
|
+
*
|
|
14
|
+
* 🔴 FTS5 的两个硬约束(都真机验过):
|
|
15
|
+
* ① 别名不能用 —— `WHERE f MATCH ?` 和 `bm25(f)` 都报 `no such column: f`,
|
|
16
|
+
* 必须写表名 `chat_fts`。副表(chat_text)可以用别名。
|
|
17
|
+
* ② 查询串必须是「引号包起来的词项 OR 连接」,否则 FTS5 把中文当语法。
|
|
18
|
+
*
|
|
19
|
+
* 断链自愈:老库升级 / 崩溃后 fts 与 chat_text 可能对不齐。rebuildFts() 逐行对账。
|
|
20
|
+
* 不在 open() 时自动跑(大库会卡启动),由调用方按需触发。
|
|
21
|
+
*/
|
|
22
|
+
import { tokenizeForBm25, queryForBm25 } from './segment.js';
|
|
23
|
+
|
|
24
|
+
/** 建 fts 表 + DELETE 联动触发器。INSERT 侧分词必须在应用层做(触发器里调不了 JS 分词)。 */
|
|
25
|
+
export function ensureFts(db) {
|
|
26
|
+
db.exec('CREATE VIRTUAL TABLE IF NOT EXISTS chat_fts USING fts5(id UNINDEXED, terms)');
|
|
27
|
+
db.exec(`CREATE TRIGGER IF NOT EXISTS chat_fts_ad AFTER DELETE ON chat_text BEGIN
|
|
28
|
+
DELETE FROM chat_fts WHERE id = old.id;
|
|
29
|
+
END`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 写入一行索引。add() 插完 chat_text 后调,rowid 与 chat_text.id 对齐。 */
|
|
33
|
+
export function indexRow(db, id, content) {
|
|
34
|
+
db.prepare('INSERT INTO chat_fts(id, terms) VALUES(?,?)').run(Number(id), tokenizeForBm25(String(content ?? '')));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 对账:fts 缺的补、多的删。返回 `{ok, fixed}`;库太大(>5 万行)返回 `{ok:false, skipped:true}`。
|
|
39
|
+
* 失败要能说出来 —— 静默 return 0 会让「没修」和「没坏」看起来一样。
|
|
40
|
+
*/
|
|
41
|
+
export function rebuildFts(db) {
|
|
42
|
+
const count = Number(db.prepare('SELECT COUNT(*) n FROM chat_text').get()?.n ?? 0);
|
|
43
|
+
if (count > 50_000) return { ok: false, skipped: true, reason: '存档太大,跳过重建', fixed: 0 };
|
|
44
|
+
db.exec('BEGIN');
|
|
45
|
+
try {
|
|
46
|
+
let fixed = 0;
|
|
47
|
+
// 缺的补:chat_text 有、chat_fts 没有
|
|
48
|
+
const ins = db.prepare('INSERT INTO chat_fts(id, terms) VALUES(?,?)');
|
|
49
|
+
for (const r of db.prepare('SELECT id, content FROM chat_text WHERE id NOT IN (SELECT id FROM chat_fts)').all()) {
|
|
50
|
+
ins.run(Number(r.id), tokenizeForBm25(String(r.content ?? '')));
|
|
51
|
+
fixed++;
|
|
52
|
+
}
|
|
53
|
+
// 多的删:chat_fts 有、chat_text 没有
|
|
54
|
+
fixed += Number(db.prepare('DELETE FROM chat_fts WHERE id NOT IN (SELECT id FROM chat_text)').run().changes ?? 0);
|
|
55
|
+
db.exec('COMMIT');
|
|
56
|
+
return { ok: true, fixed };
|
|
57
|
+
} catch (e) {
|
|
58
|
+
try { db.exec('ROLLBACK'); } catch { /* 回滚失败就让它带着原始错误抛 */ }
|
|
59
|
+
return { ok: false, fixed: 0, reason: e instanceof Error ? e.message : String(e) };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 只读检索:词项 OR 匹配 + bm25 排序,返回带命中片段的行。
|
|
65
|
+
*
|
|
66
|
+
* 返回 `{ok, rows, error}` 而不是裸数组:检索失败必须和「确实没有」分开
|
|
67
|
+
* (`.catch(() => [])` 会把超时/语法错和空结果混成同一个值,这是本项目踩过的坑)。
|
|
68
|
+
* 调用方想 fail-open 就自己看 ok。
|
|
69
|
+
*
|
|
70
|
+
* @returns {{ok:boolean, rows:Array<{id:number,who:string,self:boolean,content:string,at:number,snippet:string}>, error?:string}}
|
|
71
|
+
*/
|
|
72
|
+
export function searchChatText(db, query, { channel = '', limit = 12 } = {}) {
|
|
73
|
+
const { terms } = queryForBm25(String(query ?? ''));
|
|
74
|
+
if (terms.length === 0) return { ok: true, rows: [] };
|
|
75
|
+
const n = Math.min(30, Math.max(1, Math.floor(Number(limit) || 12)));
|
|
76
|
+
const match = terms.map((t) => `"${t.replace(/"/g, '""')}"`).join(' OR ');
|
|
77
|
+
try {
|
|
78
|
+
const sql = `SELECT chat_fts.id AS id, t.who, t.self, t.content, t.at,
|
|
79
|
+
snippet(chat_fts, 1, '「', '」', '…', 12) AS snip
|
|
80
|
+
FROM chat_fts JOIN chat_text t ON t.id = chat_fts.id
|
|
81
|
+
${channel !== '' ? 'WHERE chat_fts MATCH ? AND t.channel_id = ?' : 'WHERE chat_fts MATCH ?'}
|
|
82
|
+
ORDER BY bm25(chat_fts) LIMIT ?`;
|
|
83
|
+
const args = channel !== '' ? [match, channel, n] : [match, n];
|
|
84
|
+
const rows = db.prepare(sql).all(...args).map((r) => ({
|
|
85
|
+
id: Number(r.id), who: String(r.who ?? ''), self: r.self === 1,
|
|
86
|
+
content: String(r.content ?? ''), at: Number(r.at) || 0, snippet: String(r.snip ?? '')
|
|
87
|
+
}));
|
|
88
|
+
return { ok: true, rows };
|
|
89
|
+
} catch (e) {
|
|
90
|
+
return { ok: false, rows: [], error: e instanceof Error ? e.message : String(e) };
|
|
91
|
+
}
|
|
92
|
+
}
|
package/lib/chat-archive.js
CHANGED
|
@@ -3,14 +3,15 @@ import { DatabaseSync } from 'node:sqlite';
|
|
|
3
3
|
import { existsSync,mkdirSync,chmodSync,openSync,closeSync } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { fishSoulDir } from './db.js';
|
|
6
|
+
import { ensureFts, indexRow, rebuildFts, searchChatText } from './chat-archive-fts.js';
|
|
6
7
|
const DAY=86400000;
|
|
7
8
|
export class ChatArchive {
|
|
8
|
-
constructor({getConfig,log=()=>{}}){this.getConfig=getConfig;this.log=log;this.db=null;this.error='';this.failures=0;}
|
|
9
|
+
constructor({getConfig,log=()=>{}}){this.getConfig=getConfig;this.log=log;this.db=null;this.error='';this.failures=0;this.ftsChecked=false;}
|
|
9
10
|
config(){const c=this.getConfig()?.chatArchive ?? {};return {enabled:c.enabled===true,channels:Array.isArray(c.channels)?c.channels.filter(x=>typeof x==='string'&&x.length>0):[],days:Math.max(1,Math.min(3650,Math.floor(Number(c.days)||30)))};}
|
|
10
|
-
open(create=false){if(this.db)return this.db;const path=join(fishSoulDir(),'chat-archive.db');if(!create&&!existsSync(path))return null;mkdirSync(fishSoulDir(),{recursive:true,mode:0o700});if(!existsSync(path)){try {closeSync(openSync(path,'wx',0o600));}catch(e){if(e.code!=='EEXIST')throw e;}}chmodSync(path,0o600);const db=new DatabaseSync(path);db.exec('PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS chat_text(id INTEGER PRIMARY KEY, channel_id TEXT NOT NULL, who TEXT NOT NULL, self INTEGER NOT NULL, content TEXT NOT NULL, at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS chat_text_channel_at ON chat_text(channel_id,at DESC);');this.db=db;return db;}
|
|
11
|
+
open(create=false){if(this.db)return this.db;const path=join(fishSoulDir(),'chat-archive.db');if(!create&&!existsSync(path))return null;mkdirSync(fishSoulDir(),{recursive:true,mode:0o700});if(!existsSync(path)){try {closeSync(openSync(path,'wx',0o600));}catch(e){if(e.code!=='EEXIST')throw e;}}chmodSync(path,0o600);const db=new DatabaseSync(path);db.exec('PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS chat_text(id INTEGER PRIMARY KEY, channel_id TEXT NOT NULL, who TEXT NOT NULL, self INTEGER NOT NULL, content TEXT NOT NULL, at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS chat_text_channel_at ON chat_text(channel_id,at DESC);');ensureFts(db);this.db=db;return db;}
|
|
11
12
|
add(channel,line){const cfg=this.config();if(!cfg.enabled)return;
|
|
12
13
|
// channels 留空 = 全记(默认);填了才按白名单过滤
|
|
13
|
-
if(cfg.channels.length>0&&!cfg.channels.includes(channel))return;try {const text=String(line?.text??'').trim();if(!text)return;if(Buffer.byteLength(text,'utf8')>2*1024*1024)throw new Error('文本过长');this.open(true).prepare('INSERT INTO chat_text(channel_id,who,self,content,at) VALUES(?,?,?,?,?)').run(channel,String(line.who??''),line.self===true?1:0,text,Date.now());this.error='';}catch {this.failures++;this.error='聊天存档写入失败';this.log('warn','[fish-soul] 聊天存档写入失败,聊天继续');}}
|
|
14
|
+
if(cfg.channels.length>0&&!cfg.channels.includes(channel))return;try {const text=String(line?.text??'').trim();if(!text)return;if(Buffer.byteLength(text,'utf8')>2*1024*1024)throw new Error('文本过长');const db=this.open(true);db.prepare('INSERT INTO chat_text(channel_id,who,self,content,at) VALUES(?,?,?,?,?)').run(channel,String(line.who??''),line.self===true?1:0,text,Date.now());const rowId=Number(db.prepare('SELECT last_insert_rowid() n').get().n);indexRow(db,rowId,text);this.error='';}catch {this.failures++;this.error='聊天存档写入失败';this.log('warn','[fish-soul] 聊天存档写入失败,聊天继续');}}
|
|
14
15
|
prune(){try{const db=this.open();if(!db)return;db.prepare('DELETE FROM chat_text WHERE at < ?').run(Date.now()-this.config().days*DAY);db.exec('PRAGMA wal_checkpoint(TRUNCATE)');}catch{this.error='聊天存档清理失败';}}
|
|
15
16
|
state(){let count=0, stored=[];try{const db=this.open();count=Number(db?.prepare('SELECT COUNT(*) n FROM chat_text').get()?.n??0);stored=db?db.prepare('SELECT channel_id AS channel, COUNT(*) AS count FROM chat_text GROUP BY channel_id ORDER BY max(at) DESC LIMIT 100').all():[];}catch{this.error='聊天存档读取失败';}return {ok:true,...this.config(),count,stored,error:this.error,failures:this.failures};}
|
|
16
17
|
list(channel,before=Number.MAX_SAFE_INTEGER){try {const db=this.open();const items=db?db.prepare('SELECT id,channel_id AS channel,who,self,content,at FROM chat_text WHERE channel_id=? AND id<? ORDER BY id DESC LIMIT 50').all(channel,before):[];return {ok:true,items,next:items.length===50?items[items.length-1].id:null};}catch{return {ok:false,error:'读取聊天存档失败'};}}
|
|
@@ -40,6 +41,34 @@ export class ChatArchive {
|
|
|
40
41
|
return rows.map((r) => ({ who: String(r.who ?? ''), self: r.self === 1, content: String(r.content ?? ''), at: Number(r.at) || 0 }));
|
|
41
42
|
} catch { return []; }
|
|
42
43
|
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 关键词检索原文(PR1)。只读、有上限。
|
|
47
|
+
*
|
|
48
|
+
* 返回 `{ok,rows,error}` 而不是裸数组:**检索失败必须和「确实没有」分开**
|
|
49
|
+
* (`.catch(() => [])` 会把索引断掉和空结果混成同一个值,这是本项目踩过的坑)。
|
|
50
|
+
*
|
|
51
|
+
* 首次调用对账一次(老库的 chat_text 没有 fts 行),库太大(>5 万行)跳过对账 ——
|
|
52
|
+
* 检索照常工作,只是升级前的旧行查不到。
|
|
53
|
+
*
|
|
54
|
+
* @param {string} query
|
|
55
|
+
* @param {{channel?:string, limit?:number}} o
|
|
56
|
+
* @returns {{ok:boolean,rows:Array<{id:number,who:string,self:boolean,content:string,at:number,snippet:string}>,error?:string}}
|
|
57
|
+
*/
|
|
58
|
+
search(query,{channel='',limit=12}={}){
|
|
59
|
+
try{
|
|
60
|
+
const db=this.open();
|
|
61
|
+
if(!db)return {ok:false,rows:[],error:'聊天存档还没建起来'};
|
|
62
|
+
// 首次对账:老库的 chat_text 没有对应 fts 行,不补就永远查不到
|
|
63
|
+
if(!this.ftsChecked){
|
|
64
|
+
this.ftsChecked=true;
|
|
65
|
+
const fix=rebuildFts(db);
|
|
66
|
+
if(!fix.ok)this.log('warn',`[fish-soul] 聊天存档检索索引没补全:${fix.reason}`);
|
|
67
|
+
else if(fix.fixed>0)this.log('info',`[fish-soul] 聊天存档检索索引补齐 ${fix.fixed} 行`);
|
|
68
|
+
}
|
|
69
|
+
return searchChatText(db,query,{channel,limit});
|
|
70
|
+
}catch(e){return {ok:false,rows:[],error:e instanceof Error?e.message:String(e)};}
|
|
71
|
+
}
|
|
43
72
|
remove(channel){try{const db=this.open();const changed=db?Number(db.prepare('DELETE FROM chat_text WHERE channel_id=?').run(channel).changes):0;db?.exec('PRAGMA wal_checkpoint(TRUNCATE)');return {ok:true,changed};}catch{return {ok:false,error:'清理聊天存档失败'};}}
|
|
44
73
|
start(){this.prune();this.timer=setInterval(()=>this.prune(),3600000);this.timer.unref?.();}
|
|
45
74
|
stop(){clearInterval(this.timer);try{this.db?.close();}catch{}this.db=null;}
|
package/lib/client.soul.js
CHANGED
|
@@ -87,6 +87,15 @@ window.__ModuleLoader__.load({
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
// ── 人物:关系 / 称呼 / 印象 ──
|
|
90
|
+
/**
|
|
91
|
+
* 旧记忆的标签:区分「记错」和「过时」。
|
|
92
|
+
*
|
|
93
|
+
* 为什么必须分开:这两种在时间线上的含义是相反的 ——
|
|
94
|
+
* 「记错」= 从来没真过(他随口编自己是医生),该从历史真相里排除;
|
|
95
|
+
* 「过时」= 曾经确实是那样(他以前住 A 区),历史查询里应该看得到。
|
|
96
|
+
* 后端 memoryView 给 invalidKind,老库这一列是 NULL,兜底成 superseded。
|
|
97
|
+
*/
|
|
98
|
+
const invalidLabel = (m) => (m.invalidKind === "corrected" ? "记错" : "过时");
|
|
90
99
|
function PersonCard({ ownerId, ui, api, notify, onChanged }) {
|
|
91
100
|
const { h, Row, Group, Input, Select, Area, Button, Tag, Muted, Empty, Item, useConfirm } = ui;
|
|
92
101
|
const [confirm, confirmNode] = useConfirm();
|
|
@@ -170,9 +179,9 @@ window.__ModuleLoader__.load({
|
|
|
170
179
|
} }, "删除这张卡")) : null),
|
|
171
180
|
(data.episodes ?? []).length === 0 ? null : Group({ title: "最近聊过" },
|
|
172
181
|
h("div", { className: "fs-list" }, data.episodes.map((x) => Item({ key: x.id, text: x.content, meta: [h("span", { key: "t" }, fmtDay(x.at))] })))),
|
|
173
|
-
(data.outdated ?? []).length === 0 ? null : Group({ title: "
|
|
182
|
+
(data.outdated ?? []).length === 0 ? null : Group({ title: "记错 / 过时的", aside: Tag(String(data.outdated.length), "outline") },
|
|
174
183
|
h("div", { className: "fs-list" }, data.outdated.map((m) => Item({
|
|
175
|
-
key: m.id, lead: Tag(m
|
|
184
|
+
key: m.id, lead: Tag(invalidLabel(m), "outline"),
|
|
176
185
|
text: m.content, title: `${m.content}\n${m.evidence || m.source}`,
|
|
177
186
|
meta: [Button({ key: "r", variant: "ghost", onClick: () => restore(m.id) }, "恢复")]
|
|
178
187
|
})))), confirmNode) // #82:confirm() 的对话框要挂进这棵树,否则点「删除这张卡」只是 pending 了、界面什么都不出;
|
|
@@ -192,7 +201,7 @@ window.__ModuleLoader__.load({
|
|
|
192
201
|
}
|
|
193
202
|
return Group({ title: "她自己的改掉 / 过时的", aside: Muted(`${data.total} 条`) },
|
|
194
203
|
data.items.length === 0 ? Empty("没有旧记忆") : h("div", { className: "fs-list" }, data.items.map((m) => Item({
|
|
195
|
-
key: m.id, lead: ui.Tag(m
|
|
204
|
+
key: m.id, lead: ui.Tag(invalidLabel(m), "outline"),
|
|
196
205
|
text: m.content, title: `${m.content}\n${m.evidence || m.source}`,
|
|
197
206
|
meta: m.kind === "weekly" ? [Muted("失效周记不能恢复")] : [Button({ key: "r", variant: "ghost", onClick: () => restore(m) }, "恢复")]
|
|
198
207
|
}))),
|
|
@@ -798,7 +807,7 @@ window.__ModuleLoader__.load({
|
|
|
798
807
|
const add = () => { if (term.trim() && meaning.trim()) { edit({ add: { term, meaning } }, "加上了"); setTerm(""); setMeaning(""); } };
|
|
799
808
|
const addWay = () => { if (when.trim() && how.trim()) { edit({ addExpression: { situation: when, style: how } }, "加上了"); setWhen(""); setHow(""); } };
|
|
800
809
|
const ways = g.expressions ?? [];
|
|
801
|
-
return Group({ title: isGlobal ? "
|
|
810
|
+
return Group({ title: isGlobal ? "所有聊天都能用(全局)" : `${isGroup ? "群里的说法" : "私聊学到的"} · ${g.title || g.channelId}`, tip: isGlobal ? "手动加在这里,每个群和私聊都能用" : undefined, aside: isGlobal ? null : h("span", { className: "fs-group-aside" },
|
|
802
811
|
Muted(`${g.learnedAt ? `${relTime(g.learnedAt, Date.now())}学的` : "还没学过"} · 攒了 ${g.lines} 句`),
|
|
803
812
|
Button({ variant: "ghost", disabled: busy, onClick: learn }, busy ? "学习中" : "现在学一次")) },
|
|
804
813
|
isGlobal ? null : Row({ title: "说话风格", desc: g.styleByUser ? "你改过,不会被覆盖" : undefined },
|
package/lib/db.js
CHANGED
|
@@ -230,7 +230,14 @@ const MIGRATIONS = [
|
|
|
230
230
|
// #126:weekly_source_changed 的定义改了(owner_id 不再算「来源变了」)。
|
|
231
231
|
// 触发器是 CREATE TRIGGER IF NOT EXISTS 建的,老库不会自己换定义 —— 先摘掉,
|
|
232
232
|
// 后面建触发器那段按新定义重建(每次启动收敛一次)。
|
|
233
|
-
'DROP TRIGGER IF EXISTS weekly_source_changed'
|
|
233
|
+
'DROP TRIGGER IF EXISTS weekly_source_changed',
|
|
234
|
+
// 记忆失效的两种语义(别再混成一个 outdated):
|
|
235
|
+
// 'superseded' = 曾经是真的,后来事情变了(搬家了、换工作了)——
|
|
236
|
+
// 历史查询里应当看得到「他以前住 A 区」
|
|
237
|
+
// 'corrected' = 从来没真过,是记错 / 别人编的(原文一对就露)——
|
|
238
|
+
// 从历史真相里彻底排除,但行留着(能查到它是怎么错的)
|
|
239
|
+
// 老库一律回填 NULL,读的时候按 status 兜底(outdated 视为 superseded),不猜。
|
|
240
|
+
'ALTER TABLE memory ADD COLUMN invalid_kind TEXT'
|
|
234
241
|
];
|
|
235
242
|
|
|
236
243
|
/**
|
package/lib/gateway-media.js
CHANGED
|
@@ -10,6 +10,7 @@ import { isIdentityKey } from './douyin-conversation.js';
|
|
|
10
10
|
import { adapterOf } from './douyin-adapter.js';
|
|
11
11
|
import { findVideoRefs } from './browse.js';
|
|
12
12
|
import { prepareImage } from './imageconv.js';
|
|
13
|
+
import { stripForSpeech } from './tts-text.js';
|
|
13
14
|
import { sanitizeName, sanitizeUserText } from './channels/onebot.js';
|
|
14
15
|
import { mediaTypeOf, isInside, fetchInboundImage, splitChannelId, service, normalizeRelayId } from './gateway-util.js';
|
|
15
16
|
|
|
@@ -498,7 +499,9 @@ export const mediaMethods = {
|
|
|
498
499
|
keep.push(said);
|
|
499
500
|
continue;
|
|
500
501
|
}
|
|
501
|
-
|
|
502
|
+
// 念之前剥掉表情码(文字路上它有用,语音路上会被念成「方括号比心方括号」)
|
|
503
|
+
const spoken = stripForSpeech(said).text.trim();
|
|
504
|
+
const bytes = spoken !== '' ? await this.voice.synthesize(spoken) : null;
|
|
502
505
|
if (!bytes) {
|
|
503
506
|
this.note('filtered', { channelId: row.channel_id, title: row.title, text: said, reason: `语音没发成(${this.voiceFailReason(said)}),改成打字` });
|
|
504
507
|
keep.push(said);
|
package/lib/gateway.js
CHANGED
|
@@ -36,6 +36,7 @@ import { normalizeMessageEvent, sanitizeName, sanitizeUserText } from './channel
|
|
|
36
36
|
import { applyAttachments, attachmentConfig } from './attachments.js';
|
|
37
37
|
import { parseCollect } from './stickers.js';
|
|
38
38
|
import { UNHEARD } from './voice.js';
|
|
39
|
+
import { stripForSpeech } from './tts-text.js';
|
|
39
40
|
import { saveVoiceFile, voiceIncomingEpoch, audioExt } from './voice-files.js';
|
|
40
41
|
import { typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, isGroupChannelId, service, parseClosing, clampReplyWindow, normalizeRelayId, textOfUserMessage } from './gateway-util.js';
|
|
41
42
|
import { mediaMethods } from './gateway-media.js';
|
|
@@ -53,6 +54,33 @@ export const SOURCE_BILI = 'fish-soul/bili';
|
|
|
53
54
|
export const SOURCE_DOUYIN = 'fish-soul/douyin';
|
|
54
55
|
const OUR_SOURCES = new Set([SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN]);
|
|
55
56
|
|
|
57
|
+
/**
|
|
58
|
+
* 这一轮的结束原因是不是「上下文超限 / 400」。
|
|
59
|
+
*
|
|
60
|
+
* 宿主已经做过分类(dsh-llm 的 CONTEXT_WINDOW_EXCEEDED):provider 回 400 且文案是
|
|
61
|
+
* 「context length exceeded」这一类时,适配器把它归一成这个 code,turn/end 的
|
|
62
|
+
* reason === {kind:"error", error:{code:"CONTEXT_WINDOW_EXCEEDED"}}。
|
|
63
|
+
* 所以判 code,不猜文案 —— 文案各家不一样,也没法穷举。
|
|
64
|
+
*
|
|
65
|
+
* 兜底再看一眼 error.message / error.type:老版本宿主或自建适配器可能只给文案。
|
|
66
|
+
* 宁可少换(继续哑着),也不能把「限额 / 超时」当成超限换掉 —— 换会话 = 语境全丢。
|
|
67
|
+
*
|
|
68
|
+
* @param {object} reason turn/end 的 data.reason
|
|
69
|
+
* @returns {boolean}
|
|
70
|
+
*/
|
|
71
|
+
function isContextOverflowReason(reason) {
|
|
72
|
+
if (reason === null || typeof reason !== 'object') return false;
|
|
73
|
+
if (reason.kind !== 'error') return false;
|
|
74
|
+
const err = reason.error ?? {};
|
|
75
|
+
const code = String(err.code ?? '');
|
|
76
|
+
if (code === 'CONTEXT_WINDOW_EXCEEDED') return true;
|
|
77
|
+
if (code === 'HTTP_400' || code === 'HTTP_413') {
|
|
78
|
+
// 400/413 还得看文案:400 也可能是「参数错」「内容被拒」
|
|
79
|
+
return /context|too\s+(long|large)|maximum.{0,20}(token|length)/i.test(String(err.message ?? '') + ' ' + String(err.type ?? ''));
|
|
80
|
+
}
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
|
|
56
84
|
/** QQ 会话里模型能用的全部工具(宿主 PTC 传输 run_code 不算工具本身,单独放行)。 */
|
|
57
85
|
export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget'];
|
|
58
86
|
/** 跨平台转达:主人在 QQ 私聊里让她去抖音 / B站 私信自己一条。 */
|
|
@@ -77,6 +105,9 @@ const OWN_LIMIT = 500;
|
|
|
77
105
|
/** 戳一戳的冷却表上限(无界 Map 会随「不同人 × 不同群」长期累积)。 */
|
|
78
106
|
const POKE_LIMIT = 500;
|
|
79
107
|
const PROACTIVE_TURN_TIMEOUT_MS = 5 * 60_000;
|
|
108
|
+
// 撞过「上下文超限」的会话 id(这条会话已经灌满了,再接新消息只会撞同一个错)。
|
|
109
|
+
// 存内存 + kv 各一份:内存够快,kv 让重启后也记得(重启前的那条会话恢复回来照样是满的)。
|
|
110
|
+
const OVERFLOW_SESSION_KEY = 'session.overflowed';
|
|
80
111
|
/** 群里没点名的话最多攒多少条 / 多久以内的(被叫到时给她看"刚才在聊什么") */
|
|
81
112
|
const BACKLOG_LIMIT = 12;
|
|
82
113
|
const BACKLOG_MAX_AGE_MS = 15 * 60_000;
|
|
@@ -770,6 +801,17 @@ export class ChatGateway {
|
|
|
770
801
|
this.bound.delete(row.session_id);
|
|
771
802
|
return await this.createSession(owner, row.workspace_path || undefined, mergeFrom);
|
|
772
803
|
}
|
|
804
|
+
if (row !== null && this.overflowedSessions().has(String(row.session_id))) {
|
|
805
|
+
// 这条会话撞过上下文上限(压缩也没救回来):再接新消息只会撞同一个错,
|
|
806
|
+
// 那个聊天会一直不回话。直接换新的 —— 记忆在 soul.db,不受影响,丢的只是这段对话的语境。
|
|
807
|
+
this.log('warn', `[fish-soul] ${row.title || key} 的会话撞过上下文上限,换一条新会话`);
|
|
808
|
+
this.diag?.add('session-overflow-recycle', { sessionId: row.session_id, channelId: key }, 'warn');
|
|
809
|
+
this.note('session', { channelId: key, reason: '上下文满了,换了一条新会话(旧会话不再用)' });
|
|
810
|
+
this.db.prepare("UPDATE chat_session SET status = 'retired' WHERE id = ?").run(row.id);
|
|
811
|
+
this.bound.delete(row.session_id);
|
|
812
|
+
this.forgetOverflow(row.session_id);
|
|
813
|
+
return await this.createSession(owner, row.workspace_path || undefined, mergeFrom);
|
|
814
|
+
}
|
|
773
815
|
if (row !== null) {
|
|
774
816
|
this.bound.set(row.session_id, row);
|
|
775
817
|
// 🔴 DSH 的系统提示里 {{model}} 取自 agent.options.model(建 / 恢复会话时传的 agentOptions)。
|
|
@@ -1525,6 +1567,36 @@ export class ChatGateway {
|
|
|
1525
1567
|
return st;
|
|
1526
1568
|
}
|
|
1527
1569
|
|
|
1570
|
+
/** 撞过上下文上限的会话 id 集合(内存 + kv)。 */
|
|
1571
|
+
overflowedSessions() {
|
|
1572
|
+
this.overflowed ??= null;
|
|
1573
|
+
if (this.overflowed === null) {
|
|
1574
|
+
let saved = [];
|
|
1575
|
+
try { saved = JSON.parse(String(getKv(this.db, OVERFLOW_SESSION_KEY, '[]') ?? '[]')); } catch { saved = []; }
|
|
1576
|
+
this.overflowed = new Set(Array.isArray(saved) ? saved.map(String) : []);
|
|
1577
|
+
}
|
|
1578
|
+
return this.overflowed;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
/** 记下「这条会话上下文满了」(内存 + kv,重启后照样认得)。 */
|
|
1582
|
+
markOverflow(sessionId) {
|
|
1583
|
+
const id = String(sessionId ?? '');
|
|
1584
|
+
if (id === '') return;
|
|
1585
|
+
const set = this.overflowedSessions();
|
|
1586
|
+
set.add(id);
|
|
1587
|
+
// 只留最近 50 条:这是个兜底名单,不该无限长
|
|
1588
|
+
const keep = [...set].slice(-50);
|
|
1589
|
+
this.overflowed = new Set(keep);
|
|
1590
|
+
try { setKv(this.db, OVERFLOW_SESSION_KEY, JSON.stringify(keep)); } catch { /* 写不进去也不影响这一轮 */ }
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
/** 这条会话已经换掉了:从名单里摘掉。 */
|
|
1594
|
+
forgetOverflow(sessionId) {
|
|
1595
|
+
const set = this.overflowedSessions();
|
|
1596
|
+
if (!set.delete(String(sessionId ?? ''))) return;
|
|
1597
|
+
try { setKv(this.db, OVERFLOW_SESSION_KEY, JSON.stringify([...set])); } catch { /* 同上 */ }
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1528
1600
|
/** ctx.on('session/event') 回调。 */
|
|
1529
1601
|
onSessionEvent(session, event) {
|
|
1530
1602
|
const sessionId = String(session?.id ?? '');
|
|
@@ -1620,7 +1692,14 @@ export class ChatGateway {
|
|
|
1620
1692
|
textLen: String(st.text ?? '').length,
|
|
1621
1693
|
inboxIds: st.inboxIds ?? []
|
|
1622
1694
|
}, 'warn');
|
|
1623
|
-
|
|
1695
|
+
// 上下文超限(碰 400 / 上下文满了):宿主压缩没能救回来,这一轮就是失败了。
|
|
1696
|
+
// 把它记成「这条会话不能再用了」,下一条消息进来时换新的 —— 否则那个聊天会永久哑掉。
|
|
1697
|
+
if (isContextOverflowReason(d.reason)) {
|
|
1698
|
+
this.markOverflow(sessionId);
|
|
1699
|
+
this.log('warn', `[fish-soul] 会话 ${sessionId} 上下文超限,下一条消息换新会话`);
|
|
1700
|
+
this.diag?.add('session-overflow', { sessionId, channelId: st.channelId ?? '', code: String(d.reason?.error?.code ?? '') }, 'warn');
|
|
1701
|
+
}
|
|
1702
|
+
if (st.fromUs) this.note('failed', { channelId: st.channelId ?? this.bound.get(sessionId)?.channel_id ?? '', reason: isContextOverflowReason(d.reason) ? '上下文满了(下一条消息会换新会话)' : `这一轮没正常结束(${d.reason?.kind ?? '未知'})` });
|
|
1624
1703
|
// #78:DSH 桌面端打字的轮次不外发,但**要记动态** —— 以前在 DSH 里聊,动态页整片空白。
|
|
1625
1704
|
if (st.dshTyped === true) {
|
|
1626
1705
|
if (completed && st.text && this.bound.get(sessionId)?.channel_id) {
|
|
@@ -1662,7 +1741,8 @@ export class ChatGateway {
|
|
|
1662
1741
|
if (!raw || SILENT_RE.test(raw)) return;
|
|
1663
1742
|
for (const p of raw.split(/\n{2,}/)) {
|
|
1664
1743
|
if (!VOICE_RE.test(p)) continue;
|
|
1665
|
-
|
|
1744
|
+
// 和 QQ 那条同理:念之前剥掉表情码(文字路上它有用,语音路上会被念出来)
|
|
1745
|
+
const plain = stripForSpeech(抠正文图(p.replace(VOICE_RE, '')).净文字).text.trim();
|
|
1666
1746
|
if (!plain || this.getConfig?.()?.voice?.desktopTts !== true || this.getConfig?.()?.voice?.enabled !== true) continue;
|
|
1667
1747
|
const bytes = await this.voice.synthesize(plain);
|
|
1668
1748
|
if (bytes && this.getConfig?.()?.voice?.desktopTts === true && this.getConfig?.()?.voice?.enabled === true) saveVoiceFile('out', bytes);
|
|
@@ -1826,8 +1906,14 @@ export class ChatGateway {
|
|
|
1826
1906
|
for (const [i, p] of paragraphs.entries()) {
|
|
1827
1907
|
if (!VOICE_RE.test(p)) continue;
|
|
1828
1908
|
paragraphs[i] = p.replace(VOICE_RE, '').trim();
|
|
1909
|
+
// 表情码在文字那条路上有意义(抖音单独一段写 [比心] 会发成表情图),
|
|
1910
|
+
// 但语音没有「表情段」,原样念出来就是「方括号比心方括号」。念之前剥掉。
|
|
1911
|
+
const spoken = stripForSpeech(paragraphs[i]);
|
|
1912
|
+
if (spoken.removed.length > 0) {
|
|
1913
|
+
this.note('filtered', { channelId: row.channel_id, title: row.title, text: paragraphs[i], reason: `念之前剥掉了 ${spoken.removed.join('')}` });
|
|
1914
|
+
}
|
|
1829
1915
|
const moodOk = this.moodVoice(profile);
|
|
1830
|
-
const bytes =
|
|
1916
|
+
const bytes = spoken.text !== '' && moodOk ? await this.voice?.synthesize(spoken.text) ?? null : null;
|
|
1831
1917
|
if (bytes) voiced[i] = { type: 'record', data: { file: `base64://${bytes.toString('base64')}` } };
|
|
1832
1918
|
else if (paragraphs[i] !== '') {
|
|
1833
1919
|
this.note('filtered', { channelId: row.channel_id, title: row.title, text: paragraphs[i], reason: `语音没发成(${moodOk ? this.voiceFailReason(paragraphs[i]) : `${profile.mood || profile.tone || '心情'},不想说话`}),改成打字` });
|
package/lib/index.js
CHANGED
|
@@ -1465,6 +1465,38 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
1465
1465
|
}
|
|
1466
1466
|
})), 'dsh-fish-soul: forget');
|
|
1467
1467
|
|
|
1468
|
+
// ── 工具:chat_search(翻原始聊天记录,核对「他到底说没说过」)──
|
|
1469
|
+
// 和 recall 的区别:recall 查的是**她已经总结出来的记忆**(会记错、会被改写),
|
|
1470
|
+
// chat_search 查的是**当时的原文**,是唯一的地面真值。
|
|
1471
|
+
// 典型用法:记不清某句话的上下文、想知道原话怎么说的、怀疑记忆记错了。
|
|
1472
|
+
ctx.effect(() => ctx.tools.register(defineTool({
|
|
1473
|
+
name: 'chat_search',
|
|
1474
|
+
description: '在原始聊天记录里按关键词翻原话(不是总结过的记忆)。核对某人到底说过什么、当时怎么说的时用它。',
|
|
1475
|
+
parameters: objectSchema({
|
|
1476
|
+
query: { type: 'string', required: true, description: '要翻的词(人名、地名、具体的词都行,多个词用空格隔开)' },
|
|
1477
|
+
channel: { type: 'string', description: '不填就查当前会话;填会话 id 查那个会话' },
|
|
1478
|
+
limit: { type: 'number', description: '最多返回几条(默认 8,最多 20)' }
|
|
1479
|
+
}),
|
|
1480
|
+
output: textOutput,
|
|
1481
|
+
async execute(args, toolCtx) {
|
|
1482
|
+
const query = String(args.query ?? '').trim();
|
|
1483
|
+
if (query === '') return '要给个检索词。';
|
|
1484
|
+
// 隐私:默认只查当前说话人所在的会话,不让他随便翻别人跟她的私聊
|
|
1485
|
+
const session = sessionForTool(toolCtx, undefined);
|
|
1486
|
+
const channel = String(args.channel ?? '').trim() || session.channelId || '';
|
|
1487
|
+
const res = chatArchive.search(query, { channel, limit: Math.min(20, Math.max(1, Number(args.limit) || 8)) });
|
|
1488
|
+
if (!res.ok) return `翻了聊天记录但失败了:${res.error ?? '原因不明'}。别据此断定没说过。`;
|
|
1489
|
+
if (res.rows.length === 0) return '聊天记录里没找到对得上的原话(也可能超出保留天数了)。';
|
|
1490
|
+
// 存档里是真实毫秒时间戳,按 UTC+8 显示(和日记/周记同一套时区约定)
|
|
1491
|
+
const when = (ms) => {
|
|
1492
|
+
const t = new Date(ms + 8 * 3600000);
|
|
1493
|
+
const p2 = (n) => String(n).padStart(2, '0');
|
|
1494
|
+
return `${t.getUTCFullYear()}-${p2(t.getUTCMonth() + 1)}-${p2(t.getUTCDate())} ${p2(t.getUTCHours())}:${p2(t.getUTCMinutes())}`;
|
|
1495
|
+
};
|
|
1496
|
+
return res.rows.map((r) => `[${when(r.at)}] ${r.self ? '我' : r.who || '对方'}:${r.content}`).join('\n');
|
|
1497
|
+
}
|
|
1498
|
+
})), 'dsh-fish-soul: chat_search');
|
|
1499
|
+
|
|
1468
1500
|
// ── 工具:send_elsewhere(主人在 QQ 私聊里让她去抖音 / B站 私信自己一条)──
|
|
1469
1501
|
ctx.effect(() => ctx.tools.register(defineTool({
|
|
1470
1502
|
name: RELAY_TOOL,
|
|
@@ -1514,7 +1546,7 @@ async function startup(ctx, config, { log, gate }) {
|
|
|
1514
1546
|
const session = sessionForTool(toolCtx);
|
|
1515
1547
|
// 发起人:从会话绑定身份反查平台 uid。认不出是谁就不发 —— 白名单比的是 uid,
|
|
1516
1548
|
// 认不出 = 给不了 uid,宁可拒了也不能按昵称猜(昵称可以随便改)。
|
|
1517
|
-
const fromId = relaySenderId(
|
|
1549
|
+
const fromId = relaySenderId(session);
|
|
1518
1550
|
if (fromId === '') return '认不出你是谁(这个会话没绑到认识的人),带不了话。';
|
|
1519
1551
|
const target = parseRelayTarget(args.to, args.platform);
|
|
1520
1552
|
if (target.ok !== true) return target.error;
|
package/lib/life.js
CHANGED
|
@@ -929,8 +929,14 @@ export class LifeEngine {
|
|
|
929
929
|
`{"missedPending":[{"dueInHours":数字,"reason":"..."}],` +
|
|
930
930
|
`"suggestedRelationStage":"stranger|acquaintance|friend|close|null"` +
|
|
931
931
|
(writeProfile ? `,"profileFields":{${PROFILE_FIELDS.map(([k, l]) => `"${k}":"${l}(≤30 字,不知道就空)"`).join(',')}}` : '') +
|
|
932
|
-
',"outdated":[{"id":旧记忆编号,"by":推翻它的新记忆编号,"reason":"..."}]
|
|
933
|
-
'
|
|
932
|
+
',"outdated":[{"id":旧记忆编号,"by":推翻它的新记忆编号,"reason":"..."}],' +
|
|
933
|
+
'"corrected":[{"id":记错的记忆编号,"reason":"原文说的是什么,这条记错在哪"}]}。' +
|
|
934
|
+
// 两种失效必须分开填,别混:
|
|
935
|
+
// outdated = 曾经是真的,后来事情变了(搬家、换工作、分手)⇒ 要填 by(哪条新记忆说明的)。
|
|
936
|
+
// corrected = 从来没真过,是记错了或听信了对方随口编的 ⇒ 不要填 by,
|
|
937
|
+
// reason 里写「原文实际说的是什么」,因为这条会从历史真相里彻底排除。
|
|
938
|
+
'outdated 只填被更新的记忆明确推翻的旧事实(比如搬家、换工作、分手),拿不准就空着;' +
|
|
939
|
+
'corrected 只填和原文明确冲突的(下面给了原文时才有意义),拿不准就空着 —— 宁可漏填,别把真事判成记错。' +
|
|
934
940
|
(profile ? `现在的印象:${profile.text}。` : '') +
|
|
935
941
|
(writeProfile && profile?.lockedFields?.length ? `(${profile.lockedFields.map((k) => PROFILE_FIELDS.find(([f]) => f === k)?.[1] ?? k).join('、')}是主人写的,不用填)` : '') +
|
|
936
942
|
`近期记忆:${recent.map((m) => `#${m.id}[${day(m.created_at)}] ${m.content}`).join(';')}` +
|
|
@@ -950,6 +956,7 @@ export class LifeEngine {
|
|
|
950
956
|
const nowVirtual = this.clock.now();
|
|
951
957
|
const byId = new Map(recent.map((m) => [m.id, m]));
|
|
952
958
|
const outdated = [];
|
|
959
|
+
const corrected = [];
|
|
953
960
|
this.db.exec('BEGIN');
|
|
954
961
|
try {
|
|
955
962
|
// 兜底补写 pending(审查 #02)
|
|
@@ -981,11 +988,23 @@ export class LifeEngine {
|
|
|
981
988
|
const old = byId.get(Number(o?.id));
|
|
982
989
|
const by = byId.get(Number(o?.by));
|
|
983
990
|
if (!old || !by || old.id === by.id || by.created_at < old.created_at || (old.importance ?? 1) >= 5) continue;
|
|
984
|
-
this.db.prepare("UPDATE memory SET status = 'outdated', valid_to = ?, superseded_by = ?, updated_at = ? WHERE id = ? AND status = 'active'")
|
|
991
|
+
this.db.prepare("UPDATE memory SET status = 'outdated', invalid_kind = 'superseded', valid_to = ?, superseded_by = ?, updated_at = ? WHERE id = ? AND status = 'active'")
|
|
985
992
|
.run(nowVirtual, by.id, nowVirtual, old.id);
|
|
986
993
|
this.db.prepare('DELETE FROM vec WHERE memory_id = ?').run(old.id);
|
|
987
994
|
outdated.push({ id: old.id, by: by.id, reason: String(o.reason ?? '').slice(0, 80), content: old.content.slice(0, 80) });
|
|
988
995
|
}
|
|
996
|
+
// 记错的旧记忆(从来没真过):不需要「被谁推翻」,也没有 by。
|
|
997
|
+
// 🔴 和上面那种分开:这条不进历史真相(时间线里不该出现"他以前是医生"),
|
|
998
|
+
// 但行留着 —— 主人能查到它是怎么错的,也能手动恢复。
|
|
999
|
+
for (const o of (Array.isArray(parsed.corrected) ? parsed.corrected : [])) {
|
|
1000
|
+
if (corrected.length >= 3) break;
|
|
1001
|
+
const old = byId.get(Number(o?.id));
|
|
1002
|
+
if (!old || (old.importance ?? 1) >= 5) continue;
|
|
1003
|
+
this.db.prepare("UPDATE memory SET status = 'outdated', invalid_kind = 'corrected', valid_to = ?, updated_at = ? WHERE id = ? AND status = 'active'")
|
|
1004
|
+
.run(nowVirtual, nowVirtual, old.id);
|
|
1005
|
+
this.db.prepare('DELETE FROM vec WHERE memory_id = ?').run(old.id);
|
|
1006
|
+
corrected.push({ id: old.id, reason: String(o.reason ?? '').slice(0, 80), content: old.content.slice(0, 80) });
|
|
1007
|
+
}
|
|
989
1008
|
// relation_stage 演进(审查 #05):Dream 建议 + 互动计数/情绪均值兜底
|
|
990
1009
|
if (person !== undefined) {
|
|
991
1010
|
const stageRank = { stranger: 0, acquaintance: 1, friend: 2, close: 3 };
|
|
@@ -1023,13 +1042,13 @@ export class LifeEngine {
|
|
|
1023
1042
|
try { settleAffinity(this.db, person.canonical_id, 0, nowVirtual); } catch { /* 老库没有列 */ }
|
|
1024
1043
|
try { ensureBirthdayPending(this.db, ownerId, name, nowVirtual); } catch { /* 不要紧 */ }
|
|
1025
1044
|
}
|
|
1026
|
-
if (outdated.length > 0 || (writeProfile && profileText !== '')) {
|
|
1045
|
+
if (outdated.length > 0 || corrected.length > 0 || (writeProfile && profileText !== '')) {
|
|
1027
1046
|
const logs = getKv(this.db, 'dream.log', []) ?? [];
|
|
1028
1047
|
// transcriptLines:这次带了几行原文(0 = 没带)。
|
|
1029
1048
|
// 没有这个数,从外面根本看不出「对照原文」到底生效了没有 ——
|
|
1030
1049
|
// 加了开关却没观测点,是上次表情包那轮踩过的坑。
|
|
1031
1050
|
logs.unshift({
|
|
1032
|
-
at: Date.now(), ownerId, name, outdated,
|
|
1051
|
+
at: Date.now(), ownerId, name, outdated, corrected,
|
|
1033
1052
|
profile: writeProfile && profileText !== '',
|
|
1034
1053
|
transcriptLines: transcriptLines === '' ? 0 : transcriptLines.split('\n').length,
|
|
1035
1054
|
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mood-guard.js —— 情绪状态机的一道闸 + 提示词护栏(PR3)。
|
|
3
|
+
*
|
|
4
|
+
* 借鉴 anima-brain 的 emotion.py(常量 + 公式都在代码里,真读过的):
|
|
5
|
+
* 每轴每天的总绝对位移上限 0.12、档位滞回 0.035 ——
|
|
6
|
+
* 挡的都是「同一个话题反复刷让数值滚雪球」和「卡在档位边界反复横跳」。
|
|
7
|
+
*
|
|
8
|
+
* 我们的 mood 是离散标签 + intensity 1~3 + 12h 半衰,不是 PAD 坐标,
|
|
9
|
+
* 所以两个常数不能直接搬数值,只能搬**结构**:
|
|
10
|
+
*
|
|
11
|
+
* 我们只保留**一条**:每日翻转次数上限 —— 一天最多换 4 次标签。
|
|
12
|
+
* 挡的是「开心→委屈→开心→委屈」这种横跳,不是「情绪变强」。
|
|
13
|
+
*
|
|
14
|
+
* 🔴 为什么没有「按强度滞后」那道:既有契约(smoke-v09)要求
|
|
15
|
+
* 同一个 now 下 开心(满格) → 委屈 必须能翻,而且翻完 markMoodSaid
|
|
16
|
+
* 要重新返回 true。那是「模型判断了就是判断了」,是她的主体性。
|
|
17
|
+
* 第一版按 anima-brain 的强度滞后带写(新强度 > 旧残温 × 1.5),
|
|
18
|
+
* 直接打挂那条契约 —— 而且不是测试过时,是我理解的边界错了。
|
|
19
|
+
*
|
|
20
|
+
* ② 每日翻转次数上限:一天最多换 4 次标签。
|
|
21
|
+
* 挡的是「开心→委屈→开心→委屈」这种横跳,不是「情绪变强」——
|
|
22
|
+
* 同标签叠加(余温加深)是既有契约,不能被这道闸压。
|
|
23
|
+
*
|
|
24
|
+
* 这两道都是**写入侧**的闸,读侧 getMood 不变(衰减照旧)。
|
|
25
|
+
*/
|
|
26
|
+
export const MOOD_FLIPS_PER_DAY = 4;
|
|
27
|
+
|
|
28
|
+
/** UTC+8 的日期串(和日记 / 周记同一套时区约定)。 */
|
|
29
|
+
export function moodDayOf(ms) {
|
|
30
|
+
return new Date(ms + 8 * 3600_000).toISOString().slice(0, 10);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 判「这次还能不能换标签」的第二个闸:**一天最多翻几次**。
|
|
35
|
+
*
|
|
36
|
+
* 🔴 这里不能写成「每日位移上限」。既有契约(smoke-persona)要求
|
|
37
|
+
* 同一种情绪又来会叠加 1 → 3 → 3 —— 那是「余温加深」,是既有设计,
|
|
38
|
+
* 拿位移上限去压它直接打挂那条测试。
|
|
39
|
+
*
|
|
40
|
+
* 真正要挡的是**反复翻转**(开心→委屈→开心→委屈),不是「情绪变强」。
|
|
41
|
+
* 所以闸② 数的是「今天换了几次标签」,不是「涨了几格强度」。
|
|
42
|
+
*
|
|
43
|
+
* @param {{day:string, flips:number}|null} today 当天的翻转记录
|
|
44
|
+
* @param {number} now 当前虚拟时间
|
|
45
|
+
* @returns {{ok:true, day:string, flips:number}|{ok:false, day:string, flips:number, reason:string}}
|
|
46
|
+
*/
|
|
47
|
+
export function canFlipToday(today, now) {
|
|
48
|
+
const day = moodDayOf(now);
|
|
49
|
+
const flips = today?.day === day ? Number(today.flips ?? 0) : 0;
|
|
50
|
+
if (flips >= MOOD_FLIPS_PER_DAY) {
|
|
51
|
+
return { ok: false, day, flips, reason: `今天已经翻过 ${flips} 次了,上限 ${MOOD_FLIPS_PER_DAY}` };
|
|
52
|
+
}
|
|
53
|
+
return { ok: true, day, flips };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 提示词护栏(借鉴 anima-brain 的 emotion.py::note)。
|
|
58
|
+
*
|
|
59
|
+
* 原文:「This is fictional character state, not evidence about the user's feelings.
|
|
60
|
+
* Character mood must never make the response dismissive during user vulnerability.」
|
|
61
|
+
*
|
|
62
|
+
* 为什么我们的提示词里需要它:这个项目踩过 #75 / #76 两次「虚构内容顺着
|
|
63
|
+
* 提示词变假事实」—— 状态注记不写清「这是你自己的状态,不是对方的证据」,
|
|
64
|
+
* 模型就会把「我现在在生气」推成「他惹我生气了」这个事实,而它会进记忆。
|
|
65
|
+
*
|
|
66
|
+
* 第二句对应真实风险:她在生气时收到对方说「我最近不太好」,
|
|
67
|
+
* 绝不能回「我现在心情不好,你先别烦我」。
|
|
68
|
+
*/
|
|
69
|
+
export const MOOD_STATE_GUARD = '(这些只是你自己的状态,不是对方情绪的证据,别据此推断对方;对方在说难受、委屈、撑不住这类脆弱的话时,不许敷衍,也不许拿你自己的心情当理由)';
|
package/lib/routes-soul.js
CHANGED
|
@@ -24,6 +24,10 @@ function memoryView(m) {
|
|
|
24
24
|
id: m.id, ownerId: m.owner_id, channel: m.channel, channelId: m.channel_id, kind: m.kind, content: m.content,
|
|
25
25
|
importance: m.importance, importanceLocked: m.importance_locked === 1, importanceAutoRecalled: m.importance_auto_recalled === 1, emotion: m.emotion, createdAt: m.created_at, sortDate: m.sort_date ?? null, updatedAt: m.updated_at, status: m.status,
|
|
26
26
|
supersededBy: m.superseded_by ?? null, evidence: m.evidence ?? '', source: sourceLabel(m.source_session, m.channel),
|
|
27
|
+
// 失效的两种语义。老库这一列是 NULL(升级前写的行),按 status 兜底:
|
|
28
|
+
// outdated / superseded 都当 superseded —— 那时候还没区分,不替它猜;
|
|
29
|
+
// 只有明确写了 corrected 的才当「从来没真过」。
|
|
30
|
+
invalidKind: m.invalid_kind ?? (m.status === 'outdated' || m.status === 'superseded' ? 'superseded' : null),
|
|
27
31
|
visibility: m.visibility ?? 'normal', about: m.about ?? null
|
|
28
32
|
};
|
|
29
33
|
}
|
package/lib/slang.js
CHANGED
|
@@ -267,27 +267,30 @@ export class SlangLearner {
|
|
|
267
267
|
contextLines(channelId, recentText = '') {
|
|
268
268
|
const cfg = this.getConfig();
|
|
269
269
|
const kind = chatKind(channelId);
|
|
270
|
-
if (!cfg.enabled || kind === null
|
|
271
|
-
|
|
270
|
+
if (!cfg.enabled || kind === null) return [];
|
|
271
|
+
// 「私聊也学」关掉 = 不再从私聊里学新东西。**主人手动加的全局说法不连坐**:
|
|
272
|
+
// 全局的用途就是每个聊天都能用,跟「学不学」是两件事。
|
|
273
|
+
const learnOff = kind === 'private' && cfg.privateChats === false;
|
|
274
|
+
const own = learnOff ? { terms: [], style: '', expressions: [] } : this.data(channelId);
|
|
272
275
|
const g = getKv(this.db, `slang.${GLOBAL_ID}`, null);
|
|
273
|
-
//
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
terms: [...own.terms, ...(g.terms ?? []).filter((t) => !own.terms.some((x) => x.term === t.term))],
|
|
277
|
-
expressions: [...own.expressions, ...(g.expressions ?? []).filter((e) => !own.expressions.some((x) => exprKey(x) === exprKey(e)))]
|
|
278
|
-
};
|
|
276
|
+
// 全局(手动加的 / 导入的)和这个聊天自己学到的分开算:同名以这个聊天的为准
|
|
277
|
+
const globalTerms = (g?.terms ?? []).filter((t) => !own.terms.some((x) => x.term === t.term));
|
|
278
|
+
const globalExpressions = (g?.expressions ?? []).filter((e) => !own.expressions.some((x) => exprKey(x) === exprKey(e)));
|
|
279
279
|
const group = kind === 'group';
|
|
280
280
|
const out = [];
|
|
281
|
-
if (
|
|
282
|
-
if (
|
|
281
|
+
if (own.style) out.push(group ? `[这个群的说话习惯] ${own.style}` : `[TA 平时说话的样子] ${own.style}`);
|
|
282
|
+
if (own.terms.length + globalTerms.length > 0) {
|
|
283
283
|
const t = String(recentText);
|
|
284
|
-
const mentioned =
|
|
285
|
-
const
|
|
286
|
-
const
|
|
284
|
+
const mentioned = [...own.terms, ...globalTerms].filter((x) => t.includes(x.term));
|
|
285
|
+
const ownRest = own.terms.filter((x) => !t.includes(x.term));
|
|
286
|
+
const globalRest = globalTerms.filter((x) => !t.includes(x.term));
|
|
287
|
+
// 全局词排在这个聊天自己的梗前面:以前它拼在后面,本群学满 10 个就被 slice 整个挤掉,
|
|
288
|
+
// 「全局通用」名不副实。主人手动加的东西优先占位。
|
|
289
|
+
const pick = [...mentioned, ...globalRest, ...ownRest].slice(0, 10);
|
|
287
290
|
out.push(`${group ? '[群里的梗' : '[你们之间的梗'}(自然用,别硬套)] ${pick.map((x) => `${x.term}:${x.meaning}`).join(';')}`);
|
|
288
291
|
}
|
|
289
292
|
if (cfg.expressions !== false) {
|
|
290
|
-
const picked = pickExpressions(
|
|
293
|
+
const picked = pickExpressions([...own.expressions, ...globalExpressions], recentText, EXPRESSIONS_PER_TURN, this.random);
|
|
291
294
|
if (picked.length > 0) out.push(`[${group ? '群里' : 'TA '}的说话方式(合适才学一条,和你的性格不搭就别用)] ${picked.map((e) => `当${e.situation}时,${e.style}`).join(';')}`);
|
|
292
295
|
}
|
|
293
296
|
return out;
|
|
@@ -348,12 +351,14 @@ export class SlangLearner {
|
|
|
348
351
|
}
|
|
349
352
|
|
|
350
353
|
state() {
|
|
351
|
-
|
|
354
|
+
// 全局卡无条件列出:以前只有麦麦导入写过 `slang.global` 才出现,
|
|
355
|
+
// 没导入过的用户面板上根本没有这张卡 ⇒ 想手动加一条「所有聊天都能用」的说法没有入口。
|
|
356
|
+
const keys = new Set([GLOBAL_ID, ...this.buffers.keys(),
|
|
352
357
|
...this.db.prepare("SELECT key FROM kv WHERE key LIKE 'slang.%'").all().map((r) => r.key.replace(/^slang\.(lines\.)?/, ''))]);
|
|
353
358
|
return [...keys].filter((c) => chatKind(c) !== null || c === GLOBAL_ID).map((channelId) => {
|
|
354
359
|
if (channelId === GLOBAL_ID) {
|
|
355
360
|
const d = this.data(channelId);
|
|
356
|
-
return { channelId, kind: 'global', title: '
|
|
361
|
+
return { channelId, kind: 'global', title: '所有聊天', style: '', styleByUser: false, terms: d.terms, expressions: [...d.expressions].sort((x, y) => (y.count ?? 1) - (x.count ?? 1)), learnedAt: null, lines: 0, newLines: 0 };
|
|
357
362
|
}
|
|
358
363
|
const d = this.data(channelId);
|
|
359
364
|
const b = this.buffer(channelId);
|
package/lib/soul-memory.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* - 防跑偏:人设要点 + 试探检测。
|
|
10
10
|
*/
|
|
11
11
|
import { growthPromptPart, mergeGrowth } from './growth.js';
|
|
12
|
+
import { canFlipToday } from './mood-guard.js';
|
|
12
13
|
import { getKv, setKv, getProfile, setProfile } from './db.js';
|
|
13
14
|
import { tokenizeForBm25, splitKeywords } from './segment.js';
|
|
14
15
|
import { isSelfCapabilityClaim } from './capability.js';
|
|
@@ -105,11 +106,27 @@ export function setMood(db, ownerId, { label, reason = '', intensity = 2 }, now)
|
|
|
105
106
|
const l = String(label ?? '').trim().slice(0, 8);
|
|
106
107
|
if (l === '' || /^(平静|无|没有|null)$/.test(l)) return null;
|
|
107
108
|
const prev = getKv(db, `mood.${ownerId}`, null);
|
|
108
|
-
// said:这个情绪已经在回复里流露过一次了(换了新情绪才重新算)
|
|
109
|
-
// 同一种情绪又来了:在还剩下的余温上加一点(最多 3);换了情绪就从头算(借鉴 HDS-Interlude 的 Alter:同向加强、反向替换)
|
|
110
109
|
const base = Math.max(1, Math.min(3, Number(intensity) || 2));
|
|
111
|
-
|
|
112
|
-
const
|
|
110
|
+
|
|
111
|
+
const sameLabel = prev?.label === l;
|
|
112
|
+
// 同标签:在剩余余温上加一格(最多 3)。换了标签:从 base 起算。
|
|
113
|
+
const left = sameLabel ? Number(prev.intensity ?? 1) * Math.pow(0.5, Math.max(0, now - Number(prev.at ?? now)) / (12 * 3600_000)) : 0;
|
|
114
|
+
const target = Math.round(Math.min(3, Math.max(base, left + 1)) * 10) / 10;
|
|
115
|
+
|
|
116
|
+
// 闸②:一天最多换几次标签。挡的是反复横跳,不是「情绪变强」——
|
|
117
|
+
// 同标签叠加(余温加深)是既有契约(smoke-persona 1→3→3),这里不碰。
|
|
118
|
+
// 首次设值(prev 为 null)不算翻转 —— 那时候没有旧情绪可翻,
|
|
119
|
+
// 否则「第一天就被自己的额度挡掉一次」。
|
|
120
|
+
if (!sameLabel && prev !== null) {
|
|
121
|
+
const dayKey = `mood.flips.${ownerId}`;
|
|
122
|
+
const today = getKv(db, dayKey, null);
|
|
123
|
+
const gate = canFlipToday(today, now);
|
|
124
|
+
if (!gate.ok) return null;
|
|
125
|
+
setKv(db, dayKey, { day: gate.day, flips: gate.flips + 1 });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// said:这个情绪已经在回复里流露过一次了(换了新情绪才重新算)
|
|
129
|
+
const v = { label: l, reason: String(reason ?? '').trim().slice(0, 60), intensity: target, at: now, said: sameLabel && prev?.said === true };
|
|
113
130
|
setKv(db, `mood.${ownerId}`, v);
|
|
114
131
|
return v;
|
|
115
132
|
}
|
package/lib/tts-text.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tts-text.js —— 念出来之前对文本做的最后一层清洗。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:`deAi` 那套是给**文字**消息用的(剥 Markdown、删括号动作、
|
|
5
|
+
* 去 AI 套话),它刻意**不动表情码** —— 因为表情码在文字那条路上是有意义的
|
|
6
|
+
* (抖音那边单独一段写 `[比心]` 会真的发成表情图)。但语音这条路没有「表情段」,
|
|
7
|
+
* 表情码会被原样念出来,用户听到的是「方括号比心方括号」。
|
|
8
|
+
*
|
|
9
|
+
* 实测(2026-11-19):
|
|
10
|
+
* deAi('我今天好累啊[比心]') → '我今天好累啊[比心]' ← 会念出来
|
|
11
|
+
* deAi('哈哈哈哈[笑死][绝了]') → '哈哈哈哈[笑死][绝了]' ← 会念出来
|
|
12
|
+
*
|
|
13
|
+
* 这跟 MEMORY 里记的那条同族:`[捂脸]` 不在抖音表情面板里 ⇒ 静默退化成文字发出去。
|
|
14
|
+
* 表情码在「文字 / 语音」两条路上处理不一致,是同一个盲区。
|
|
15
|
+
*
|
|
16
|
+
* ⚠️ 只剥**确认为表情码**的方括号,不能见方括号就删:
|
|
17
|
+
* - `[语音]` 是协议标记,调用方在进来之前已经剥了,但这里也认一下(幂等);
|
|
18
|
+
* - `[图片]` `【图片】` 这类占位要删;
|
|
19
|
+
* - 但 `[1]` `[注]` `[参考]` 这种正文里的引用标记**不是表情码**,
|
|
20
|
+
* 无脑删会把正文改坏。所以判据是「1~8 个中日韩字/字母数字,且不是纯数字」。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** 表情码:半角方括号 + 1~8 个字(中日韩/字母/数字),且不是纯数字(那是引用标记)。 */
|
|
24
|
+
const EMOJI_CODE_RE = /\[([\u4e00-\u9fa5A-Za-z0-9]{1,8})\]/g;
|
|
25
|
+
/** 正文占位(这些不是表情,是图/附件的替身),整段删掉。 */
|
|
26
|
+
const PLACEHOLDER_RE = /[\[【](?:图片|图|表情|表情包|动画表情|附件|文件|视频|语音消息|图片消息)[\]】]/g;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 看着像引用 / 脚注 / 正文标记的,不当表情码。
|
|
30
|
+
*
|
|
31
|
+
* 🔴 判据要窄。第一版只排了纯数字,结果 `[注]` 被当成表情码删掉了 ——
|
|
32
|
+
* 而 `[注]` `[略]` `[完]` 这类单字方括号在中文正文里是标记,不是表情。
|
|
33
|
+
* 表情名基本都是两个及以上(比心/笑死/绝了/爱心),单字极少(嗨/麻了…「嗨」是一个字)。
|
|
34
|
+
* 所以:单字只认已知的那几个真表情名,其余单字一律当正文标记留着。
|
|
35
|
+
*/
|
|
36
|
+
const SINGLE_CHAR_EMOJI = new Set(['嗨']);
|
|
37
|
+
const looksLikeCitation = (inner) =>
|
|
38
|
+
/^\d+$/.test(inner) ||
|
|
39
|
+
/^[A-Za-z]{1,2}\d*$/.test(inner) ||
|
|
40
|
+
(inner.length === 1 && !SINGLE_CHAR_EMOJI.has(inner));
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 把文本里会被念出来的表情码 / 占位符剥掉。
|
|
44
|
+
*
|
|
45
|
+
* @param {string} text
|
|
46
|
+
* @returns {{text: string, removed: string[]}} removed 是剥掉了什么(给日志用,别静默)
|
|
47
|
+
*/
|
|
48
|
+
export function stripForSpeech(text) {
|
|
49
|
+
const removed = [];
|
|
50
|
+
let t = String(text ?? '');
|
|
51
|
+
if (t === '') return { text: '', removed };
|
|
52
|
+
|
|
53
|
+
t = t.replace(PLACEHOLDER_RE, (m) => {
|
|
54
|
+
removed.push(m);
|
|
55
|
+
return '';
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
t = t.replace(EMOJI_CODE_RE, (m, inner) => {
|
|
59
|
+
// [语音] 是协议标记(调用方通常已经剥过,这里兜一层)
|
|
60
|
+
if (inner === '语音') { removed.push(m); return ''; }
|
|
61
|
+
if (looksLikeCitation(inner)) return m; // 引用标记留着
|
|
62
|
+
removed.push(m);
|
|
63
|
+
return '';
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// 剥完可能留下多余空格 / 空段,收一下(但别把段落结构压平 —— 调用方按 \n\n 分段)
|
|
67
|
+
t = t.replace(/[ \t]{2,}/g, ' ').replace(/[ \t]+$/gm, '').replace(/^[ \t]+/gm, '');
|
|
68
|
+
t = t.replace(/\n{3,}/g, '\n\n').trim();
|
|
69
|
+
|
|
70
|
+
return { text: t, removed };
|
|
71
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-fish-soul",
|
|
3
|
-
"version": "0.18.
|
|
4
|
-
"description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.18.
|
|
3
|
+
"version": "0.18.12",
|
|
4
|
+
"description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.18.12)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
7
7
|
"files": [
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
}
|
|
65
65
|
},
|
|
66
66
|
"scripts": {
|
|
67
|
-
"test": "node test/douyin-send.mjs && node test/douyin-mechanism.mjs && node test/douyin-route.mjs && node test/douyin-adapter.mjs && node test/douyin-contract.mjs && node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/diag-douyin-running.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-config-route.mjs && node test/share-fallback.mjs && node test/share-quota-refund.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/image-inbound-fail.mjs && node test/group-backlog-images.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/check-secrets.mjs",
|
|
67
|
+
"test": "node test/douyin-send.mjs && node test/douyin-mechanism.mjs && node test/douyin-route.mjs && node test/douyin-adapter.mjs && node test/douyin-contract.mjs && node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-share-card-dedupe.mjs && node test/douyin-share-card-dom.mjs && node test/session-overflow-recycle.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/slang-global.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/diag-douyin-running.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/relay-to-friend.mjs && node test/relay-config-route.mjs && node test/share-fallback.mjs && node test/share-quota-refund.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/memory-recall-recent-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs && node test/qq-mention-only-echo.mjs && node test/bili-panel-pagination.mjs && node test/bili-allowlist.mjs && node test/douyin-master-uid-mismatch.mjs && node test/image-inbound-fail.mjs && node test/group-backlog-images.mjs && node test/check-test-chain.mjs && node test/check-route-guard.mjs && node test/check-client-imports.mjs && node test/chat-archive-fts.mjs && node test/chat-search-tool.mjs && node test/memory-invalidate-kind.mjs && node test/mood-guard.mjs && node test/tts-strip-emoji.mjs && node test/check-secrets.mjs",
|
|
68
68
|
"test:douyin": "node test/parallel.mjs 4 --only douyin",
|
|
69
69
|
"test:fast": "node test/parallel.mjs 4 --skip \"douyin|browser\""
|
|
70
70
|
}
|