dsh-fish-soul 0.18.11 → 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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.18.11**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.18.12**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -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
- const messageId = seq !== ''
214
- ? `s${seq}`
215
- : hasTime
216
- ? `${print}-${timeMs}-${occ}`
217
- : `${print}-${day}-${occ}`;
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
@@ -807,7 +807,7 @@ window.__ModuleLoader__.load({
807
807
  const add = () => { if (term.trim() && meaning.trim()) { edit({ add: { term, meaning } }, "加上了"); setTerm(""); setMeaning(""); } };
808
808
  const addWay = () => { if (when.trim() && how.trim()) { edit({ addExpression: { situation: when, style: how } }, "加上了"); setWhen(""); setHow(""); } };
809
809
  const ways = g.expressions ?? [];
810
- return Group({ title: isGlobal ? "所有聊天都能用的说法(导入的)" : `${isGroup ? "群里的说法" : "私聊学到的"} · ${g.title || g.channelId}`, tip: isGlobal ? "排在每个聊天自己学的后面" : undefined, aside: isGlobal ? null : h("span", { className: "fs-group-aside" },
810
+ return Group({ title: isGlobal ? "所有聊天都能用(全局)" : `${isGroup ? "群里的说法" : "私聊学到的"} · ${g.title || g.channelId}`, tip: isGlobal ? "手动加在这里,每个群和私聊都能用" : undefined, aside: isGlobal ? null : h("span", { className: "fs-group-aside" },
811
811
  Muted(`${g.learnedAt ? `${relTime(g.learnedAt, Date.now())}学的` : "还没学过"} · 攒了 ${g.lines} 句`),
812
812
  Button({ variant: "ghost", disabled: busy, onClick: learn }, busy ? "学习中" : "现在学一次")) },
813
813
  isGlobal ? null : Row({ title: "说话风格", desc: g.styleByUser ? "你改过,不会被覆盖" : undefined },
@@ -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
- const bytes = await this.voice.synthesize(said);
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
- if (st.fromUs) this.note('failed', { channelId: st.channelId ?? this.bound.get(sessionId)?.channel_id ?? '', reason: `这一轮没正常结束(${d.reason?.kind ?? '未知'})` });
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
- const plain = 抠正文图(p.replace(VOICE_RE, '')).净文字.trim();
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 = paragraphs[i] !== '' && moodOk ? await this.voice?.synthesize(paragraphs[i]) ?? null : null;
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
@@ -1546,7 +1546,7 @@ async function startup(ctx, config, { log, gate }) {
1546
1546
  const session = sessionForTool(toolCtx);
1547
1547
  // 发起人:从会话绑定身份反查平台 uid。认不出是谁就不发 —— 白名单比的是 uid,
1548
1548
  // 认不出 = 给不了 uid,宁可拒了也不能按昵称猜(昵称可以随便改)。
1549
- const fromId = relaySenderId(db, session);
1549
+ const fromId = relaySenderId(session);
1550
1550
  if (fromId === '') return '认不出你是谁(这个会话没绑到认识的人),带不了话。';
1551
1551
  const target = parseRelayTarget(args.to, args.platform);
1552
1552
  if (target.ok !== true) return target.error;
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 || (kind === 'private' && cfg.privateChats === false)) return [];
271
- const own = this.data(channelId);
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 d = !g ? own : {
275
- ...own,
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 (d.style) out.push(group ? `[这个群的说话习惯] ${d.style}` : `[TA 平时说话的样子] ${d.style}`);
282
- if (d.terms.length > 0) {
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 = d.terms.filter((x) => t.includes(x.term));
285
- const rest = d.terms.filter((x) => !t.includes(x.term));
286
- const pick = [...mentioned, ...rest].slice(0, 10);
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(d.expressions, recentText, EXPRESSIONS_PER_TURN, this.random);
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
- const keys = new Set([...this.buffers.keys(),
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: '所有聊天(导入的)', style: '', styleByUser: false, terms: d.terms, expressions: [...d.expressions].sort((x, y) => (y.count ?? 1) - (x.count ?? 1)), learnedAt: null, lines: 0, newLines: 0 };
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);
@@ -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.11",
4
- "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.18.11)",
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/chat-archive-fts.mjs && node test/chat-search-tool.mjs && node test/memory-invalidate-kind.mjs && node test/mood-guard.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
  }