dsh-fish-soul 0.19.5 → 0.19.7

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.19.5**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.7**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
package/lib/browse.js CHANGED
@@ -382,7 +382,7 @@ export class BiliBrowser {
382
382
  `这是 B站 视频《${oneLine(v.title, 40)}》开头的九宫格截图(每格约 6 秒)。` +
383
383
  '用一句不超过 30 字的话,写画面里看到的具体东西:谁在做什么、什么颜色、什么场景。' +
384
384
  '看不清就只写「没看清」。不要分点、不要引号、不要写"这张图"。',
385
- { feature: 'browse', maxTokens: 80, images: [frame] }
385
+ { feature: 'browse', maxTokens: 80, images: [frame], needImages: true }
386
386
  );
387
387
  const t = oneLine(String(text ?? '').replace(/^["“]|["”]$/g, ''), 40);
388
388
  return t && t !== '没看清' ? t : '';
@@ -166,7 +166,7 @@ export function isGroupConversation(msgs, { name = '', groups = [] } = {}) {
166
166
  if (m.fromMe !== true) {
167
167
  // 🔴 只认 ID,**不认昵称**:DOM 路补的媒体消息没有 senderId、只有 senderName,
168
168
  // 拿昵称当「一个人」会把「同一个人 + 他的昵称」数成两个 peer → 单聊被误判成群
169
- // (真机见过:会话「未云」的游标被写成 group: true,从此走群聊路径读,永远读不到)。
169
+ // (真机见过:会话「某人」的游标被写成 group: true,从此走群聊路径读,永远读不到)。
170
170
  const who = String(m.senderId || m.secUid || '');
171
171
  if (who !== '') peers.add(who);
172
172
  }
@@ -684,7 +684,8 @@ export class DouyinChannel {
684
684
  let rows = [];
685
685
  try { rows = this.db.prepare("SELECT key, value FROM kv WHERE key LIKE 'douyin.fails.douyin.conv.%'").all(); } catch { return 0; }
686
686
  for (const row of rows) {
687
- if (!(Number(row.value) > 0)) continue;
687
+ const failCount = Number(row.value);
688
+ if (!(failCount > 0)) continue;
688
689
  const key = row.key.slice('douyin.fails.'.length);
689
690
  let hasCursor = false;
690
691
  let retryAt = 0;
@@ -693,6 +694,13 @@ export class DouyinChannel {
693
694
  retryAt = Number(getKv(this.db, `douyin.retry.${key}`, 0) ?? 0) || 0;
694
695
  } catch { hasCursor = true; }
695
696
  const touched = Math.max(retryAt, this.lastReadAt(key));
697
+ // 🔴 「永远读不出来的死会话」不该算作「活着的失败」:
698
+ // 重试机制在 fails >= FAIL_HARD_AFTER 后就自己停了(needsVerify 的
699
+ // `fails < FAIL_HARD_AFTER` 上限),面板上还显示「N 个会话上次读取失败,
700
+ // 等待重试」是骗人 —— 它根本不会再重试了。
701
+ // 判据:失败次数已顶到上限 **且仍无游标**(从没读成功过)。
702
+ // kv 保留不删:排查「这个会话为什么没消息」时还查得到。
703
+ if (!hasCursor && failCount >= FAIL_HARD_AFTER) continue;
696
704
  if (!hasCursor && touched > 0 && now - touched > ORPHAN_FAIL_TTL_MS) {
697
705
  try {
698
706
  this.db.prepare('DELETE FROM kv WHERE key IN (?, ?, ?)')
@@ -1127,7 +1135,7 @@ export class DouyinChannel {
1127
1135
  const groups = this.groupNames();
1128
1136
  // 当前会话 ID 是单聊形状(0:1:)时,旧游标里的 group 标记不算数。
1129
1137
  // 那个标记是之前某轮误判写进去的,沿用下去会让单聊永远走群聊路径
1130
- // (2026-11-11 真机:未云的 convId 是 0:1:...,游标却是 group:true,
1138
+ // (2026-11-11 真机:某人的 convId 是 0:1:...,游标却是 group:true,
1131
1139
  // 私信被当成群消息入库)。
1132
1140
  const singleNow = isSingleConversation(convId);
1133
1141
  const group = singleNow ? false : (st?.group === true || isGroupConversation(msgs, { name, groups }));
@@ -1368,7 +1376,7 @@ export class DouyinChannel {
1368
1376
  * 进别的会话,还把会话列表滚到那儿(抖音的会话列表是虚拟滚动的,
1369
1377
  * 眼下只有几个会话在 DOM 里)。下一段再进目标会话就点不到了 ——
1370
1378
  * enterChat 抛「找不到会话「X」」,整条回复被判「回复没发出去(发送失败)」
1371
- * (真机 2026-11-12:未云那条和 Re. 那条的发送窗口撞在一起)。
1379
+ * (真机 2026-11-12:两个会话的发送窗口撞在一起)。
1372
1380
  *
1373
1381
  * 锁是 FIFO 的:轮询排在整条发送**之后**,发送中途就插不进来了。
1374
1382
  * ⚠️ 这里不能再套一层 exclusive(自己抢自己的锁会死锁)。
@@ -32,6 +32,12 @@ const LAUNCH_FLAGS = [
32
32
  '--no-first-run',
33
33
  '--no-default-browser-check',
34
34
  '--window-size=1400,1000',
35
+ '--disk-cache-size=67108864',
36
+ '--media-cache-size=33554432',
37
+ '--disable-component-update',
38
+ '--disable-background-networking',
39
+ '--disable-sync',
40
+ '--disable-default-apps',
35
41
  ]
36
42
 
37
43
  const BROWSER_CANDIDATES = {
@@ -300,6 +306,7 @@ export class Browser {
300
306
  // 只有确认没有浏览器占着这个 profile,才敢删锁文件
301
307
  // (删早了 ⇒ 新开的浏览器不再认得老实例 ⇒ 两个浏览器抢同一个 profile)
302
308
  cleanLocks(this.userDataDir)
309
+ cleanProfileCache(this.userDataDir)
303
310
 
304
311
  mkdirSync(this.userDataDir, { recursive: true })
305
312
 
@@ -914,3 +921,44 @@ export function cleanLocks(dir) {
914
921
  }
915
922
  } catch { /* 没有 / 坏了的 Preferences 都不挡启动 */ }
916
923
  }
924
+
925
+ const DISPOSABLE_DEFAULT_CACHE_DIRS = [
926
+ 'Cache',
927
+ 'Code Cache',
928
+ 'GPUCache',
929
+ join('Service Worker', 'CacheStorage'),
930
+ join('Service Worker', 'ScriptCache'),
931
+ ]
932
+
933
+ const DISPOSABLE_ROOT_CACHE_DIRS = [
934
+ 'GrShaderCache',
935
+ 'GraphiteDawnCache',
936
+ 'ShaderCache',
937
+ 'BrowserMetrics',
938
+ 'component_crx_cache',
939
+ 'optimization_guide_model_store',
940
+ 'segmentation_platform',
941
+ 'WasmTtsEngine',
942
+ 'Edge Entity Extraction',
943
+ ]
944
+
945
+ /**
946
+ * 启动前清理可重建的浏览器 HTTP/脚本/着色器/组件缓存目录,保留登录态与站点存储。
947
+ * 必须在确认无存活同 profile 进程后调用;任一条失败静默跳过,不挡启动。
948
+ */
949
+ export function cleanProfileCache(dir) {
950
+ if (!dir) return
951
+ for (const sub of DISPOSABLE_DEFAULT_CACHE_DIRS) {
952
+ try { rmSync(join(dir, 'Default', sub), { recursive: true, force: true }) } catch { /* 忽略 */ }
953
+ }
954
+ for (const sub of DISPOSABLE_ROOT_CACHE_DIRS) {
955
+ try { rmSync(join(dir, sub), { recursive: true, force: true }) } catch { /* 忽略 */ }
956
+ }
957
+ try {
958
+ for (const f of readdirSync(dir)) {
959
+ if (/^BrowserMetrics.*\.pma$/i.test(f)) {
960
+ try { rmSync(join(dir, f), { force: true }) } catch { /* 忽略 */ }
961
+ }
962
+ }
963
+ } catch { /* 目录不存在 */ }
964
+ }
@@ -21,17 +21,53 @@
21
21
  */
22
22
  import { tokenizeForBm25, queryForBm25 } from './segment.js';
23
23
 
24
+ function realignMisalignedFts(db) {
25
+ const misaligned = db.prepare('SELECT rowid, id, terms FROM chat_fts WHERE rowid != id').all();
26
+ if (misaligned.length === 0) return 0;
27
+ const hasChatText = db.prepare('SELECT 1 FROM chat_text WHERE id = ?');
28
+ const hasAligned = db.prepare('SELECT 1 FROM chat_fts WHERE rowid = ? AND id = ?');
29
+ const del = db.prepare('DELETE FROM chat_fts WHERE rowid = ?');
30
+ const ins = db.prepare('INSERT INTO chat_fts(rowid, id, terms) VALUES(?,?,?)');
31
+ let fixed = 0;
32
+ for (const r of misaligned) { del.run(Number(r.rowid)); fixed++; }
33
+ const seen = new Set();
34
+ for (const r of misaligned) {
35
+ const id = Number(r.id);
36
+ if (!Number.isSafeInteger(id) || seen.has(id)) continue;
37
+ seen.add(id);
38
+ if (hasChatText.get(id) && !hasAligned.get(id, id)) {
39
+ ins.run(id, id, String(r.terms ?? ''));
40
+ }
41
+ }
42
+ return fixed;
43
+ }
44
+
24
45
  /** 建 fts 表 + DELETE 联动触发器。INSERT 侧分词必须在应用层做(触发器里调不了 JS 分词)。 */
25
46
  export function ensureFts(db) {
26
47
  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`);
48
+ const trg = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'chat_fts_ad'").get();
49
+ if (!trg || /WHERE\s+id\s*=\s*old\.id/i.test(String(trg.sql ?? ''))) {
50
+ if (db.prepare('SELECT 1 FROM chat_fts WHERE rowid != id LIMIT 1').get()) {
51
+ db.exec('BEGIN');
52
+ try {
53
+ realignMisalignedFts(db);
54
+ db.exec('COMMIT');
55
+ } catch (e) {
56
+ try { db.exec('ROLLBACK'); } catch { /* 忽略 */ }
57
+ throw e;
58
+ }
59
+ }
60
+ db.exec('DROP TRIGGER IF EXISTS chat_fts_ad');
61
+ db.exec(`CREATE TRIGGER chat_fts_ad AFTER DELETE ON chat_text BEGIN
62
+ DELETE FROM chat_fts WHERE rowid = old.id;
63
+ END`);
64
+ }
30
65
  }
31
66
 
32
67
  /** 写入一行索引。add() 插完 chat_text 后调,rowid 与 chat_text.id 对齐。 */
33
68
  export function indexRow(db, id, content) {
34
- db.prepare('INSERT INTO chat_fts(id, terms) VALUES(?,?)').run(Number(id), tokenizeForBm25(String(content ?? '')));
69
+ const n = Number(id);
70
+ db.prepare('INSERT INTO chat_fts(rowid, id, terms) VALUES(?,?,?)').run(n, n, tokenizeForBm25(String(content ?? '')));
35
71
  }
36
72
 
37
73
  /**
@@ -43,15 +79,16 @@ export function rebuildFts(db) {
43
79
  if (count > 50_000) return { ok: false, skipped: true, reason: '存档太大,跳过重建', fixed: 0 };
44
80
  db.exec('BEGIN');
45
81
  try {
46
- let fixed = 0;
82
+ let fixed = realignMisalignedFts(db);
47
83
  // 缺的补: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 ?? '')));
84
+ const ins = db.prepare('INSERT INTO chat_fts(rowid, id, terms) VALUES(?,?,?)');
85
+ for (const r of db.prepare('SELECT id, content FROM chat_text WHERE id NOT IN (SELECT rowid FROM chat_fts)').all()) {
86
+ const id = Number(r.id);
87
+ ins.run(id, id, tokenizeForBm25(String(r.content ?? '')));
51
88
  fixed++;
52
89
  }
53
90
  // 多的删: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);
91
+ fixed += Number(db.prepare('DELETE FROM chat_fts WHERE rowid NOT IN (SELECT id FROM chat_text)').run().changes ?? 0);
55
92
  db.exec('COMMIT');
56
93
  return { ok: true, fixed };
57
94
  } catch (e) {
@@ -90,3 +127,43 @@ export function searchChatText(db, query, { channel = '', limit = 12 } = {}) {
90
127
  return { ok: false, rows: [], error: e instanceof Error ? e.message : String(e) };
91
128
  }
92
129
  }
130
+
131
+ /**
132
+ * 格式化 chat_search 返回的原话列表,按单条与总量上限截断,防止单次检索撑爆上下文。
133
+ *
134
+ * @param {Array<{who?:string,self?:boolean,content?:string,at:number,snippet?:string}>} rows
135
+ * @param {{maxRowChars?:number, maxTotalChars?:number}} [opts]
136
+ */
137
+ export function formatChatSearchRows(rows, { maxRowChars = 240, maxTotalChars = 3000 } = {}) {
138
+ // 存档里是真实毫秒时间戳,按 UTC+8 显示(和日记/周记同一套时区约定)
139
+ const when = (ms) => {
140
+ const t = new Date(ms + 8 * 3600000);
141
+ const p2 = (n) => String(n).padStart(2, '0');
142
+ return `${t.getUTCFullYear()}-${p2(t.getUTCMonth() + 1)}-${p2(t.getUTCDate())} ${p2(t.getUTCHours())}:${p2(t.getUTCMinutes())}`;
143
+ };
144
+ const out = [];
145
+ let totalChars = 0;
146
+ for (const r of rows) {
147
+ const content = String(r.content ?? '');
148
+ const snippet = String(r.snippet ?? '');
149
+ const body = content.length <= maxRowChars
150
+ ? content
151
+ : snippet !== ''
152
+ ? (snippet.length > maxRowChars ? `${snippet.slice(0, maxRowChars)}…` : snippet)
153
+ : `${content.slice(0, maxRowChars)}…`;
154
+ const line = `[${when(r.at)}] ${r.self ? '我' : r.who || '对方'}:${body}`;
155
+ if (out.length === 0) {
156
+ const first = line.length > maxTotalChars ? `${line.slice(0, maxTotalChars)}…` : line;
157
+ out.push(first);
158
+ totalChars = first.length;
159
+ if (totalChars >= maxTotalChars) break;
160
+ continue;
161
+ }
162
+ if (totalChars + 1 + line.length > maxTotalChars) break;
163
+ out.push(line);
164
+ totalChars += 1 + line.length;
165
+ }
166
+ const omitted = rows.length - out.length;
167
+ if (omitted > 0) out.push(`(还有 ${omitted} 条已省略,可缩小关键词或调小 limit)`);
168
+ return out.join('\n');
169
+ }
@@ -8,11 +8,11 @@ const DAY=86400000;
8
8
  export class ChatArchive {
9
9
  constructor({getConfig,log=()=>{}}){this.getConfig=getConfig;this.log=log;this.db=null;this.error='';this.failures=0;this.ftsChecked=false;}
10
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)))};}
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
+ 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); CREATE INDEX IF NOT EXISTS chat_text_at ON chat_text(at);');ensureFts(db);this.db=db;return db;}
12
12
  add(channel,line){const cfg=this.config();if(!cfg.enabled)return;
13
13
  // channels 留空 = 全记(默认);填了才按白名单过滤
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] 聊天存档写入失败,聊天继续');}}
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='聊天存档清理失败';}}
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.exec('BEGIN');try {const res=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());indexRow(db,Number(res.lastInsertRowid),text);db.exec('COMMIT');}catch(e){try{db.exec('ROLLBACK');}catch{}throw e;}this.error='';}catch {this.failures++;this.error='聊天存档写入失败';this.log('warn','[fish-soul] 聊天存档写入失败,聊天继续');}}
15
+ prune(){try{const db=this.open();if(!db)return;const res=db.prepare('DELETE FROM chat_text WHERE at < ?').run(Date.now()-this.config().days*DAY);if(Number(res?.changes??0)>0)db.exec('PRAGMA wal_checkpoint(TRUNCATE)');}catch{this.error='聊天存档清理失败';}}
16
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};}
17
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:'读取聊天存档失败'};}}
18
18
 
@@ -459,7 +459,7 @@ window.__ModuleLoader__.load({
459
459
  const [showAllFiles, setShowAllFiles] = react.useState(false);
460
460
  const [confirm, confirmNode] = useConfirm();
461
461
  react.useEffect(() => { if (chat && form === null) setForm({ enabled: chat.enabled, channels: chat.channels.join(", "), days: chat.days }); }, [chat, form]);
462
- react.useEffect(() => { if (storage && threshold === null) setThreshold({ warnMB: storage.warnMB, freeMB: storage.freeMB, keep: storage.keep ?? 0 }); }, [storage, threshold]);
462
+ react.useEffect(() => { if (storage && threshold === null) setThreshold({ warnMB: storage.warnMB, freeMB: storage.freeMB, keep: storage.keep ?? 10 }); }, [storage, threshold]);
463
463
  if (!storage || !chat || !form || !threshold) return null;
464
464
  const size = (x) => `${(Number(x || 0) / 1048576).toFixed(1)} MB`;
465
465
  async function storageConfig(patch) { const r=await api("POST", "/storage/config", patch); if(r?.ok){await load();notify("已保存");}else notify(r?.error??"保存失败"); }
@@ -122,7 +122,7 @@ export function fishSoulConfigSchema(z) {
122
122
  sessionAllow: z.string().default('memory')
123
123
  }).default({}),
124
124
  onboarding: z.object({ dismissed: z.boolean().default(false) }).default({}),
125
- storage: z.object({ auto: z.boolean().default(true), keep: z.number().default(0), warnMB: z.number().default(1024), freeMB: z.number().default(512) }).default({}),
125
+ storage: z.object({ auto: z.boolean().default(true), keep: z.number().default(10), warnMB: z.number().default(1024), freeMB: z.number().default(512) }).default({}),
126
126
  // 聊天原文存档(本地 SQLite,0600 权限)。
127
127
  // ⚠️ 默认开:它是记忆体系的「原始记录层」—— 睡前整理(Dream)要靠它核对记忆有没有记错
128
128
  // (原来默认关 + 要显式列会话 = 这一层一直是空的,Dream 只能拿结论校验结论)。
package/lib/db.js CHANGED
@@ -275,7 +275,8 @@ const MIGRATIONS = [
275
275
  // 'corrected' = 从来没真过,是记错 / 别人编的(原文一对就露)——
276
276
  // 从历史真相里彻底排除,但行留着(能查到它是怎么错的)
277
277
  // 老库一律回填 NULL,读的时候按 status 兜底(outdated 视为 superseded),不猜。
278
- 'ALTER TABLE memory ADD COLUMN invalid_kind TEXT'
278
+ 'ALTER TABLE memory ADD COLUMN invalid_kind TEXT',
279
+ 'CREATE INDEX IF NOT EXISTS idx_memory_kind_created ON memory(character_id, status, kind, created_at DESC)'
279
280
  ];
280
281
 
281
282
  /**
@@ -351,9 +352,18 @@ export function withoutWeeklyProtect(db, fn) {
351
352
  * try/finally 保证触发器一定重建,哪怕搬的过程抛错。
352
353
  */
353
354
  export function reassignMemoryOwner(db, from, to) {
355
+ if (from === to) return;
354
356
  withoutWeeklyProtect(db, () => {
355
357
  db.prepare('UPDATE memory SET owner_id = ? WHERE owner_id = ?').run(to, from);
358
+ db.prepare('UPDATE memory SET about = ? WHERE about = ?').run(to, from);
356
359
  db.prepare('UPDATE pending SET owner_id = ? WHERE owner_id = ?').run(to, from);
360
+ if (getProfile(db, to) === null) {
361
+ const savedProfile = getKv(db, `profile.${from}`, null);
362
+ if (savedProfile !== null) setKv(db, `profile.${to}`, savedProfile);
363
+ }
364
+ db.prepare('DELETE FROM kv WHERE key IN (?, ?, ?, ?, ?)').run(
365
+ `profile.${from}`, `mood.${from}`, `mood.flips.${from}`, `dream.watermark.${from}`, `dream.watermark.${to}`
366
+ );
357
367
  });
358
368
  }
359
369
 
@@ -512,7 +522,7 @@ export function isMergedNameList(db, raw, excludeId = '') {
512
522
  /**
513
523
  * 清掉「把几个名字拼一起」的脏身份行。
514
524
  *
515
- * 历史上有过 `Re., 未云, 云` 这种值 —— 旧代码把一段对话里的**几个人**
525
+ * 历史上有过 `某某, 某人, 云` 这种值 —— 旧代码把一段对话里的**几个人**
516
526
  * 拼成了一个身份,于是「和 A、B、C 寒暄」被记成了**一个人**的互动:好几个人的
517
527
  * 往来记在一个人头上,就是「人物关系乱」本身。
518
528
  *
@@ -223,7 +223,7 @@ export class DouyinBrowser {
223
223
  `这是抖音视频《${oneLine(String(d?.desc ?? ''), 40)}》开头的九宫格截图(按视频时长均匀取 9 格)。` +
224
224
  '用一句不超过 30 字的话,写画面里看到的具体东西:谁在做什么、什么颜色、什么场景。' +
225
225
  '看不清就只写「没看清」。不要分点、不要引号、不要写"这张图"。',
226
- { feature: 'browse', maxTokens: 80, images: [img] }
226
+ { feature: 'browse', maxTokens: 80, images: [img], needImages: true }
227
227
  );
228
228
  const t = oneLine(String(text ?? '').replace(/^["“]|["”]$/g, ''), 40);
229
229
  return t && t !== '没看清' ? t : '';
@@ -800,8 +800,28 @@ export function douyinSocialDriver(host, timing = {}) {
800
800
  await br.send('Input.insertText', { text }, br.sessionId, tm.evalTimeoutMs);
801
801
  await sleep(1000);
802
802
  // 等图片传完("上传中"没了)
803
- const uploaded = await waitFor(async () => !/上传中|正在上传/.test(String(await br.eval('document.body.innerText', { timeoutMs: tm.evalTimeoutMs }).catch(() => '') ?? '')), { tries: 30, budgetMs: tm.waitBudgetMs });
804
- if (!uploaded) return { ok: false, code: 'UPLOAD_TIMEOUT', error: '图片一直在上传中,没等到上传完成' };
803
+ //
804
+ // 🔴 「读不回来」≠「读到空」(2026-11-27):原来写 `.catch(() => '')`,
805
+ // eval 超时/断连都返回空串 ⇒ `!/上传中/.test('')` 恒真 ⇒ 没读完页面就报上传成功。
806
+ // 页面被验证码 iframe 卡住时正好走这条路。现在把 eval 失败单独拿出来当「不知道」,
807
+ // 继续等;等到预算耗尽仍读不回来 ⇒ UPLOAD_UNKNOWN(不谎报成功)。
808
+ let readFailed = false;
809
+ const uploaded = await waitFor(async () => {
810
+ let body;
811
+ try {
812
+ body = await br.eval('document.body.innerText', { timeoutMs: tm.evalTimeoutMs });
813
+ } catch {
814
+ readFailed = true; // 读不回来:不知道传完没,继续等
815
+ return null;
816
+ }
817
+ readFailed = false;
818
+ return !/上传中|正在上传/.test(String(body ?? '')) ? true : null;
819
+ }, { tries: 30, budgetMs: tm.waitBudgetMs });
820
+ if (!uploaded) {
821
+ return readFailed
822
+ ? { ok: false, code: 'UPLOAD_UNKNOWN', error: '页面读不回来(可能卡住或断连),没法确认图片传完没有' }
823
+ : { ok: false, code: 'UPLOAD_TIMEOUT', error: '图片一直在上传中,没等到上传完成' };
824
+ }
805
825
  return { ok: true };
806
826
  },
807
827
 
@@ -250,7 +250,7 @@ export const dispatchMethods = {
250
250
  const interject = chat.chatType === 'group' && items.every((x) => x.interject === true);
251
251
  const backlog = savedBacklog ?? (chat.chatType === 'group' ? this.takeBacklog(channelId, new Set(items.map(({ m }) => m.messageId))) : { lines: [], images: [] });
252
252
  if (interject) this.interjectTurns.add(agent.id); else this.interjectTurns.delete(agent.id);
253
- this.soul.beginTurn(agent.id, {
253
+ const vecReady = this.soul.beginTurn(agent.id, {
254
254
  channel: sessionChannelOf(channelId),
255
255
  channelId,
256
256
  replyChannel: this.replyChannelFor(agent, channelId),
@@ -304,6 +304,7 @@ export const dispatchMethods = {
304
304
  }
305
305
  const retryEntry = !retried ? { kind: 'dispatch', channelId, items, backlog, inboxIds: route.inboxIds ?? [], dispatched: false } : null;
306
306
  if (retryEntry !== null) this.rememberRetryableTurn(followupId, retryEntry);
307
+ if (vecReady && typeof vecReady.then === 'function') await vecReady;
307
308
  try { await agent.followup({
308
309
  id: followupId,
309
310
  role: 'user',
@@ -421,7 +422,7 @@ export const dispatchMethods = {
421
422
  const person = kind === 'private' ? findPersonByQq(this.db, id) : kind === 'bili' ? findPersonByBili(this.db, id) : kind === 'douyin' ? findPersonByDouyin(this.db, id) : null;
422
423
  this.turnMood ??= new Map();
423
424
  this.turnMood.set(agent.id, this.moodOf(person));
424
- this.soul.beginTurn(agent.id, {
425
+ const vecReady = this.soul.beginTurn(agent.id, {
425
426
  channel: sessionChannelOf(channelId),
426
427
  channelId,
427
428
  replyChannel: this.replyChannelFor(agent, channelId),
@@ -446,6 +447,7 @@ export const dispatchMethods = {
446
447
  : `【主动开口】${this.soul.nowLabel()},你想主动找${kind === 'group' ? '群里的大家' : '对方'}说话。` +
447
448
  `理由:${sanitizeUserText(reason)}。直接写要发出去的那条消息,像平时聊天一样自然,` +
448
449
  '别提"系统""提醒任务""主动开口"这些字眼。';
450
+ if (vecReady && typeof vecReady.then === 'function') await vecReady;
449
451
  await agent.followup({
450
452
  id: msgId,
451
453
  role: 'user',
@@ -9,7 +9,7 @@ import { fishSoulDir, getKv } from './db.js';
9
9
  import { isIdentityKey } from './douyin-conversation.js';
10
10
  import { adapterOf } from './douyin-adapter.js';
11
11
  import { findVideoRefs } from './browse.js';
12
- import { prepareImage } from './imageconv.js';
12
+ import { prepareImage, shrinkInboundImage } from './imageconv.js';
13
13
  import { stripForSpeech } from './tts-text.js';
14
14
  import { sanitizeName, sanitizeUserText } from './channels/onebot.js';
15
15
  import { mediaTypeOf, isInside, fetchInboundImage, splitChannelId, service, normalizeRelayId } from './gateway-util.js';
@@ -391,7 +391,8 @@ export const mediaMethods = {
391
391
  const bytes = r.bytes;
392
392
  const mediaType = mediaTypeOf(bytes);
393
393
  this.stickers?.remember(sessionId, { bytes, mediaType, sticker: img.sticker === true, summary: img.summary, from: m.nickname || m.userId });
394
- const part = { type: 'image', data: bytes.toString('base64'), mediaType, name: `qq-${entry.quoteId || m.messageId || 'x'}-${i + 1}.${mediaType.split('/')[1]}` };
394
+ const shrunk = await shrinkInboundImage(bytes, mediaType);
395
+ const part = { type: 'image', data: shrunk.bytes.toString('base64'), mediaType: shrunk.mediaType, name: `qq-${entry.quoteId || m.messageId || 'x'}-${i + 1}.${shrunk.mediaType.split('/')[1]}` };
395
396
  // 配了识图模型:会话模型没视觉也能"看见" —— 先让视觉模型把这张图说成一段文字,喂文字不喂图。
396
397
  // 只在主人明确配了 models.vision 时才走;没配 = 原样把图塞给会话模型(行为一字不变)。
397
398
  if (describeImage !== null) {
@@ -7,7 +7,7 @@ import { platformOf, splitChannelId, normalizeRelayId, service } from './gateway
7
7
  import { adapterOf } from './douyin-adapter.js';
8
8
 
9
9
  /** QQ 会话里模型能用的全部工具(宿主 PTC 传输 run_code 不算工具本身,单独放行)。 */
10
- export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget'];
10
+ export const QQ_SESSION_TOOLS = ['remember', 'recall', 'forget', 'chat_search'];
11
11
  /** 跨平台转达:主人在 QQ 私聊里让她去抖音 / B站 私信自己一条。 */
12
12
  export const RELAY_TOOL = 'send_elsewhere';
13
13
  /** 熟人传话:白名单里的人托她给白名单里的另一个人带句话(默认关)。 */
@@ -212,11 +212,35 @@ export const sessionMethods = {
212
212
  } catch { /* 忽略 */ }
213
213
  return [];
214
214
  };
215
- const isMaster = channelId !== undefined && typeof this.isMasterChannel === 'function' && this.isMasterChannel(channelId);
215
+ // 🔴 抖音私聊不能用 isMasterChannel(它对 douyin: 恒 false)—— 那会让主人自己的抖音私聊
216
+ // 拿不到 make_douyin_video / make_douyin_note(#220 就是这么坏的)。统一走按平台拆的判定。
217
+ const isMaster = channelId !== undefined && typeof this.isMasterPrivateChat === 'function' && this.isMasterPrivateChat(channelId);
218
+ const cfg = typeof this.getConfig === 'function' ? (this.getConfig() ?? {}) : null;
219
+ const allowMasterTools = channelId === undefined || isMaster;
220
+ // 图文/视频是两个开关(post.enabled / video.enabled),工具各按各的开关放行
221
+ const allowDouyinVideo = allowMasterTools && (cfg === null || (cfg.douyin?.enabled === true && cfg.douyin?.video?.enabled === true));
222
+ const allowDouyinNote = allowMasterTools && (cfg === null || (cfg.douyin?.enabled === true && cfg.douyin?.post?.enabled === true));
223
+ const allowRelayFriend = cfg === null || cfg.relay?.enabled === true;
224
+ let webTools = [];
225
+ if (cfg === null) {
226
+ webTools = [...WEB_TOOLS, OWN_WEB_TOOL];
227
+ } else if (cfg.tools?.web?.enabled === true) {
228
+ const provider = String(cfg.tools?.web?.provider ?? 'host') || 'host';
229
+ webTools = provider === 'host' ? [...WEB_TOOLS] : [OWN_WEB_TOOL];
230
+ }
216
231
  const omTools = isMaster
217
232
  ? [...new Set([...listNames(tools), ...listNames(agentCtx?.tools)].filter(isOpenMotionTool))]
218
233
  : [];
219
- const base = [...CHAT_TOOLS, ...WEB_TOOLS, OWN_WEB_TOOL, ...(this.voiceGuardReady ? ['sound_read'] : [])].filter((n) =>
234
+ const candidates = [
235
+ ...QQ_SESSION_TOOLS,
236
+ ...(allowMasterTools ? [RELAY_TOOL, ...SCHEDULED_TASK_TOOLS] : []),
237
+ ...(allowDouyinVideo ? [DOUYIN_VIDEO_TOOL] : []),
238
+ ...(allowDouyinNote ? [DOUYIN_NOTE_TOOL] : []),
239
+ ...(allowRelayFriend ? [RELAY_FRIEND_TOOL] : []),
240
+ ...webTools,
241
+ ...(this.voiceGuardReady ? ['sound_read'] : [])
242
+ ];
243
+ const base = candidates.filter((n) =>
220
244
  WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n));
221
245
  return [...new Set([...base, ...omTools])];
222
246
  },
@@ -302,13 +326,15 @@ export const sessionMethods = {
302
326
  if (platformOf(channelId) === 'douyin' && this.douyinHostVisible()) {
303
327
  for (const name of this.hostToolNames(agentCtx)) if (!allow.includes(name)) allow.push(name);
304
328
  }
305
- if (typeof agentCtx?.tools?.restrict === 'function' && allow.length > 0) {
329
+ if (typeof agentCtx?.tools?.restrict === 'function') {
306
330
  try {
307
331
  agentCtx.tools.restrict({ allow });
308
332
  } catch (error) {
333
+ const trimmed = allow.filter((n) => !WEB_TOOLS.includes(n));
334
+ if (trimmed.length === allow.length) throw error;
309
335
  // 宿主要是不认没注册的工具名:去掉联网工具再收窄一次(收不窄就让建会话失败,宁可不回也不放开 shell)
310
336
  this.log('warn', `[fish-soul] 收窄工具失败,去掉联网工具重试:${String(error instanceof Error ? error.message : error)}`);
311
- agentCtx.tools.restrict({ allow: allow.filter((n) => !WEB_TOOLS.includes(n)) });
337
+ agentCtx.tools.restrict({ allow: trimmed });
312
338
  }
313
339
  }
314
340
  },
package/lib/imageconv.js CHANGED
@@ -131,6 +131,29 @@ export function sharpReady() {
131
131
  return sharpFn !== null;
132
132
  }
133
133
 
134
+ /**
135
+ * 缩略超宽/过大入站图,降低多模态 token 与重复计费;小图与动图 GIF 原样透传。
136
+ */
137
+ export async function shrinkInboundImage(bytes, mediaType, { maxEdge = 1024, maxBytes = 500 * 1024, quality = 80, sharpOverride = null } = {}) {
138
+ if (!Buffer.isBuffer(bytes) || mediaType === 'image/gif') return { bytes, mediaType };
139
+ const { width, height } = imageSize(bytes);
140
+ if (bytes.length <= maxBytes && width <= maxEdge && height <= maxEdge) return { bytes, mediaType };
141
+ const sharp = sharpOverride ?? await loadSharp();
142
+ if (!sharp) return { bytes, mediaType };
143
+ try {
144
+ const out = await sharp(bytes)
145
+ .rotate()
146
+ .resize({ width: maxEdge, height: maxEdge, fit: 'inside', withoutEnlargement: true })
147
+ .jpeg({ quality })
148
+ .toBuffer();
149
+ return Buffer.isBuffer(out) && out.length > 0 && out.length < bytes.length
150
+ ? { bytes: out, mediaType: 'image/jpeg' }
151
+ : { bytes, mediaType };
152
+ } catch {
153
+ return { bytes, mediaType };
154
+ }
155
+ }
156
+
134
157
  /**
135
158
  * 图片整理:返回能直接发的 {path, bytes, type, width, height};发不了返回 null。
136
159
  *
@@ -118,8 +118,20 @@ export function registerExtraTools(ctx, deps) {
118
118
  });
119
119
  if (memories.length === 0) return '没有检索到相关记忆。';
120
120
  const now = clock.now();
121
- reinforce(db, memories.map((m) => m.id), now);
122
- return memories.map((m) => `#${m.id}${memoryLabel(m, now).slice(1)}`).join('\n');
121
+ const budget = Math.max(400, Number(retrievalCfg().tokenBudget ?? 1200) || 1200);
122
+ const out = [];
123
+ const ids = [];
124
+ let spent = 0;
125
+ for (const m of memories) {
126
+ const line = `#${m.id}${memoryLabel(m, now).slice(1)}`;
127
+ const nextSpent = spent + line.length + (out.length > 0 ? 1 : 0);
128
+ if (out.length > 0 && nextSpent > budget) break;
129
+ out.push(line);
130
+ ids.push(m.id);
131
+ spent = nextSpent;
132
+ }
133
+ reinforce(db, ids, now);
134
+ return out.join('\n');
123
135
  }
124
136
  })), 'dsh-fish-soul: recall');
125
137