dsh-fish-soul 0.19.4 → 0.19.6

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.4**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.6**。
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 : '';
@@ -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
+ }
@@ -1401,11 +1401,38 @@ export async function sendEmoji({ browser, name = '', uname = '', expectConvId =
1401
1401
  for (let i = 0; i < 16; i++) {
1402
1402
  await sleep(1000)
1403
1403
  const after = await browser.eval(COUNT_EMOJI).catch(() => [])
1404
- if (hasNewBubble(before, after)) return { ok: true, verified: true, name: picked.name, url: picked.src }
1404
+ if (hasNewBubble(before, after)) {
1405
+ await closeEmojiPanel(browser)
1406
+ return { ok: true, verified: true, name: picked.name, url: picked.src }
1407
+ }
1405
1408
  }
1409
+ await closeEmojiPanel(browser)
1406
1410
  return { ok: false, submitted: true, error: '点了表情,但消息列表里没出现新的表情气泡', name: picked.name }
1407
1411
  }
1408
1412
 
1413
+ /**
1414
+ * 关掉表情面板(发完收尾)。
1415
+ *
1416
+ * 不关的话面板会一直挂在那儿:主人下次进会话看到一个开着的面板,观感很差,
1417
+ * 而且挡着输入区。点一次面板以外的地方即可;面板可能已经自己关了,所以幂等、失败不报。
1418
+ */
1419
+ async function closeEmojiPanel(browser) {
1420
+ try {
1421
+ await browser.eval(`(() => {
1422
+ const panel = document.querySelector('[class*="emojiPanel"]')
1423
+ if (!panel) return 'gone'
1424
+ const r = panel.getBoundingClientRect()
1425
+ const x = Math.round(r.left - 12), y = Math.round(r.top - 12)
1426
+ const el = document.elementFromPoint(Math.max(1, x), Math.max(1, y)) || document.body
1427
+ const o = { bubbles: true, cancelable: true, view: window, clientX: Math.max(1, x), clientY: Math.max(1, y) }
1428
+ el.dispatchEvent(new MouseEvent('mousedown', o))
1429
+ el.dispatchEvent(new MouseEvent('mouseup', o))
1430
+ el.dispatchEvent(new MouseEvent('click', o))
1431
+ return 'clicked'
1432
+ })()`)
1433
+ } catch { /* 关不掉不影响已经发出去的表情 */ }
1434
+ }
1435
+
1409
1436
  /** 登录态检查 */
1410
1437
  export async function checkLogin(browser) {
1411
1438
  const ck = await browser.cookies(['https://www.douyin.com/', 'https://www.douyin.com/user/self'])
@@ -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
 
@@ -80,6 +80,7 @@ window.__ModuleLoader__.load({
80
80
  const [report, setReport] = react.useState(null);
81
81
  const [showShot, setShowShot] = react.useState(false);
82
82
  const [framesPerDay, setFramesPerDay] = react.useState("");
83
+ const [noteText, setNoteText] = react.useState("");
83
84
  react.useEffect(() => { if (framesPerDay === "" && br.framesPerDay !== undefined) setFramesPerDay(String(br.framesPerDay)); }, [br.framesPerDay]);
84
85
  // 待确认的抖音身份(昵称配了但还没主人确认过)。
85
86
  // 放在面板里而不是自动绑定 —— 主人是唯一能看懂 uid 的人。
@@ -276,9 +277,10 @@ window.__ModuleLoader__.load({
276
277
  video.enabled ? Tag(`今天视频 ${so.video?.todayCount ?? 0} / ${video.perDay ?? 1}`, "outline") : null) : null },
277
278
  Row({ title: "自己发图文", desc: "把想说的话做成文字卡片,在创作者中心发图文;创作者中心可能要单独登录一次" },
278
279
  post.enabled ? Button({ disabled: busy || so.post?.running === true || so.video?.running === true || Boolean(so.postPending) || d.enabled !== true || !running, onClick: async () => {
279
- if (await confirm({ title: "现在发一条图文?", description: "将在抖音创作者中心公开发布一条图文动态。", confirmLabel: "发布" })) await act("/douyin/post-now", {}, "发出去了", "没发成");
280
+ if (await confirm({ title: "现在发一条图文?", description: "将在抖音创作者中心公开发布一条图文动态。", confirmLabel: "发布" })) await act("/douyin/post-now", { text: noteText.trim() }, "发出去了", "没发成");
280
281
  } }, so.post?.running ? "正在发…" : "现在发一条") : null,
281
282
  sw("自己发图文", post.enabled === true, (v) => save({ post: { enabled: v } }))),
283
+ post.enabled ? Row({ title: "指定内容", desc: "留空则按她此刻的心情随机写一条" }, Input({ value: noteText, onChange: (e) => setNoteText(e.target.value), placeholder: "想发什么就写在这里", "aria-label": "图文指定内容" })) : null,
282
284
  post.enabled ? Row({ title: "每天最多" }, Num({ min: 0, max: 5, "aria-label": "每天最多几条", ...bind("postPerDay") }), Muted("条")) : null,
283
285
  // 视频:生成要调付费接口(按条计费)—— 开关旁边必须写清楚这是花钱的操作,点击前也要二次确认。
284
286
  Row({ title: "自己发视频", desc: "生成视频要调用付费接口(按条计费),每发一条都真花钱;创作者中心也要先登录过" },
@@ -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
 
@@ -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 : '';
@@ -743,8 +743,10 @@ export class DouyinBrowser {
743
743
  const d = await this.host.exclusive('看分享的抖音', () => this.readDetail({ browser: this.host.browser, id, commentLimit: 3 }), { maxMs: 45_000 });
744
744
  if (!d?.ok) continue;
745
745
  const hot = (d.comments ?? []).slice(0, 2).map((c) => oneLine(c.text ?? c, 60)).filter(Boolean);
746
+ const shot = await this.frameForWatch(d, id);
746
747
  const text = `【抖音视频:${oneLine(d.desc, 120) || '(没有文案)'};作者 ${oneLine(d.author, 20) || '未知'}` +
747
- (hot.length ? `;热评:${hot.join(' / ')}` : '') + '】';
748
+ (hot.length ? `;热评:${hot.join(' / ')}` : '') +
749
+ (shot ? `;画面:${shot}` : '') + '】';
748
750
  this.described.set(id, { text, at: Date.now() });
749
751
  if (this.described.size > 200) this.described.delete(this.described.keys().next().value);
750
752
  notes.push(text);
@@ -760,10 +762,14 @@ export class DouyinBrowser {
760
762
  const d = det.detail;
761
763
  const cm = await this.http.comments(id, { count: 3 });
762
764
  const sum = extractWorkSummary(d, cm.ok ? cm.list : []);
765
+ // 抽帧看画面(默认关,共用"自己刷视频"那个开关与每日配额):
766
+ // 私信里分享的视频也该看得见画面,不能只给文案 + 热评(用户反馈 2026-11-25)。
767
+ const shot = sum.imageCount > 0 ? '' : await this.frameForWatch(d, id);
763
768
  return `【抖音${sum.imageCount > 0 ? '图文' : '视频'}:${oneLine(sum.title, 120) || '(没有文案)'};作者 ${oneLine(sum.author, 20) || '未知'}`
764
769
  + (sum.imageCount > 0 ? `;共 ${sum.imageCount} 张图` : '')
765
770
  + (sum.music ? `;BGM:${oneLine(sum.music, 40)}` : '')
766
771
  + (sum.ocr ? `;画面文字:${oneLine(sum.ocr, 80)}` : '')
772
+ + (shot ? `;画面:${shot}` : '')
767
773
  + (sum.topComments.length ? `;热评:${sum.topComments.join(' / ')}` : '') + '】';
768
774
  }
769
775
  }
@@ -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,17 +7,19 @@ 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
  /** 熟人传话:白名单里的人托她给白名单里的另一个人带句话(默认关)。 */
14
14
  export const RELAY_FRIEND_TOOL = 'relay_to_friend';
15
15
  /** 抖音发视频:主人在私聊里让她做一条视频并发抖音。 */
16
16
  export const DOUYIN_VIDEO_TOOL = 'make_douyin_video';
17
+ /** 抖音发图文:主人在私聊里让她发一条文字卡片。 */
18
+ export const DOUYIN_NOTE_TOOL = 'make_douyin_note';
17
19
  /** 定时任务(#190):AI 只能看和改已经排好的任务 —— 建与删只走设置页。 */
18
20
  export const SCHEDULED_TASK_TOOLS = ['scheduled_tasks_list', 'scheduled_tasks_update'];
19
21
  /** 聊天会话里放行的插件工具(记忆 + 跨平台转达 + 熟人传话 + 抖音发视频 + 定时任务)。 */
20
- export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, ...SCHEDULED_TASK_TOOLS];
22
+ export const CHAT_TOOLS = [...QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, DOUYIN_NOTE_TOOL, ...SCHEDULED_TASK_TOOLS];
21
23
  /** OpenMotion MCP 工具名识别(兼容 mcp__openmotion__* 与 openmotion_*)。 */
22
24
  export function isOpenMotionTool(name) {
23
25
  const s = String(name ?? '');
@@ -210,11 +212,35 @@ export const sessionMethods = {
210
212
  } catch { /* 忽略 */ }
211
213
  return [];
212
214
  };
213
- 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
+ }
214
231
  const omTools = isMaster
215
232
  ? [...new Set([...listNames(tools), ...listNames(agentCtx?.tools)].filter(isOpenMotionTool))]
216
233
  : [];
217
- 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) =>
218
244
  WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n));
