dsh-fish-soul 0.19.7 → 0.19.8

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.7**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.8**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
package/lib/behavior.js CHANGED
@@ -598,6 +598,7 @@ export class DiaryWriter {
598
598
  this.log = log ?? (() => {});
599
599
  this.timer = null;
600
600
  this.running = false;
601
+ this.shownTopics = new Set();
601
602
  }
602
603
 
603
604
  start(everyMs = 5 * 60_000) {
@@ -723,6 +724,7 @@ export class DiaryWriter {
723
724
  const dropped = parsedTopics.length - topics.length;
724
725
  if (dropped > 0) this.log('info', `[fish-soul] 日记有 ${dropped} 条想聊的对象认不出是谁,没存`);
725
726
  setKv(this.db, 'diary.topics', { date, at: now, items: topics });
727
+ this.shownTopics.clear();
726
728
  setKv(this.db, 'diary.last', date);
727
729
  this.note?.('diary', { title: '日记', reason: '写了今天的日记', text: diary });
728
730
  if (cfg.qzone && typeof this.qzone === 'function') {
@@ -737,10 +739,24 @@ export class DiaryWriter {
737
739
  }
738
740
 
739
741
  /** 昨晚(36 小时内)日记里想跟这个人聊的。 */
740
- topicsFor(ownerId, now = this.clock.now()) {
742
+ topicsFor(ownerId, now = this.clock.now(), { skipShown = false } = {}) {
741
743
  const t = getKv(this.db, 'diary.topics', null);
742
744
  if (!t || !Array.isArray(t.items) || now - Number(t.at ?? 0) > 36 * 3600_000) return [];
743
- return t.items.filter((x) => x.ownerId === ownerId).map((x) => x.topic);
745
+ const dateKey = String(t.date ?? t.at ?? '');
746
+ return t.items
747
+ .filter((x) => x.ownerId === ownerId)
748
+ .filter((x) => !skipShown || !this.shownTopics.has(`${dateKey}:${ownerId}:${x.topic}`))
749
+ .map((x) => x.topic);
750
+ }
751
+
752
+ /** 标记这个人今日想聊的日记话题已在对话开场带过,避免同一话题每轮重复占位。 */
753
+ markTopicsShown(ownerId, now = this.clock.now()) {
754
+ const t = getKv(this.db, 'diary.topics', null);
755
+ if (!t || !Array.isArray(t.items) || now - Number(t.at ?? 0) > 36 * 3600_000) return;
756
+ const dateKey = String(t.date ?? t.at ?? '');
757
+ for (const x of t.items) {
758
+ if (x.ownerId === ownerId) this.shownTopics.add(`${dateKey}:${ownerId}:${x.topic}`);
759
+ }
744
760
  }
745
761
 
746
762
  entries(n = 7) {
@@ -780,7 +796,7 @@ export function moodStyle(moods, p) {
780
796
  return k && moods[k] ? `你${k === '犯懒' ? '懒洋洋' : k}的时候一般:${moods[k]}` : '';
781
797
  }
782
798
 
783
- export function behaviorLines({ db, getConfig, session, known, tone, now, diary, moods }) {
799
+ export function behaviorLines({ db, getConfig, session, known, tone, now, diary, moods, includeStatic = true, diaryTopics = null }) {
784
800
  const out = [];
785
801
  const cfg = behaviorConfig(getConfig().behavior);
786
802
  const inGroup = session.channel === 'qq-group';
@@ -794,13 +810,13 @@ export function behaviorLines({ db, getConfig, session, known, tone, now, diary,
794
810
  const own = moodStyle(moods, p);
795
811
  if (p.hint) out.push(`[你现在的状态] ${p.hint}——体现在回复的快慢、长短和语气上,别直接说出来。${own ? `${own}。` : ''}${MOOD_STATE_GUARD}`);
796
812
  }
797
- // 去 AI 味:发出去以后再删只能删漏网的,先在提示里压一压(参考 MaiBot 的默认说话风格)
798
- if (cfg.outFilter.enabled && session.channel !== 'dsh') {
813
+ // 去 AI 味:发出去以后再删只能删漏网的,先在提示里压一压(纯静态规则,外层可拆到 section 避免每轮通胀)
814
+ if (includeStatic && cfg.outFilter.enabled && session.channel !== 'dsh') {
799
815
  out.push('[说话方式] 像平时打字聊天:简短、口语,可以省略主语、可以倒装,一次说一两件事;不滥用比喻、不讲大道理、不客套;' +
800
816
  '别用括号或星号写动作神态(比如“(揉了揉眼睛)”),别用破折号、冒号、列点。');
801
817
  }
802
- if (!inGroup && known.length === 1 && diary) {
803
- const topics = diary.topicsFor(known[0].ownerId, now);
818
+ if (!inGroup && known.length === 1 && (Array.isArray(diaryTopics) || diary)) {
819
+ const topics = Array.isArray(diaryTopics) ? diaryTopics : diary.topicsFor(known[0].ownerId, now);
804
820
  if (topics.length > 0) out.push(`[昨晚日记里想跟 ${known[0].displayName} 聊的] ${topics.join(';')}(合适就自然地提,不合适就算了)`);
805
821
  }
806
822
  return out;
@@ -133,6 +133,20 @@ export const sessionMethods = {
133
133
  }
134
134
  },
135
135
 
136
+ /** 按文件名排序的稳定表情包清单(用于放进上下文提示词,避免 >40 张每轮随机重排破坏前缀缓存)。 */
137
+ stableStickers(workspacePath, limit = 24) {
138
+ try {
139
+ const dir = join(workspacePath, '_stickers');
140
+ if (!existsSync(dir)) return [];
141
+ return readdirSync(dir)
142
+ .filter((f) => IMAGE_EXT.has(extname(f).toLowerCase()))
143
+ .sort()
144
+ .slice(0, limit);
145
+ } catch {
146
+ return [];
147
+ }
148
+ },
149
+
136
150
  /** 当前嵌入模型 id(换模型后老的向量就不算数了,得重打)。 */
137
151
  embeddingModel() {
138
152
  try {
@@ -146,8 +160,9 @@ export const sessionMethods = {
146
160
  * 没标签的照旧只给文件名 —— 老记录 / 主人手放的图都走这条降级路,不报错。
147
161
  * @returns {Array<{file: string, tags: string[]}>}
148
162
  */
149
- stickerManifest(workspacePath) {
150
- const files = new Set(this.listStickers(workspacePath));
163
+ stickerManifest(workspacePath, { deterministic = false, limit = 40 } = {}) {
164
+ const raw = deterministic ? this.stableStickers(workspacePath, limit) : this.listStickers(workspacePath);
165
+ const files = new Set(raw);
151
166
  if (files.size === 0) return [];
152
167
  const tagged = new Map();
153
168
  try {
@@ -162,9 +177,10 @@ export const sessionMethods = {
162
177
  * 发图清单(给模型看的):_stickers/ 里的表情包 + (images.sendAny 打开时)工作区里任意图片。
163
178
  * 都是相对工作区根的路径,模型照着写 ![说明](相对路径) 就能发出去。
164
179
  */
165
- listImages(workspacePath) {
180
+ listImages(workspacePath, { deterministic = false, stickerLimit = 24 } = {}) {
166
181
  const ws = String(workspacePath ?? '').trim();
167
- const stickers = this.listStickers(ws).map((f) => ({ rel: `_stickers/${f}`, mtimeMs: fileMtime(join(ws, '_stickers', f)) }));
182
+ const stickerFiles = deterministic ? this.stableStickers(ws, stickerLimit) : this.listStickers(ws);
183
+ const stickers = stickerFiles.map((f) => ({ rel: `_stickers/${f}`, mtimeMs: fileMtime(join(ws, '_stickers', f)) }));
168
184
  const sendAny = this.getConfig?.()?.images?.sendAny === true;
169
185
  if (!sendAny || ws === '') return stickers.map((x) => x.rel);
170
186
  let extra = [];
@@ -228,9 +244,11 @@ export const sessionMethods = {
228
244
  const provider = String(cfg.tools?.web?.provider ?? 'host') || 'host';
229
245
  webTools = provider === 'host' ? [...WEB_TOOLS] : [OWN_WEB_TOOL];
230
246
  }
231
- const omTools = isMaster
247
+ const allowOpenMotion = isMaster && (cfg === null || (cfg.douyin?.enabled === true && cfg.douyin?.video?.enabled === true && (!cfg.douyin?.video?.provider || cfg.douyin.video.provider === 'openmotion')));
248
+ const omTools = allowOpenMotion
232
249
  ? [...new Set([...listNames(tools), ...listNames(agentCtx?.tools)].filter(isOpenMotionTool))]
233
250
  : [];
251
+ const allowSoundRead = this.voiceGuardReady && cfg?.voice?.enabled === true && cfg?.voice?.saveIncoming === true && (channelId === undefined || platformOf(channelId) === 'qq');
234
252
  const candidates = [
235
253
  ...QQ_SESSION_TOOLS,
236
254
  ...(allowMasterTools ? [RELAY_TOOL, ...SCHEDULED_TASK_TOOLS] : []),
@@ -238,7 +256,7 @@ export const sessionMethods = {
238
256
  ...(allowDouyinNote ? [DOUYIN_NOTE_TOOL] : []),
239
257
  ...(allowRelayFriend ? [RELAY_FRIEND_TOOL] : []),
240
258
  ...webTools,
241
- ...(this.voiceGuardReady ? ['sound_read'] : [])
259
+ ...(allowSoundRead ? ['sound_read'] : [])
242
260
  ];
243
261
  const base = candidates.filter((n) =>
244
262
  WEB_TOOLS.includes(n) || typeof tools?.get !== 'function' || has(tools, n) || has(agentCtx?.tools, n));
@@ -261,7 +279,7 @@ export const sessionMethods = {
261
279
  } catch { /* 读不到就少给几个,不影响授权 */ }
262
280
  }
263
281
  const mine = new Set([...CHAT_TOOLS, ...WEB_TOOLS, OWN_WEB_TOOL, 'sound_read', 'run_code']);
264
- return [...new Set(names.filter((n) => typeof n === 'string' && n !== '' && !mine.has(n) && !isOpenMotionTool(n)))];
282
+ return [...new Set(names.filter((n) => typeof n === 'string' && n !== '' && !mine.has(n) && !isOpenMotionTool(n) && !n.startsWith('mcp__')))];
265
283
  },
266
284
 
267
285
  /** 传话配置:熟人托她给另一个人带句话(默认关,白名单按平台 uid 精确匹配)。 */
@@ -302,7 +320,7 @@ export const sessionMethods = {
302
320
  async setupAgent(agentCtx, channelId) {
303
321
  // 人格卡 + 此刻状态只挂在这个 agent 的 scope 上,不注册全局段 —— 宿主自己的会话根本看不到(#41 架构方案)
304
322
  try {
305
- this.agentSections?.(agentCtx);
323
+ this.agentSections?.(agentCtx, channelId);
306
324
  } catch (error) {
307
325
  // 注不上不拦着建会话:宁可她少一张人格卡,也别整个聊天哑掉(人格卡是真身份,但比「不回」轻)
308
326
  this.log('error', `[fish-soul] 人格注入挂不上:${String(error instanceof Error ? error.message : error)}`);
@@ -323,9 +341,11 @@ export const sessionMethods = {
323
341
  const allow = this.allowedTools(agentCtx, channelId);
324
342
  // #169 抖音:档位放开的只是「可见性」,真正放不放由 guard 每轮按身份当场判(见 lib/index.js)。
325
343
  // 这里不判身份 —— 身份证据会变,restrict 是一次性的,判错就收不回来。guard 没装就不放宽。
326
- if (platformOf(channelId) === 'douyin' && this.douyinHostVisible()) {
344
+ const douyinVisible = platformOf(channelId) === 'douyin' && this.douyinHostVisible();
345
+ if (douyinVisible) {
327
346
  for (const name of this.hostToolNames(agentCtx)) if (!allow.includes(name)) allow.push(name);
328
347
  }
348
+ let finalAllow = allow;
329
349
  if (typeof agentCtx?.tools?.restrict === 'function') {
330
350
  try {
331
351
  agentCtx.tools.restrict({ allow });
@@ -334,9 +354,48 @@ export const sessionMethods = {
334
354
  if (trimmed.length === allow.length) throw error;
335
355
  // 宿主要是不认没注册的工具名:去掉联网工具再收窄一次(收不窄就让建会话失败,宁可不回也不放开 shell)
336
356
  this.log('warn', `[fish-soul] 收窄工具失败,去掉联网工具重试:${String(error instanceof Error ? error.message : error)}`);
357
+ finalAllow = trimmed;
337
358
  agentCtx.tools.restrict({ allow: trimmed });
338
359
  }
339
360
  }
361
+ // 受限聊天会话(QQ / B站 / 抖音 memory 模式):过滤宿主全局注入的编码工具说明、MCP 提示段、AGENTS.md、time-context 和 skill-catalog
362
+ if (!douyinVisible && typeof agentCtx?.on === 'function') {
363
+ const allowSet = new Set(finalAllow);
364
+ const stripSections = new Set([
365
+ 'harness:source', 'app:web-surface', 'plan:policy', 'team:policy',
366
+ 'ui:deliverable-file-references', 'context:file-reference',
367
+ 'mcp-resource-servers', 'deployment:persona-prefix', 'deployment:persona-suffix', 'tools:sdk'
368
+ ]);
369
+ const stripPreStep = new Set(['agent-instructions', 'time-context', 'skill-catalog']);
370
+ try {
371
+ agentCtx.on('system-prompt/assemble', async (assembly, _context, next) => {
372
+ const result = await next();
373
+ if (!result || !Array.isArray(result.sections)) return result;
374
+ return {
375
+ ...result,
376
+ sections: result.sections.filter((s) => {
377
+ const name = String(s?.name ?? '');
378
+ if (name === '' || name.startsWith('fish-soul')) return true;
379
+ if (name.startsWith('mcp:') || stripSections.has(name)) return false;
380
+ if (name.startsWith('tool:')) return allowSet.has(name.slice(5));
381
+ return true;
382
+ })
383
+ };
384
+ }, { prepend: true });
385
+ } catch (error) {
386
+ this.log('warn', `[fish-soul] system-prompt/assemble 过滤挂不上:${String(error instanceof Error ? error.message : error)}`);
387
+ }
388
+ try {
389
+ agentCtx.on('agent/pre-step', async (_payload, next) => {
390
+ const decision = await next();
391
+ if (!decision || decision.kind === 'reject' || !Array.isArray(decision.messages)) return decision;
392
+ const filtered = decision.messages.filter((m) => !stripPreStep.has(m?.source?.kind));
393
+ return filtered.length === decision.messages.length ? decision : { ...decision, messages: filtered };
394
+ }, { prepend: true });
395
+ } catch (error) {
396
+ this.log('warn', `[fish-soul] agent/pre-step 过滤挂不上:${String(error instanceof Error ? error.message : error)}`);
397
+ }
398
+ }
340
399
  },
341
400
 
342
401
  /**
@@ -555,6 +614,7 @@ export const sessionMethods = {
555
614
  ...(agentOptions !== undefined ? { agentOptions } : {}),
556
615
  setup: (agentCtx) => this.setupAgent(agentCtx, key)
557
616
  });
617
+ this.onSectionsMounted?.(handle.agent?.id ?? row.session_id, key);
558
618
  this.log('info', `[fish-soul] 已恢复会话 ${row.title || key}`);
559
619
  this.diag?.add('session-resume', { sessionId: row.session_id, channelId: key });
560
620
  const preflight = await this.shouldRotateBeforeModelSwitch(handle.agent, key);
@@ -635,6 +695,7 @@ export const sessionMethods = {
635
695
  ...(agentOptions !== undefined ? { agentOptions } : {}),
636
696
  setup: (agentCtx) => this.setupAgent(agentCtx, chat.channelId)
637
697
  });
698
+ this.onSectionsMounted?.(handle.agent?.id ?? sessionId, chat.channelId);
638
699
  // 换新会话(resetSession)沿用旧标题:chatTitle 依赖人物库的当前状态,
639
700
  // 对方改了昵称 / person 行被合并过,重算出来的题头就变了 —— 用户眼里是
640
701
  // 「我只是换了个新会话,题头怎么变了」(2026-11-23 用户反馈)。
package/lib/gateway.js CHANGED
@@ -103,14 +103,15 @@ export class ChatGateway extends gatewayMixins() {
103
103
  * @param {any} [deps.voice]
104
104
  * @param {any} [deps.stickers]
105
105
  * @param {any} [deps.slang]
106
- * @param {((agentCtx: object) => void)|null} [deps.agentSections] 给单个 agent 挂人格卡 / 瞬态块(index.js 传入 registerAgentSections)
106
+ * @param {((agentCtx: object, channelId?: string) => void)|null} [deps.agentSections] 给单个 agent 挂人格卡 / 瞬态块(index.js 传入 registerAgentSections)
107
+ * @param {((sessionId: string) => void)|null} [deps.onSectionsMounted] setupAgent 成功挂完段后通知外层标记已挂载
107
108
  * @param {any} [deps.groupAdmin]
108
109
  * @param {any} [deps.embedder]
109
110
  * @param {any} [deps.embeddingCfg]
110
111
  * @param {any} [deps.diag]
111
112
  * @param {any} [deps.vision]
112
113
  */
113
- constructor({ ctx, db, clock, getConfig, log, channel, bili = null, browser = null, douyin = null, douyinBrowser = null, canvasConvert = null, soul, voice = null, stickers = null, slang = null, agentSections = null, groupAdmin = null, embedder = null, embeddingCfg = null, diag = null, vision = null }) {
114
+ constructor({ ctx, db, clock, getConfig, log, channel, bili = null, browser = null, douyin = null, douyinBrowser = null, canvasConvert = null, soul, voice = null, stickers = null, slang = null, agentSections = null, onSectionsMounted = null, groupAdmin = null, embedder = null, embeddingCfg = null, diag = null, vision = null }) {
114
115
  super();
115
116
  this.ctx = ctx;
116
117
  this.db = db;
@@ -153,8 +154,9 @@ export class ChatGateway extends gatewayMixins() {
153
154
  this.vision = vision;
154
155
  /** 群管理(入群申请):主人回"/鱼 同意/拒绝"时用它(可能没有) */
155
156
  this.groupAdmin = groupAdmin;
156
- /** 给单个 agent 挂人格卡 / 瞬态块:`(agentCtx) => void`(在 setup 里调,只对那个 agent 生效) */
157
+ /** 给单个 agent 挂人格卡 / 瞬态块:`(agentCtx, channelId) => void`(在 setup 里调,只对那个 agent 生效) */
157
158
  this.agentSections = agentSections;
159
+ this.onSectionsMounted = onSectionsMounted;
158
160
  this.diag = diag;
159
161
  /**
160
162
  * 抖音适配器(PR2):身份解析 / 配置归一 / 认人 / 会话标题。
@@ -10,7 +10,7 @@ export function registerExtraTools(ctx, deps) {
10
10
  embeddingCfg, retrievalCfg, memoryLabel, nearDuplicateSync, tokenizeForBm25,
11
11
  parseRoleIso, sessionForTool, UNKNOWN_OWNER, recall, reinforce,
12
12
  gateway, douyinSocial, getConfig, webConfig, ownSearchReady, runWebSearch, formatSearch,
13
- relaySenderId, parseRelayTarget, log,
13
+ relaySenderId, parseRelayTarget, log, toolWhen = {},
14
14
  RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, DOUYIN_NOTE_TOOL, OWN_WEB_TOOL
15
15
  } = deps;
16
16
 
@@ -19,22 +19,25 @@ export function registerExtraTools(ctx, deps) {
19
19
  render: (_args, value) => [{ type: 'text', text: String(value) }]
20
20
  };
21
21
 
22
+ const reg = (def, label) => {
23
+ const when = toolWhen[def.name];
24
+ return ctx.effect(() => (when ? ctx.tools.register(def, { when }) : ctx.tools.register(def)), label);
25
+ };
26
+
22
27
  // ── 工具:remember / recall / forget ──
23
- ctx.effect(() => ctx.tools.register(defineTool({
28
+ reg(defineTool({
24
29
  name: 'remember',
25
- description: '把用户刚说的事实 / 事件 / 感受写入长期记忆。用户提及未来约定或提醒时,' +
26
- '同时填 dueInMinutes(相对分钟,优先)或 dueAtIso + proactiveReason,会在同一事务内' +
27
- '登记到期主动提醒(pending)。',
30
+ description: '写入长期记忆(fact/event/feeling)。有未来约定或提醒时同填 dueInMinutes(优先)或 dueAtIso + proactiveReason。',
28
31
  parameters: objectSchema({
29
- content: { type: 'string', required: true, description: '要记住的内容(一句完整的话)' },
32
+ content: { type: 'string', required: true, description: '要记住的完整一句话' },
30
33
  kind: { type: 'string', enum: ['fact', 'event', 'feeling'], required: true, description: "'fact' | 'event' | 'feeling'" },
31
- importance: { type: 'number', description: '1..5,>=3 豁免时间衰减' },
34
+ importance: { type: 'number', description: '1..5,>=3 豁免衰减' },
32
35
  emotion: { type: 'number', description: '-2..+2' },
33
- dueInMinutes: { type: 'number', description: '相对当前虚拟时间的分钟数(到期提醒,优先)' },
34
- dueAtIso: { type: 'string', description: '或绝对时间,如 2026-11-02T09:00(按 UTC+8 角色时区理解)' },
35
- proactiveReason: { type: 'string', description: '到期主动开口的理由' },
36
- speaker: { type: 'string', description: '群里多人说话时,这条记忆属于谁(填消息里的署名);私聊不用填' },
37
- private: { type: 'boolean', description: '私聊里说的健康 / 感情 / 家庭 / 钱 / 秘密这类不该在群里提的事填 true' }
36
+ dueInMinutes: { type: 'number', description: '相对当前虚拟时间的分钟数(优先)' },
37
+ dueAtIso: { type: 'string', description: '或绝对时间 YYYY-MM-DDTHH:mm(UTC+8)' },
38
+ proactiveReason: { type: 'string', description: '到期主动提醒理由' },
39
+ speaker: { type: 'string', description: '群里说话人署名,私聊留空' },
40
+ private: { type: 'boolean', description: '私聊里的健康/感情/家庭/钱/秘密填 true' }
38
41
  }),
39
42
  output: textOutput,
40
43
  async execute(args, toolCtx) {
@@ -99,14 +102,14 @@ export function registerExtraTools(ctx, deps) {
99
102
  const tail = dueAt !== null ? `,并登记到期提醒(${new Date(dueAt + 8 * 3600_000).toISOString().slice(0, 16).replace('T', ' ')})` : '';
100
103
  return `${dup !== undefined ? '已经记过了,已刷新' : '已记住'} #${memoryId}${tail}。`;
101
104
  }
102
- })), 'dsh-fish-soul: remember');
105
+ }), 'dsh-fish-soul: remember');
103
106
 
104
- ctx.effect(() => ctx.tools.register(defineTool({
107
+ reg(defineTool({
105
108
  name: 'recall',
106
- description: '按当前对话内容主动检索当前说话人的长期记忆(BM25 + 语义向量 RRF 融合)。',
109
+ description: '主动检索当前说话人的长期记忆(BM25 + 向量融合)。',
107
110
  parameters: objectSchema({
108
111
  query: { type: 'string', required: true, description: '检索词或问题' },
109
- speaker: { type: 'string', description: '群里多人说话时,查谁的记忆(填消息里的署名);私聊不用填' }
112
+ speaker: { type: 'string', description: '群里说话人署名,私聊留空' }
110
113
  }),
111
114
  output: textOutput,
112
115
  async execute(args, toolCtx) {
@@ -133,14 +136,14 @@ export function registerExtraTools(ctx, deps) {
133
136
  reinforce(db, ids, now);
134
137
  return out.join('\n');
135
138
  }
136
- })), 'dsh-fish-soul: recall');
139
+ }), 'dsh-fish-soul: recall');
137
140
 
138
- ctx.effect(() => ctx.tools.register(defineTool({
141
+ reg(defineTool({
139
142
  name: 'forget',
140
- description: '删除当前说话人自己的一条长期记忆(id 来自 remember/recall 输出)。不能删除别人的记忆。',
143
+ description: '按 id 删除当前说话人的长期记忆,不可删他人记忆。',
141
144
  parameters: objectSchema({
142
145
  id: { type: 'number', required: true, description: '记忆 id' },
143
- speaker: { type: 'string', description: '群里多人说话时,是谁要删(填消息里的署名)' }
146
+ speaker: { type: 'string', description: '群里说话人署名' }
144
147
  }),
145
148
  output: textOutput,
146
149
  async execute(args, toolCtx) {
@@ -165,13 +168,12 @@ export function registerExtraTools(ctx, deps) {
165
168
  }
166
169
  return `已删除记忆 #${id}。`;
167
170
  }
168
- })), 'dsh-fish-soul: forget');
171
+ }), 'dsh-fish-soul: forget');
169
172
 
170
173
  // ── 工具:send_elsewhere(主人在 QQ 私聊里让她去抖音 / B站 私信自己一条)──
171
- ctx.effect(() => ctx.tools.register(defineTool({
174
+ reg(defineTool({
172
175
  name: RELAY_TOOL,
173
- description: '在另一个平台(抖音私信 / B站私信)给主人发一条消息。只有主人明确要求(「去抖音给我发」「去B站说一声」这类)时才用,别自己找机会用。' +
174
- '话由你自己写,像平时发私信那样自然,直接写要发出去的那一条。只能在主人的私聊里用。',
176
+ description: '在抖音/B站给主人发私信。仅主人明确要求时在主人私聊里用,直接写要发的原话。',
175
177
  parameters: objectSchema({
176
178
  platform: { type: 'string', enum: ['douyin', 'bili'], required: true, description: "'douyin' | 'bili'" },
177
179
  text: { type: 'string', required: true, description: '要发出去的原话(一段,别加引号)' }
@@ -196,19 +198,16 @@ export function registerExtraTools(ctx, deps) {
196
198
  return `没发成:${msg.slice(0, 120)}。`;
197
199
  }
198
200
  }
199
- })), 'dsh-fish-soul: send_elsewhere');
201
+ }), 'dsh-fish-soul: send_elsewhere');
200
202
 
201
203
  // ── 工具:relay_to_friend(白名单里的人 A 托她给白名单里的 B 带句话;默认关)──
202
- ctx.effect(() => ctx.tools.register(defineTool({
204
+ reg(defineTool({
203
205
  name: RELAY_FRIEND_TOOL,
204
- description: '帮当前说话的人给另一个熟人带一句话(对方会收到「xx 托我带句话:…」)。' +
205
- '只有对方明确要求(「帮我跟 xx 说一声」「带句话给 xx」这类)时才用,别自己找机会用。' +
206
- '收件人必须给平台 uid(QQ 号 / B站 UID / 抖音 uid),昵称会发错人所以不认。' +
207
- '两边都得在主人配的传话白名单里才能用,发不出去会告诉你原因,照实跟对方说,别编。',
206
+ description: '帮白名单里的熟人给另一位白名单熟人带话。仅对方明确要求时用;to 必须填平台 uid(不认昵称);失败时如实告知原因。',
208
207
  parameters: objectSchema({
209
- to: { type: 'string', required: true, description: "收件人的平台 uid。两种写法都收:纯数字 + platform(如 to='12345', platform='qq'),或直接带前缀(如 to='bili:12345')。白名单里怎么写的就照抄" },
210
- platform: { type: 'string', description: "收件人在哪个平台:'qq' | 'bili' | 'douyin'。to 已经带前缀时可以不给;两个都给就以前缀为准。**不认识的平台值会被拒**(不会默认成 QQ,那样可能把话发给另一个人)" },
211
- text: { type: 'string', required: true, description: '要带的那句话(一段,照对方的意思写,别加引号)' }
208
+ to: { type: 'string', required: true, description: "收件人平台 uid,如 to='12345' 配 platform='qq' 或 to='bili:12345'" },
209
+ platform: { type: 'string', description: "平台:'qq' | 'bili' | 'douyin'(to 已带前缀可省略;不认的值会拒)" },
210
+ text: { type: 'string', required: true, description: '要带的那句话(一段,别加引号)' }
212
211
  }),
213
212
  output: textOutput,
214
213
  async execute(args, toolCtx) {
@@ -233,15 +232,14 @@ export function registerExtraTools(ctx, deps) {
233
232
  return `没带成:${msg.slice(0, 120)}。`;
234
233
  }
235
234
  }
236
- })), 'dsh-fish-soul: relay_to_friend');
235
+ }), 'dsh-fish-soul: relay_to_friend');
237
236
 
238
237
  // ── 工具:make_douyin_video(主人在私聊里让她做一条视频并发到抖音)──
239
- ctx.effect(() => ctx.tools.register(defineTool({
238
+ reg(defineTool({
240
239
  name: DOUYIN_VIDEO_TOOL,
241
- description: '按给定或自己想的画面文案生成一条短视频并发到抖音(服务商配成 OpenMotion 时走本地渲染,配成云端服务商时调对应视频模型)。' +
242
- '只有主人明确要求(「做个视频发抖音」「用 OpenMotion 做条视频发出去」这类)时才用,别自己找机会用。只能在主人的私聊里用。',
240
+ description: '生成一条短视频并发到抖音。仅主人在私聊里明确要求时用。',
243
241
  parameters: objectSchema({
244
- text: { type: 'string', description: '视频画面/配文(15~80 字,写视频里在拍什么或画面里的文案;不填就由你自己按此刻心情写一条)' }
242
+ text: { type: 'string', description: '画面/配文(15~80 字;不填按此刻心情自拟)' }
245
243
  }),
246
244
  output: textOutput,
247
245
  async execute(args, toolCtx) {
@@ -269,14 +267,14 @@ export function registerExtraTools(ctx, deps) {
269
267
  return `没发成:${msg.slice(0, 120)}。`;
270
268
  }
271
269
  }
272
- })), 'dsh-fish-soul: make_douyin_video');
270
+ }), 'dsh-fish-soul: make_douyin_video');
273
271
 
274
272
  // ── 工具:make_douyin_note(主人在私聊里让她发一条图文到抖音)──
275
- ctx.effect(() => ctx.tools.register(defineTool({
273
+ reg(defineTool({
276
274
  name: DOUYIN_NOTE_TOOL,
277
- description: '把文字做成卡片并发一条抖音图文。只有主人明确要求(「发条抖音图文」「发一条图文到抖音」这类)时才用,别自己找机会用。只能在主人的私聊里用。',
275
+ description: '把文字做成卡片发一条抖音图文。仅主人在私聊里明确要求时用。',
278
276
  parameters: objectSchema({
279
- text: { type: 'string', description: '图文配文(会印在文字卡片上;不填就按此刻心情写一条)' }
277
+ text: { type: 'string', description: '图文配文(不填按此刻心情自拟)' }
280
278
  }),
281
279
  output: textOutput,
282
280
  async execute(args, toolCtx) {
@@ -302,14 +300,14 @@ export function registerExtraTools(ctx, deps) {
302
300
  return `没发成:${msg.slice(0, 120)}。`;
303
301
  }
304
302
  }
305
- })), 'dsh-fish-soul: make_douyin_note');
303
+ }), 'dsh-fish-soul: make_douyin_note');
306
304
 
307
305
  // ── 工具:fish_search(自己填 key 的搜索服务;只在鱼的聊天会话里能用,开关 / 次数由上面的护栏管)──
308
- ctx.effect(() => ctx.tools.register(defineTool({
306
+ reg(defineTool({
309
307
  name: OWN_WEB_TOOL,
310
- description: '上网搜一下(新闻、比赛、新出的东西、没听过的梗等你不知道或可能过时的事),返回几条标题和摘要。',
308
+ description: '上网查不知道或可能过时的事(新闻/比赛/新梗),返回标题和摘要。',
311
309
  parameters: objectSchema({
312
- query: { type: 'string', required: true, description: '搜索词,简短具体,比如「2026 英雄联盟 全球总决赛 冠军」' }
310
+ query: { type: 'string', required: true, description: '简短具体的搜索词' }
313
311
  }),
314
312
  output: textOutput,
315
313
  async execute(args, toolCtx) {
@@ -324,5 +322,108 @@ export function registerExtraTools(ctx, deps) {
324
322
  return `这次没搜成(${msg.slice(0, 120)}),不知道就直说。`;
325
323
  }
326
324
  }
327
- })), 'dsh-fish-soul: fish_search');
325
+ }), 'dsh-fish-soul: fish_search');
326
+ }
327
+
328
+ /** 构造聊天专有工具(及定时任务工具)的作用域判定函数:非鱼会话(如 DSH 桌面)不挂载定义,省下首轮 schema token。 */
329
+ export function buildChatToolWhen({ getGateway, sessions, getConfig, webConfig, RELAY_TOOL, RELAY_FRIEND_TOOL, DOUYIN_VIDEO_TOOL, DOUYIN_NOTE_TOOL, OWN_WEB_TOOL }) {
330
+ const agentChannelFor = (toolCtx) => {
331
+ const id = String(toolCtx?.agent?.id ?? toolCtx?.scope?.id ?? toolCtx?.sessionId ?? '');
332
+ if (id === '') return '';
333
+ const gw = getGateway();
334
+ return gw?.turns?.get(id)?.channelId ?? sessions.get(id)?.channelId ?? gw?.chatForSession(id)?.channel_id ?? '';
335
+ };
336
+ const isFishChat = (toolCtx) => agentChannelFor(toolCtx) !== '';
337
+ const isMasterChatWhen = (toolCtx) => {
338
+ const chId = agentChannelFor(toolCtx);
339
+ const gw = getGateway();
340
+ return chId !== '' && gw !== null && typeof gw.isMasterChannel === 'function' && gw.isMasterChannel(chId);
341
+ };
342
+ const isMasterPrivateWhen = (toolCtx) => {
343
+ const chId = agentChannelFor(toolCtx);
344
+ const gw = getGateway();
345
+ return chId !== '' && gw !== null && typeof gw.isMasterPrivateChat === 'function' && gw.isMasterPrivateChat(chId);
346
+ };
347
+ const toolWhen = {
348
+ [RELAY_TOOL]: isMasterPrivateWhen,
349
+ [RELAY_FRIEND_TOOL]: (toolCtx) => isFishChat(toolCtx) && getConfig().relay?.enabled === true,
350
+ [DOUYIN_VIDEO_TOOL]: (toolCtx) => isMasterPrivateWhen(toolCtx) && getConfig().douyin?.enabled === true && getConfig().douyin?.video?.enabled === true,
351
+ [DOUYIN_NOTE_TOOL]: (toolCtx) => isMasterPrivateWhen(toolCtx) && getConfig().douyin?.enabled === true && getConfig().douyin?.post?.enabled === true,
352
+ [OWN_WEB_TOOL]: (toolCtx) => isFishChat(toolCtx) && webConfig().enabled === true && webConfig().provider !== 'host'
353
+ };
354
+ return { isMasterChatWhen, toolWhen };
355
+ }
356
+
357
+ /** 兜底工具护栏:即使会话按默认预设恢复或未走 restrict,仍按通道/档位与本轮身份实时鉴权。 */
358
+ export function registerToolGuard(ctx, {
359
+ getGateway, getConfig, platformOf, isAllowedVoiceInput,
360
+ webConfig, webUsedToday, countWebUse, markHostWebSeen,
361
+ CHAT_TOOLS, WEB_TOOLS, OWN_WEB_TOOL, isOpenMotionTool, log
362
+ }) {
363
+ try {
364
+ if (typeof ctx.tools.guard !== 'function') {
365
+ log('warn', '[fish-soul] 宿主没有 tools.guard:QQ 会话的工具限制只靠建会话时的 restrict');
366
+ return;
367
+ }
368
+ const allowed = new Set(CHAT_TOOLS);
369
+ const sessionOpen = (id) => {
370
+ const gw = getGateway();
371
+ const row = gw?.chatForSession(id);
372
+ return row !== null && row !== undefined && gw.sessionOpenFor(row.channel_id) === true;
373
+ };
374
+ const isMasterSession = (id) => {
375
+ const gw = getGateway();
376
+ const row = gw?.chatForSession(id);
377
+ return row !== null && row !== undefined && gw.isMasterChannel(row.channel_id) === true;
378
+ };
379
+ ctx.effect(() => {
380
+ const off = ctx.tools.guard((exec) => {
381
+ const gw = getGateway();
382
+ const cfg = getConfig();
383
+ const id = exec?.agent?.id;
384
+ const activeChannel = gw?.turns?.get(String(id))?.channelId;
385
+ const boundChannel = gw?.chatForSession(String(id))?.channel_id;
386
+ let douyinMaster = false;
387
+ if ((activeChannel && platformOf(activeChannel) === 'douyin') || (boundChannel && platformOf(boundChannel) === 'douyin')) {
388
+ const douyinChannel = activeChannel && platformOf(activeChannel) === 'douyin'
389
+ ? activeChannel
390
+ : boundChannel && platformOf(boundChannel) === 'douyin' ? boundChannel : '';
391
+ const douyinUin = douyinChannel === '' ? '' : String(gw?.douyinUinOf?.({ channelId: douyinChannel }) ?? '');
392
+ const masterUin = String(cfg.masterQqUin ?? '').trim();
393
+ if (douyinUin === '' || masterUin === '' || douyinUin !== masterUin) return '抖音身份尚未验证,暂不开放聊天工具';
394
+ douyinMaster = gw.sessionAllowMode() !== 'memory';
395
+ }
396
+ const ours = id !== undefined && id !== null && gw?.isOurSession(id) === true;
397
+ if (!ours && WEB_TOOLS.includes(exec?.name)) markHostWebSeen();
398
+ if (!ours) return exec?.name === OWN_WEB_TOOL ? `${OWN_WEB_TOOL} 只给鱼的聊天会话用(DSH 自己的会话请用 web_search)` : undefined;
399
+ if (WEB_TOOLS.includes(exec.name) || exec.name === OWN_WEB_TOOL) {
400
+ const w = webConfig();
401
+ if (!w.enabled) return `聊天会话里现在不能上网(设置页「模型」里打开「聊天时可以上网查」)`;
402
+ if (exec.name === OWN_WEB_TOOL && w.provider === 'host') return `现在用的是 DSH 自带的搜索,请用 web_search`;
403
+ if (exec.name !== OWN_WEB_TOOL && w.provider !== 'host') return `现在用的是自己配的搜索服务,请用 ${OWN_WEB_TOOL}`;
404
+ if (webUsedToday() >= w.perDay) return `今天上网查的次数用完了(每天 ${w.perDay} 次)`;
405
+ if (WEB_TOOLS.includes(exec.name)) markHostWebSeen();
406
+ countWebUse(id, exec.name);
407
+ return undefined;
408
+ }
409
+ if (exec.name === 'sound_read' && cfg.voice?.saveIncoming === true && !sessionOpen(id)) {
410
+ const st = gw?.turns?.get(String(id));
411
+ return st?.fromUs === true && st.channelId && platformOf(st.channelId) === 'qq' && cfg.voice?.enabled === true && isAllowedVoiceInput(exec.arguments, st.voicePaths)
412
+ ? undefined : '只能分析当前 QQ 说话人本轮保存的语音,且只允许 input 参数';
413
+ }
414
+ if (exec.name === 'run_code') return `聊天会话里不能运行代码(放开工具也不放 run_code:它能跑任意程序)`;
415
+ if (sessionOpen(id)) return undefined;
416
+ if (douyinMaster && !isOpenMotionTool(exec.name)) return undefined;
417
+ if (isOpenMotionTool(exec.name)) {
418
+ return isMasterSession(id) ? undefined : 'OpenMotion 视频工具只能在主人的私聊里用';
419
+ }
420
+ return allowed.has(exec.name) ? undefined : `聊天会话(QQ / B站 / 抖音)里不能用 ${exec.name}(只开放记忆工具、跨平台转达、熟人传话和上网查;设置页「模型」里可以放开)`;
421
+ });
422
+ const gw = getGateway();
423
+ if (gw) gw.voiceGuardReady = true;
424
+ return () => { const curGw = getGateway(); if (curGw) curGw.voiceGuardReady = false; off?.(); };
425
+ }, 'dsh-fish-soul: qq tool guard');
426
+ } catch (error) {
427
+ log('error', `[fish-soul] 工具护栏挂不上:${String(error instanceof Error ? error.message : error)}`);
428
+ }
328
429
  }