dsh-fish-soul 0.19.5 → 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 +1 -1
- package/lib/browse.js +1 -1
- package/lib/channels/vendor/douyin-bridge/browser.mjs +48 -0
- package/lib/chat-archive-fts.js +86 -9
- package/lib/chat-archive.js +3 -3
- package/lib/client.soul.js +1 -1
- package/lib/config-schema.js +1 -1
- package/lib/db.js +11 -1
- package/lib/douyin-browse.js +1 -1
- package/lib/gateway-dispatch.js +4 -2
- package/lib/gateway-media.js +3 -2
- package/lib/gateway-session.js +31 -5
- package/lib/imageconv.js +23 -0
- package/lib/index-tools.js +14 -2
- package/lib/index.js +56 -39
- package/lib/life.js +12 -4
- package/lib/llm.js +1 -0
- package/lib/retrieval.js +75 -17
- package/lib/routes.js +5 -2
- package/lib/slang.js +4 -0
- package/lib/soul-memory.js +198 -9
- package/lib/sticker-vision.js +3 -2
- package/lib/stickers.js +11 -3
- package/lib/storage.js +9 -4
- package/lib/video-frames.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
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
|
+
}
|
package/lib/chat-archive-fts.js
CHANGED
|
@@ -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.
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
|
50
|
-
|
|
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
|
|
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
|
+
}
|
package/lib/chat-archive.js
CHANGED
|
@@ -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());
|
|
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
|
|
package/lib/client.soul.js
CHANGED
|
@@ -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 ??
|
|
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??"保存失败"); }
|
package/lib/config-schema.js
CHANGED
|
@@ -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(
|
|
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
|
|
package/lib/douyin-browse.js
CHANGED
|
@@ -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 : '';
|
package/lib/gateway-dispatch.js
CHANGED
|
@@ -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',
|
package/lib/gateway-media.js
CHANGED
|
@@ -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
|
|
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) {
|
package/lib/gateway-session.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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'
|
|
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:
|
|
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
|
*
|
package/lib/index-tools.js
CHANGED
|
@@ -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
|
-
|
|
122
|
-
|
|
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
|
|