219
245
  return [...new Set([...base, ...omTools])];
220
246
  },
@@ -300,13 +326,15 @@ export const sessionMethods = {
300
326
  if (platformOf(channelId) === 'douyin' && this.douyinHostVisible()) {
301
327
  for (const name of this.hostToolNames(agentCtx)) if (!allow.includes(name)) allow.push(name);
302
328
  }
303
- if (typeof agentCtx?.tools?.restrict === 'function' && allow.length > 0) {
329
+ if (typeof agentCtx?.tools?.restrict === 'function') {
304
330
  try {
305
331
  agentCtx.tools.restrict({ allow });
306
332
  } catch (error) {
333
+ const trimmed = allow.filter((n) => !WEB_TOOLS.includes(n));
334
+ if (trimmed.length === allow.length) throw error;
307
335
  // 宿主要是不认没注册的工具名:去掉联网工具再收窄一次(收不窄就让建会话失败,宁可不回也不放开 shell)
308
336
  this.log('warn', `[fish-soul] 收窄工具失败,去掉联网工具重试:${String(error instanceof Error ? error.message : error)}`);
309
- agentCtx.tools.restrict({ allow: allow.filter((n) => !WEB_TOOLS.includes(n)) });
337
+ agentCtx.tools.restrict({ allow: trimmed });
310
338
  }
311
339
  }
312
340
  },
package/lib/gateway.js CHANGED
@@ -38,7 +38,7 @@ import { Outbox, classifySendError } from './outbox.js';
38
38
  import { safeDownload } from './safe-download.js';
39
39
  import { behaviorMethods } from './gateway-behavior.js';
40
40
  import {
41
- sessionMethods, QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL,
41
+ sessionMethods, QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, DOUYIN_NOTE_TOOL,
42
42
  SCHEDULED_TASK_TOOLS, CHAT_TOOLS, isOpenMotionTool, WEB_TOOLS, OWN_WEB_TOOL,
43
43
  IMAGE_EXT, OVERFLOW_SESSION_KEY, SWITCH_BLOCKED_SESSION_KEY, dedicatedWorkspacePath
44
44
  } from './gateway-session.js';
@@ -59,7 +59,7 @@ const normUidKey = (uid) => {
59
59
  export {
60
60
  typingDelayMs, interjectScore, interjectConfig, platformOf, splitChannelId, sessionChannelOf, clampReplyWindow,
61
61
  SOURCE_QQ, SOURCE_PROACTIVE, SOURCE_BILI, SOURCE_DOUYIN,
62
- QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, SCHEDULED_TASK_TOOLS, CHAT_TOOLS,
62
+ QQ_SESSION_TOOLS, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, DOUYIN_NOTE_TOOL, SCHEDULED_TASK_TOOLS, CHAT_TOOLS,
63
63
  isOpenMotionTool, WEB_TOOLS, OWN_WEB_TOOL, dedicatedWorkspacePath
64
64
  };
65
65
 
@@ -408,6 +408,7 @@ export class ChatGateway extends gatewayMixins() {
408
408
  return adapterOf(this).douyinUinBinding(uid);
409
409
  }
410
410
 
411
+
411
412
  bindDouyinUin(uid, qq) {
412
413
  return adapterOf(this).bindDouyinUin(uid, qq);
413
414
  }
@@ -416,6 +417,25 @@ export class ChatGateway extends gatewayMixins() {
416
417
  return adapterOf(this).douyinIdentityOfChannel(channelId);
417
418
  }
418
419
 
420
+ /**
421
+ * 工具授权用的「主人私聊」判定(#220)。
422
+ *
423
+ * 为什么不用 isMasterChannel:它对抖音通道恒 false(channelId 是昵称,不是授权身份),
424
+ * 于是「主人自己的抖音私聊」里发图文/视频永远被误拒。这里把授权拆到平台:
425
+ * · QQ → isMasterChannel(`private:<主人QQ>`,安全);
426
+ * · 抖音 → 这个会话的**真实对端身份** == 主人的抖音身份(`douyin:<uid>`,认 uid 不认昵称);
427
+ * · 其余 → isMasterChannel(B站按 masterUid,群一律 false)。
428
+ */
429
+ isMasterPrivateChat(channelId) {
430
+ if (platformOf(channelId) === 'douyin') {
431
+ const identity = this.douyinIdentityOfChannel(channelId);
432
+ if (identity === '') return false;
433
+ const master = this.masterDouyinIdentity?.() ?? adapterOf(this).masterDouyinIdentity();
434
+ return master !== '' && identity === master;
435
+ }
436
+ return this.isMasterChannel(channelId);
437
+ }
438
+
419
439
  /** 记忆里这个人挂着的 QQ 号(认人用的是真实 ID,改昵称也不丢);没有就返回 ''。 */
420
440
  linkedQqOf(chat) {
421
441
  const [kind, id] = splitChannelId(chat?.channelId);
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
  *