@zaofan/dsh-qqbot 1.13.28 → 1.13.36

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.
Files changed (75) hide show
  1. package/client/qqbot-settings.js +280 -11
  2. package/dist/channel-tools.d.ts +35 -1
  3. package/dist/channel-tools.d.ts.map +1 -1
  4. package/dist/channel-tools.js +282 -60
  5. package/dist/channel-tools.js.map +1 -1
  6. package/dist/config.d.ts +66 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +40 -0
  9. package/dist/config.js.map +1 -1
  10. package/dist/features/auto-recall.d.ts.map +1 -1
  11. package/dist/features/auto-recall.js +2 -3
  12. package/dist/features/auto-recall.js.map +1 -1
  13. package/dist/features/ext-tool-interaction.d.ts.map +1 -1
  14. package/dist/features/ext-tool-interaction.js +2 -3
  15. package/dist/features/ext-tool-interaction.js.map +1 -1
  16. package/dist/features/image-aggregate.d.ts +7 -4
  17. package/dist/features/image-aggregate.d.ts.map +1 -1
  18. package/dist/features/image-aggregate.js +46 -19
  19. package/dist/features/image-aggregate.js.map +1 -1
  20. package/dist/features/md-media-rewrite.d.ts.map +1 -1
  21. package/dist/features/md-media-rewrite.js +2 -3
  22. package/dist/features/md-media-rewrite.js.map +1 -1
  23. package/dist/features/msg-history.d.ts +9 -9
  24. package/dist/features/msg-history.d.ts.map +1 -1
  25. package/dist/features/msg-history.js +80 -53
  26. package/dist/features/msg-history.js.map +1 -1
  27. package/dist/gateway/bootstrap.js +2 -2
  28. package/dist/gateway/bootstrap.js.map +1 -1
  29. package/dist/gateway/middleware-setup.js +1 -1
  30. package/dist/gateway/middleware-setup.js.map +1 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +28 -7
  33. package/dist/index.js.map +1 -1
  34. package/dist/middleware/attribution.d.ts +1 -1
  35. package/dist/middleware/attribution.d.ts.map +1 -1
  36. package/dist/middleware/attribution.js +3 -3
  37. package/dist/middleware/attribution.js.map +1 -1
  38. package/dist/model/model-resolver.d.ts +12 -0
  39. package/dist/model/model-resolver.d.ts.map +1 -1
  40. package/dist/model/model-resolver.js +23 -4
  41. package/dist/model/model-resolver.js.map +1 -1
  42. package/dist/model/prefs-store.d.ts +26 -0
  43. package/dist/model/prefs-store.d.ts.map +1 -1
  44. package/dist/model/prefs-store.js +66 -0
  45. package/dist/model/prefs-store.js.map +1 -1
  46. package/dist/model/settings-reader.js +3 -3
  47. package/dist/model/settings-reader.js.map +1 -1
  48. package/dist/model/types.d.ts +9 -0
  49. package/dist/model/types.d.ts.map +1 -1
  50. package/dist/model/types.js +9 -1
  51. package/dist/model/types.js.map +1 -1
  52. package/dist/session/session-manager.d.ts +58 -0
  53. package/dist/session/session-manager.d.ts.map +1 -1
  54. package/dist/session/session-manager.js +247 -50
  55. package/dist/session/session-manager.js.map +1 -1
  56. package/dist/shared/index.d.ts +1 -1
  57. package/dist/shared/index.d.ts.map +1 -1
  58. package/dist/shared/index.js +1 -1
  59. package/dist/shared/index.js.map +1 -1
  60. package/dist/shared/reply-gate-reason.d.ts +34 -0
  61. package/dist/shared/reply-gate-reason.d.ts.map +1 -0
  62. package/dist/shared/reply-gate-reason.js +86 -0
  63. package/dist/shared/reply-gate-reason.js.map +1 -0
  64. package/dist/shared/utils.d.ts +31 -0
  65. package/dist/shared/utils.d.ts.map +1 -1
  66. package/dist/shared/utils.js +54 -1
  67. package/dist/shared/utils.js.map +1 -1
  68. package/dist/transport/inbound.d.ts.map +1 -1
  69. package/dist/transport/inbound.js +35 -29
  70. package/dist/transport/inbound.js.map +1 -1
  71. package/dist/transport/outbound.d.ts +11 -9
  72. package/dist/transport/outbound.d.ts.map +1 -1
  73. package/dist/transport/outbound.js +22 -10
  74. package/dist/transport/outbound.js.map +1 -1
  75. package/package.json +1 -1
@@ -13,8 +13,9 @@ import { uploadMarkdownImage, listMarkdownImages, deleteMarkdownImage } from './
13
13
  import { setMaterialTargetFactory } from './features/md-media-rewrite.js';
14
14
  import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
15
15
  import { join, dirname, resolve } from 'node:path';
16
+ import { dshHomePath } from './shared/utils.js';
17
+ import { isContradictoryReplyFalse } from './shared/reply-gate-reason.js';
16
18
  import { dataRootOf } from './gateway/data-root.js';
17
- import { homedir } from 'node:os';
18
19
  import { getStickerStore } from './features/sticker-store.js';
19
20
  import { autoTagImage } from './features/sticker-tagger.js';
20
21
  import { isStickerGateDenied } from './features/sticker-gate.js';
@@ -381,8 +382,23 @@ let ctxSmartGlobal = false;
381
382
  export function setContextlessSmartGlobal(v) { ctxSmartGlobal = v === true; }
382
383
  function getContextlessSmartGlobal() { return ctxSmartGlobal; }
383
384
  /** 无上下文·智能判断:取当前会话的 dataRoot + sessionKey */
385
+ /**
386
+ * 从工具执行上下文里取**当前会话 id**(取不到返回空串)。
387
+ *
388
+ * 用途:`context_compact` / `context_drop` 只「登记」请求,真正执行在下一回合的 pre-step。
389
+ * 登记时把目标会话 id 一起写进 pending 文件 —— 否则**历史会话**(`/bot-new` 之后,
390
+ * 它的 id 仍能经派生反查映射回同一个 sessionKey)会把这条请求当成自己的,裁掉自己的历史。
391
+ */
392
+ function execSessionId(exec) {
393
+ try {
394
+ const a = exec?.agent;
395
+ return String(a?.session?.id ?? '').trim();
396
+ }
397
+ catch {
398
+ return '';
399
+ }
400
+ }
384
401
  async function resolveCtxMemoEnv(exec) {
385
- // ★ 优先用注册时记住的会话坐标(工具里的 exec.agent 与 pre-step 的 agent 是两个不同对象,反查常失败)
386
402
  // ⚠️ 必须要求 sessionKey 非空:备忘/压缩都按会话分文件存,空 key 会让所有会话串到同一份。
387
403
  const cached = ctxEnvOf(exec);
388
404
  if (cached && cached.sessionKey)
@@ -431,9 +447,23 @@ function writeContextPending(dataRoot, sessionKey, o) {
431
447
  catch { /* ignore */ }
432
448
  }
433
449
  /** 读登记(session-manager 的 pre-step 用) */
434
- export function readContextPending(dataRoot, sessionKey) {
450
+ export function readContextPending(dataRoot, sessionKey, expectSessionId) {
435
451
  try {
436
- return JSON.parse(readFileSync(ctxPendingPath(dataRoot, sessionKey), 'utf8'));
452
+ const o = JSON.parse(readFileSync(ctxPendingPath(dataRoot, sessionKey), 'utf8'));
453
+ if (!o)
454
+ return undefined;
455
+ // ★★ 2026-11-28(CodeRabbit:按会话键登记的历史派生会话会误消费)
456
+ // pending 文件是按 **sessionKey** 命名的,而 `/bot-new` 之后**历史会话**的 id 仍能经
457
+ // 派生反查映射回同一个 key(`derive(key)` 是确定性的)。于是"打开历史会话"会让它
458
+ // 读走**当前会话**登记的压缩请求,把历史会话自己的历史裁掉,而当前会话的请求被吞掉。
459
+ // 这条裁剪不可逆,只有 note 里的要点留得下。
460
+ // 兜法:登记时记下目标会话 id,读取时对不上就当作没有(**不删**,留给真正的主人)。
461
+ // 旧格式(没有 sessionId)不拦,保持向后兼容。
462
+ const want = String(expectSessionId ?? '').trim();
463
+ const got = String(o.sessionId ?? '').trim();
464
+ if (want && got && got !== want)
465
+ return undefined;
466
+ return o;
437
467
  }
438
468
  catch {
439
469
  return undefined;
@@ -615,6 +645,11 @@ function stickerStoreOf(exec) {
615
645
  * 调用方(session-manager)知道自己是谁,必须把根传进来。
616
646
  * @param opts.cwd 本实例的工作目录(扩展 runner 的 env.cwd)
617
647
  */
648
+ /**
649
+ * @param opts.config 当前插件配置(2026-11-26,issue #94 加)。
650
+ * 装载方 SessionManager 手里有 `this.config`,沿参数链传进来即可 ——
651
+ * 这样工具可见性判定能读到用户配置,不必去猜或读全局。
652
+ */
618
653
  export async function apply(ctx, opts) {
619
654
  // ★★★ 2026-10-31:记住本插件的 apply ctx —— expose:'all' 的工具必须注册到**这个** ctx 上,
620
655
  // 才能和普通扩展工具(下面的 `ctx.tools.register`)处在同一个作用域。
@@ -1207,7 +1242,9 @@ export async function apply(ctx, opts) {
1207
1242
  description: '回复闸门(**只在你不回复时**才调用): 每轮先自己判断"这一轮该不该说话"——判断要回,就**直接回复**,不要调用本工具; 判断这一轮不该说话(没@你、话题与你无关、没必要插嘴),就调用它传 reply:false,本回合立即静默终止,你不会再输出任何内容(这条消息就像没发生过)。默认行为是"正常回复",所以不调用它 = 照常说话。' +
1208
1243
  '\n✅ **收到 reply:false 后,你会看到一条 `tool call aborted` 之类的"报错" —— 那正是「静默成功」本身**(本工具就是靠中断输出实现的,设计如此),不是工具坏了、也不是调用失败。看到它请直接收手,什么都不用做、也不用重试。' +
1209
1244
  '\n⛔ **不要为了"想安静"去动别的开关**(例如把出站模式切成 silent/静默):那会影响**后续所有回合**,而你要的只是"这一轮别说话"。要静默,只走本工具。' +
1210
- '\n⚠️ 传 reply:false 后**不要再调用任何工具**(包括记笔记、记喜好、发表情包): 本回合已经关闭, 那些调用会被直接中止 —— 想记录的话, 留到下一次开口的回合里做。',
1245
+ '\n⚠️ 传 reply:false 后**不要再调用任何工具**(包括记笔记、记喜好、发表情包): 本回合已经关闭, 那些调用会被直接中止 —— 想记录的话, 留到下一次开口的回合里做。' +
1246
+ '\n🚫 **私聊(c2c)里、或被 @ 时,永远不要调用本工具**:私聊是主人一对一找你说话,静默等于不回话;被 @ 是明确在叫你。这两种情况直接回,闸门只用于群里「旁观」的回合。' +
1247
+ '\n⚠️ **reply 语义只看布尔值**:reply:false = 这一轮静默;reply:true = 继续回复。reason 必须与 reply 一致 —— 如果 reason 里明确写着"该回/必须回/需要回",就不要传 reply:false;而「不需要回复」「已经有群友回答了」这类是**否定/已答语境**,传 reply:false 是**对的**,不会被拦。',
1211
1248
  parameters: {
1212
1249
  reply: { type: 'boolean', required: true, description: 'false=静默终止本回合(不再输出任何内容); true=正常继续(一般用不到 —— 想说话就直接说, 不必调本工具)' },
1213
1250
  reason: { type: 'string', required: true, description: '为什么这一轮不说话, 如"未@且话题无关" / "只是别人在聊天" / "已经问过她了"' },
@@ -1218,10 +1255,11 @@ export async function apply(ctx, opts) {
1218
1255
  properties: {
1219
1256
  ok: { type: 'boolean', required: true },
1220
1257
  stopped: { type: 'boolean', required: true },
1258
+ note: { type: 'string', description: '被私聊拦下时的回执说明(此时 stopped=false,本回合照常开口)' },
1221
1259
  },
1222
1260
  },
1223
1261
  render: (_a, v) => [
1224
- { type: 'text', text: v.stopped
1262
+ { type: 'text', text: v.note ? String(v.note) : v.stopped
1225
1263
  ? '(已静默: 本回合终止, 不再回复)'
1226
1264
  // ★ 2026-10-29(issue #28):原来是「(继续回复)」—— 括号舞台提示体,天然被读成"接着演",
1227
1265
  // 而闸门把回合劈成两段后,待回的那条消息已被挤到上下文中间,末尾只剩这句提示 ⇒
@@ -1231,6 +1269,43 @@ export async function apply(ctx, opts) {
1231
1269
  },
1232
1270
  async execute(args, exec) {
1233
1271
  if (args.reply === false) {
1272
+ let sessionKey = '';
1273
+ try {
1274
+ sessionKey = (await resolveCtxMemoEnv(exec))?.sessionKey ?? '';
1275
+ }
1276
+ catch { /* ignore */ }
1277
+ // ★ 2026-11-27(实测事故):私聊里闸门恒开 —— 私聊是主人一对一找它说话,静默等于不回话。
1278
+ // 本地 27B 在无思考档位下会把本工具当成"开口开关",连传 reply:false(reason 里却写着"要回复"),
1279
+ // cancel 掉整个回合 ⇒ 用户只看到 tool call aborted、一个字都没收到(11-27 夜里连续复现)。
1280
+ // 所以在真正取消之前先判会话类型:c2c 一律放行(stopped:false + 回执说清楚),不 cancel。
1281
+ // ⚠️ c2c 判定要**与出站侧同源**(那边用 `record.scope`):只嗅 sessionKey 字符串不够稳 ——
1282
+ // `resolveCtxMemoEnv` 拿不到时会回空串,而 `''.includes(':c2c:') === false`
1283
+ // ⇒ 私聊被当成群聊 ⇒ 照旧 cancel(本 bug 原样复活)。所以优先取记录里的 scope。
1284
+ let scopeOfSession = '';
1285
+ try {
1286
+ const gotOf = findSessionRec(channelOf(exec), exec);
1287
+ scopeOfSession = String(gotOf?.rec?.scope ?? '');
1288
+ }
1289
+ catch { /* ignore */ }
1290
+ const isC2c = scopeOfSession === 'c2c' || (!!sessionKey && sessionKey.includes(':c2c:'));
1291
+ if (isC2c) {
1292
+ return { ok: true, stopped: false, note: '(私聊必须开口:闸门在私聊恒开 —— 直接写你要说的那句话,不要静默)' };
1293
+ }
1294
+ // ★ 2026-11-28(实测事故):小傻龙群里 @ 提问,模型传 reply:false 且 reason="用户直接@我提问,需要回复",
1295
+ // 闸门照单 cancel ⇒ turn/end aborted(hook reply_gate: 本轮静默),用户只看到 tool call aborted。
1296
+ // 这是 27B 无思考档位下的布尔语义反转:reason 说要回,reply 却传了 false。
1297
+ // 命中矛盾时不 cancel,返回明确回执让模型直接开口;正常静默仍走原 cancel 路径。
1298
+ // ⚠️ 判定**不能**按"整串里有没有某几个词"—— 否定是**分句局部**的:
1299
+ // 「未@我,不需要回复」「已经有群友回答了」都是正常静默,
1300
+ // 而「群友已经@我了,必须回复」是矛盾 —— 三者都含"已经/回答"类词,
1301
+ // 只有**逐处就近判否定**才分得开(见 shared/reply-gate-reason.ts)。
1302
+ const reason = typeof args.reason === 'string' ? args.reason : '';
1303
+ // ⚠️ 判定收在 `shared/reply-gate-reason.ts` —— 与 outbound 的出站静默**共用一份**,
1304
+ // 别在这里再写一条正则(两处不同步就是"工具放行了、出站还在静默"这类怪象)。
1305
+ // 否定 / 已答语境优先:「未@我,不需要回复」「已经有群友回答了」都**不算**矛盾。
1306
+ if (isContradictoryReplyFalse(reason)) {
1307
+ return { ok: true, stopped: false, note: '(自相矛盾:reason 说要回复却传 reply=false —— 直接写你要说的那句话,不要再调本工具,也不要静默)' };
1308
+ }
1234
1309
  try {
1235
1310
  const agent = exec.agent;
1236
1311
  if (agent && typeof agent.cancel === 'function') {
@@ -2269,7 +2344,8 @@ export async function apply(ctx, opts) {
2269
2344
  const ga = groupAdminOf(exec);
2270
2345
  if (!ga)
2271
2346
  return { ok: false, msg: '群管理未开启或非群会话' };
2272
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2347
+ const ctxRoot = await resolveCtxDataRoot(exec);
2348
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2273
2349
  if (!gid)
2274
2350
  return { ok: false, msg: '当前不是群会话且未指定 gid, 无法确定目标群' };
2275
2351
  const r = await ga.client.getMuteState(gid);
@@ -2308,14 +2384,15 @@ export async function apply(ctx, opts) {
2308
2384
  const ga = groupAdminOf(exec);
2309
2385
  if (!ga)
2310
2386
  return { ok: false, msg: '群管理未开启或非群会话' };
2311
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2387
+ const ctxRoot = await resolveCtxDataRoot(exec);
2388
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2312
2389
  if (!gid)
2313
2390
  return { ok: false, msg: '当前不是群会话且未指定 gid, 无法确定目标群' };
2314
2391
  let msgId = String(args.msg_id ?? '').trim();
2315
2392
  let who = '';
2316
2393
  if (msgId === '') {
2317
2394
  const member = String(args.member ?? '').trim();
2318
- const rec = latestMsgHistory('group', gid, { senderId: member || undefined, withinMs: 120_000 });
2395
+ const rec = latestMsgHistory('group', gid, { senderId: member || undefined, withinMs: 120_000 }, ctxRoot);
2319
2396
  if (!rec) {
2320
2397
  return {
2321
2398
  ok: false,
@@ -2359,7 +2436,8 @@ export async function apply(ctx, opts) {
2359
2436
  const ga = groupAdminOf(exec);
2360
2437
  if (!ga)
2361
2438
  return { ok: false, msg: '群管理未开启或非群会话' };
2362
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2439
+ const ctxRoot = await resolveCtxDataRoot(exec);
2440
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2363
2441
  if (!gid)
2364
2442
  return { ok: false, msg: '当前不是群会话且未指定 gid' };
2365
2443
  const list = readMsgHistory('group', gid, {
@@ -2367,9 +2445,9 @@ export async function apply(ctx, opts) {
2367
2445
  kind: (args.kind ? String(args.kind) : undefined),
2368
2446
  fromSelf: typeof args.from_self === 'boolean' ? args.from_self : undefined,
2369
2447
  limit: Number(args.limit) || 20,
2370
- });
2448
+ }, ctxRoot);
2371
2449
  if (list.length === 0)
2372
- return { ok: true, msg: '台账里没有命中的消息(默认只查最近 2 小时)。' + historyDebug('group', gid) };
2450
+ return { ok: true, msg: '台账里没有命中的消息(默认只查最近 2 小时)。' + historyDebug('group', gid, ctxRoot) };
2373
2451
  const lines = list.map((m, i) => `${i + 1}. ${m.me ? '🤖' : '👤'}${m.n || m.s} [${m.k ?? 'text'}] ${m.x || '(无正文)'}|id=${String(m.id).slice(0, 16)}…|${new Date(m.t).toLocaleTimeString('zh-CN')}`);
2374
2452
  return {
2375
2453
  ok: true,
@@ -2408,7 +2486,7 @@ export async function apply(ctx, opts) {
2408
2486
  execute: async (args) => {
2409
2487
  try {
2410
2488
  const prof = process.env.DSH_PROFILE || 'web';
2411
- const base = join(homedir(), '.dsh', 'qqbot-settings', prof);
2489
+ const base = dshHomePath('qqbot-settings', prof);
2412
2490
  let file = join(base, 'im-qqbot-2.json');
2413
2491
  if (!existsSync(file)) {
2414
2492
  const cands = existsSync(base) ? readdirSync(base).filter((f) => /^im-qqbot-.*\.json$/.test(f)) : [];
@@ -2493,7 +2571,8 @@ export async function apply(ctx, opts) {
2493
2571
  const ga = groupAdminOf(exec);
2494
2572
  if (!ga)
2495
2573
  return { ok: false, msg: '群管理未开启或非群会话' };
2496
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2574
+ const ctxRoot = await resolveCtxDataRoot(exec);
2575
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2497
2576
  if (!gid)
2498
2577
  return { ok: false, msg: '当前不是群会话且未指定 gid' };
2499
2578
  const ids = (Array.isArray(args.member_openids) ? args.member_openids : [])
@@ -2638,7 +2717,8 @@ export async function apply(ctx, opts) {
2638
2717
  const ga = groupAdminOf(exec);
2639
2718
  if (!ga)
2640
2719
  return { ok: false, msg: '群管理未开启或非群会话' };
2641
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2720
+ const ctxRoot = await resolveCtxDataRoot(exec);
2721
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2642
2722
  if (!gid)
2643
2723
  return { ok: false, msg: '当前不是群会话且未指定 gid' };
2644
2724
  const brief = (m) => `${m.me ? '🤖' : '👤'}${m.n || m.s} [${m.k ?? 'text'}] ${(m.x ?? '').slice(0, 24)}`;
@@ -2649,11 +2729,11 @@ export async function apply(ctx, opts) {
2649
2729
  keyword: args.keyword ? String(args.keyword) : undefined,
2650
2730
  kind: (args.kind ? String(args.kind) : undefined),
2651
2731
  limit: 20,
2652
- }).map((r) => ({ me: r.me, s: r.s, n: r.n, k: r.k, x: r.x, msgId: r.id }));
2732
+ }, ctxRoot).map((r) => ({ me: r.me, s: r.s, n: r.n, k: r.k, x: r.x, msgId: r.id }));
2653
2733
  ids = picked.map((p) => p.msgId);
2654
2734
  }
2655
2735
  else {
2656
- const all = readMsgHistory('group', gid, { withinMs: 120_000, limit: 200 }).map((r) => ({ me: r.me, s: r.s, n: r.n, k: r.k, x: r.x, msgId: r.id }));
2736
+ const all = readMsgHistory('group', gid, { withinMs: 120_000, limit: 200 }, ctxRoot).map((r) => ({ me: r.me, s: r.s, n: r.n, k: r.k, x: r.x, msgId: r.id }));
2657
2737
  picked = all.filter((p) => ids.includes(p.msgId));
2658
2738
  }
2659
2739
  ids = ids.slice(0, 20);
@@ -2721,7 +2801,8 @@ export async function apply(ctx, opts) {
2721
2801
  const ga = groupAdminOf(exec);
2722
2802
  if (!ga)
2723
2803
  return { ok: false, msg: '群管理未开启或非群会话' };
2724
- const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId();
2804
+ const ctxRoot = await resolveCtxDataRoot(exec);
2805
+ const gid = String(args.gid ?? '').trim() || ga.gid || latestGroupId(ctxRoot);
2725
2806
  if (!gid)
2726
2807
  return { ok: false, msg: '当前不是群会话且未指定 gid, 无法确定目标群' };
2727
2808
  const secs = Math.max(1, Math.min(30 * 86400, Math.round(Number(args.seconds ?? 600))));
@@ -3014,47 +3095,83 @@ export async function apply(ctx, opts) {
3014
3095
  // ✅ 全局注册统一交给 session-manager 的 pre-step 用**插件根 ctx** 做:
3015
3096
  // `ensureContextToolsGlobal(this.ctx)` —— 它内部用 `ctx.get('tools')` 取服务,绕开 inject 限制。
3016
3097
  // 这里只保留下面 ②段"QQ 群管理工具"的按会话注册(那本来就是会话级工具)。
3098
+ /**
3099
+ * 工具定义(2026-11-26,issue #94)。
3100
+ *
3101
+ * ★ `scope` 是**必填**的:它决定这个工具在「只要私聊」这类配置下会不会被注册。
3102
+ * 必填的意义 —— 新增工具时忘了标记,TypeScript 直接报错,而不是运行时静默漏掉,
3103
+ * 让用户再提一次「XX 工具关不掉」(这正是 issue #94 的成因)。
3104
+ * · group 纯群治理(没有群就是空壳)
3105
+ * · cross 跨会话投递(私聊用户也可能要)
3106
+ * · memo 人物记忆
3107
+ * · base 其余:媒体 / 表情 / 会话控制 / 定时
3108
+ */
3017
3109
  const toolDefs = [
3018
- { name: 'send_media', tool: sendMediaTool },
3019
- { name: 'recall_message', tool: recallTool },
3020
- { name: 'text_break', tool: textBreakTool },
3021
- { name: 'quote_view', tool: quoteViewTool },
3022
- { name: 'people_memo', tool: peopleMemoTool },
3110
+ { name: 'send_media', tool: sendMediaTool, scope: 'base' },
3111
+ { name: 'recall_message', tool: recallTool, scope: 'base' },
3112
+ { name: 'text_break', tool: textBreakTool, scope: 'base' },
3113
+ { name: 'quote_view', tool: quoteViewTool, scope: 'base' },
3114
+ { name: 'people_memo', tool: peopleMemoTool, scope: 'memo' },
3023
3115
  // 无上下文模式·智能判断专用(全局开关 config.contextlessSmart 开启时才出现)
3024
3116
  ...(getContextlessSmartGlobal() === true
3025
3117
  ? []
3026
3118
  : []),
3027
- { name: 'tools_reload', tool: toolsReloadTool },
3028
- { name: 'reply_gate', tool: replyGateTool },
3029
- { name: 'outbound_mode', tool: outboundModeTool },
3030
- { name: 'group_join_requests', tool: listJoinRequestsTool },
3031
- { name: 'group_approve_join', tool: approveJoinTool },
3032
- { name: 'group_join_auto', tool: autoApproveJoinTool },
3033
- { name: 'group_mute_state', tool: muteStateTool },
3034
- { name: 'group_mute_member', tool: muteMemberTool },
3035
- { name: 'group_recall', tool: groupRecallTool },
3036
- { name: 'group_msg_search', tool: msgSearchTool },
3037
- { name: 'group_recall_batch', tool: recallBatchTool },
3038
- { name: 'recall_keywords', tool: recallKeywordsTool },
3039
- { name: 'group_kick', tool: kickMemberTool },
3040
- { name: 'qq_material', tool: materialTool },
3041
- { name: 'id_lookup', tool: idLookupTool },
3042
- { name: 'session_list', tool: sessionListTool },
3043
- { name: 'session_wake', tool: sessionWakeTool },
3044
- { name: 'broadcast_send', tool: broadcastSendTool },
3045
- { name: 'target_group', tool: targetGroupTool },
3046
- { name: 'list_stickers', tool: listStickersTool },
3047
- { name: 'sticker_tag', tool: tagStickerTool },
3048
- { name: 'sticker_delete', tool: deleteStickerTool },
3049
- { name: 'sticker_restore', tool: restoreStickerTool },
3050
- { name: 'sticker_stats', tool: statsStickerTool },
3051
- { name: 'sticker_untagged', tool: untaggedStickerTool },
3052
- { name: 'schedule_timer', tool: scheduleTimerTool },
3053
- { name: 'schedule_cancel', tool: scheduleCancelTool },
3119
+ { name: 'tools_reload', tool: toolsReloadTool, scope: 'base' },
3120
+ { name: 'reply_gate', tool: replyGateTool, scope: 'base' },
3121
+ { name: 'outbound_mode', tool: outboundModeTool, scope: 'base' },
3122
+ { name: 'group_join_requests', tool: listJoinRequestsTool, scope: 'group' },
3123
+ { name: 'group_approve_join', tool: approveJoinTool, scope: 'group' },
3124
+ { name: 'group_join_auto', tool: autoApproveJoinTool, scope: 'group' },
3125
+ { name: 'group_mute_state', tool: muteStateTool, scope: 'group' },
3126
+ { name: 'group_mute_member', tool: muteMemberTool, scope: 'group' },
3127
+ { name: 'group_recall', tool: groupRecallTool, scope: 'group' },
3128
+ { name: 'group_msg_search', tool: msgSearchTool, scope: 'group' },
3129
+ { name: 'group_recall_batch', tool: recallBatchTool, scope: 'group' },
3130
+ { name: 'recall_keywords', tool: recallKeywordsTool, scope: 'group' },
3131
+ { name: 'group_kick', tool: kickMemberTool, scope: 'group' },
3132
+ { name: 'qq_material', tool: materialTool, scope: 'base' },
3133
+ { name: 'id_lookup', tool: idLookupTool, scope: 'cross' },
3134
+ { name: 'session_list', tool: sessionListTool, scope: 'cross' },
3135
+ { name: 'session_wake', tool: sessionWakeTool, scope: 'cross' },
3136
+ { name: 'broadcast_send', tool: broadcastSendTool, scope: 'cross' },
3137
+ { name: 'target_group', tool: targetGroupTool, scope: 'cross' },
3138
+ { name: 'list_stickers', tool: listStickersTool, scope: 'base' },
3139
+ { name: 'sticker_tag', tool: tagStickerTool, scope: 'base' },
3140
+ { name: 'sticker_delete', tool: deleteStickerTool, scope: 'base' },
3141
+ { name: 'sticker_restore', tool: restoreStickerTool, scope: 'base' },
3142
+ { name: 'sticker_stats', tool: statsStickerTool, scope: 'base' },
3143
+ { name: 'sticker_untagged', tool: untaggedStickerTool, scope: 'base' },
3144
+ { name: 'schedule_timer', tool: scheduleTimerTool, scope: 'base' },
3145
+ { name: 'schedule_cancel', tool: scheduleCancelTool, scope: 'base' },
3054
3146
  ];
3147
+ // ★ 2026-11-26(issue #94):内置工具终于也有「条件可见」了 ——
3148
+ // 照抄扩展工具那套 `enabled(env)` 的语义(见 extension-store.ts 的同名注释):
3149
+ // **注册前判定,返回 false 就 continue ⇒ AI 完全看不见**,
3150
+ // 而不是"看得见但报错"。这样它的 describe 也不再每轮占 context。
3151
+ // 判定为假时顺手回收旧句柄(若之前注册过),实现「关了就是真关」。
3152
+ const skipped = [];
3153
+ const myDisposers = disposerBucketOf(ctx); // ★ P0-4:按本 agent 分桶
3154
+ let okCount = 0; // ★ P1-4:真实注册成功数(原口径把失败也算进去了)
3055
3155
  for (const t of toolDefs) {
3156
+ if (!toolVisible(t.name, t.scope, opts?.config)) {
3157
+ const stale = myDisposers.get(t.name);
3158
+ if (stale) {
3159
+ try {
3160
+ stale();
3161
+ }
3162
+ catch { /* 旧句柄已失效 */ }
3163
+ myDisposers.delete(t.name);
3164
+ }
3165
+ skipped.push(t.name);
3166
+ diag(`条件隐藏(配置关闭): ${t.name}`);
3167
+ continue;
3168
+ }
3056
3169
  try {
3057
- ctx.tools.register(t.tool);
3170
+ // ★ 收下 disposer(original 是直接丢弃的,于是「热关闭」不可能 —— issue #94 的另一半)
3171
+ const dispose = ctx.tools.register(t.tool);
3172
+ if (typeof dispose === 'function')
3173
+ myDisposers.set(t.name, dispose);
3174
+ okCount += 1;
3058
3175
  ctx.logger?.info?.(`[channel-tools] 已注册: ${t.name}`);
3059
3176
  diag(`注册成功: ${t.name}`);
3060
3177
  }
@@ -3069,6 +3186,22 @@ export async function apply(ctx, opts) {
3069
3186
  diag(`注册失败: ${t.name} → ${msg}`);
3070
3187
  }
3071
3188
  }
3189
+ // 一行可验证的收尾日志(issue #94 的验收标准:从「能关」变成「能验证关了」)
3190
+ // ★ P1-3:ensureChannelTools 是**每条入站消息**调一次,全量打 info 会把日志淹掉。
3191
+ // 只在「本次有隐藏」或「隐藏集合变了」时打 info,其余降到 diag。
3192
+ const sig = skipped.join(',') || '(none)';
3193
+ if (sig !== lastVisibilitySig) {
3194
+ lastVisibilitySig = sig;
3195
+ if (skipped.length > 0) {
3196
+ ctx.logger?.info?.(`[channel-tools] 按配置隐藏 ${skipped.length} 个工具(${okCount}/${toolDefs.length} 已注册): ${skipped.join(', ')}`);
3197
+ }
3198
+ else {
3199
+ ctx.logger?.info?.(`[channel-tools] 全部 ${toolDefs.length} 个工具已注册(未配置隐藏)`);
3200
+ }
3201
+ }
3202
+ else {
3203
+ diag(`可见性未变: ${okCount}/${toolDefs.length} 已注册, 隐藏 ${skipped.length}`);
3204
+ }
3072
3205
  // ══════════════════════════════════════════════════════════════════════════
3073
3206
  // expose:'all' 支撑(2026-10-10 主人定)—— 扩展工具的"跨通道"能力
3074
3207
  // ══════════════════════════════════════════════════════════════════════════
@@ -3777,7 +3910,7 @@ var contextCompactTool = defineTool({
3777
3910
  const a = (args ?? {});
3778
3911
  if (a.note)
3779
3912
  appendContextMemo(r.dataRoot, r.sessionKey, String(a.note));
3780
- writeContextPending(r.dataRoot, r.sessionKey, { mode: 'compact', keep: Number(a.keep) || 3, at: Date.now() });
3913
+ writeContextPending(r.dataRoot, r.sessionKey, { mode: 'compact', keep: Number(a.keep) || 3, at: Date.now(), sessionId: execSessionId(exec) || undefined });
3781
3914
  return { ok: true, msg: '已登记压缩:下一个回合开始时执行'
3782
3915
  + (a.note ? '(要点已存进你的备忘)' : '(本次没写要点;若压缩后有需要记住的,请带上 note)') };
3783
3916
  },
@@ -3805,7 +3938,7 @@ var contextDropTool = defineTool({
3805
3938
  const a = (args ?? {});
3806
3939
  if (a.note)
3807
3940
  appendContextMemo(r.dataRoot, r.sessionKey, String(a.note));
3808
- writeContextPending(r.dataRoot, r.sessionKey, { mode: 'drop', keep: 0, at: Date.now() });
3941
+ writeContextPending(r.dataRoot, r.sessionKey, { mode: 'drop', keep: 0, at: Date.now(), sessionId: execSessionId(exec) || undefined });
3809
3942
  return { ok: true, msg: '已登记丢弃:下一个回合开始时执行'
3810
3943
  + (a.note ? '(要点已存进你的备忘)' : '(本次没写要点;丢弃后这些历史就找不回来了,建议带 note)') };
3811
3944
  },
@@ -3820,6 +3953,68 @@ var contextDropTool = defineTool({
3820
3953
  * 而"某个人到底是哪个 QQ"这种需求只有这条老网页版通道能满足。
3821
3954
  * 所以 `group_kick`(官方 API)和它**并存**,各管一边,不要互相替代。
3822
3955
  */
3956
+ // ══════════════════════════════════════════════════════════════════════════
3957
+ // 工具可见性(2026-11-26,issue #94)
3958
+ // ══════════════════════════════════════════════════════════════════════════
3959
+ //
3960
+ // 语义与扩展工具的 `enabled(env)` 完全一致(见 extension-store.ts:211-221):
3961
+ // **注册前判定,false ⇒ 不注册**,AI 完全看不见,其 schema 也不再占 context。
3962
+ // 不配置 = 永远可见 ⇒ 存量用户行为逐字不变。
3963
+ //
3964
+ // 两层结构:类开关给默认值,单项 overrides 给它做例外。
3965
+ /**
3966
+ * 已注册内置工具的 disposer,用于「改配置后真的能撤销」(原来 register 的返回值被直接丢弃)。
3967
+ *
3968
+ * ⚠️ 2026-11-26(审核 P0-4):必须**按 agentCtx 分桶**。
3969
+ * `ctx.tools.register()` 是 per-agent 各注册一份,若只用工具名做 key(模块级 Map),
3970
+ * 会话 B 的 apply 会把会话 A 的句柄覆盖掉 ⇒ A 的那份永远撤不掉,还会出现
3971
+ * 「撤掉的是别的会话的工具」。
3972
+ * 用 WeakMap 查(不阻止 ctx 回收)+ Map 登记桶(需要枚举时用)。
3973
+ */
3974
+ /** 上一次的隐藏集合签名(用于抑制重复 info 日志,见 P1-3) */
3975
+ let lastVisibilitySig = '';
3976
+ const builtinDisposerBuckets = new WeakMap();
3977
+ function disposerBucketOf(ctx) {
3978
+ const key = ctx;
3979
+ let m = builtinDisposerBuckets.get(key);
3980
+ if (!m) {
3981
+ m = new Map();
3982
+ builtinDisposerBuckets.set(key, m);
3983
+ }
3984
+ return m;
3985
+ }
3986
+ /**
3987
+ * 这个工具在**当前配置**下是否可见。
3988
+ *
3989
+ * 判定顺序:单项覆盖 → 类开关 → 默认可见。
3990
+ * `overrides` 优先是刻意的:用户先按类关掉 10 个群工具,再单独把 group_kick 勾回来,是可预期的。
3991
+ */
3992
+ export function toolVisible(name, scope, config) {
3993
+ const vis = config?.visibility?.tools;
3994
+ const ov = vis?.overrides;
3995
+ if (ov && typeof ov[name] === 'boolean')
3996
+ return ov[name];
3997
+ const cls = vis?.classes;
3998
+ if (cls && typeof cls[scope] === 'boolean')
3999
+ return cls[scope];
4000
+ return true; // 未配置 ⇒ 可见(与旧版行为一致)
4001
+ }
4002
+ /**
4003
+ * dock 标签的可见性。语义基准:**client 的 dockOn() 必须与此逐行一致**
4004
+ * (overrides → classes → true,且都用 `typeof === 'boolean'` 严格判)。
4005
+ * client 是手写 bundle(不 import dist),两者是**双源同步**关系 ——
4006
+ * 改这里记得同步改 `client/qqbot-settings.js` 的 visOf()。
4007
+ */
4008
+ export function dockTabVisible(key, cap, config) {
4009
+ const vis = config?.visibility?.dock;
4010
+ const ov = vis?.overrides;
4011
+ if (ov && typeof ov[key] === 'boolean')
4012
+ return ov[key];
4013
+ const cls = vis?.classes;
4014
+ if (cls && typeof cls[cap] === 'boolean')
4015
+ return cls[cap];
4016
+ return true;
4017
+ }
3823
4018
  var qunAdminTool = defineTool({
3824
4019
  name: 'qq_group_admin',
3825
4020
  description: '【老网页版通道 · 唯一能看 QQ 号】用主人自己的 QQ 号管理群(我创建/我管理的群):登录、看群列表、查群成员、踢人。'
@@ -4062,6 +4257,11 @@ export function setCtxEnv(agentCtx, env) {
4062
4257
  }
4063
4258
  catch { /* ignore */ }
4064
4259
  }
4260
+ /**
4261
+ * ⚠️ 2026-11-26:**已废弃**(全仓无调用点)。qq_group_admin 现在只经
4262
+ * `syncChannelScopedTools` 注册,可见性由那里的 `toolVisible` 判定。
4263
+ * 若将来要复活本函数,必须补上同样的 toolVisible 判定,否则 issue #94 的洞会重新打开。
4264
+ */
4065
4265
  export function syncContextTools(agentCtx, shouldHave, env, reminderText) {
4066
4266
  void reminderText; // 保留签名(提示文本改由主 ctx 的 systemPrompt.context 提供,见 index.ts)
4067
4267
  if (!agentCtx || typeof agentCtx !== 'object')
@@ -4177,7 +4377,19 @@ export function applyExtToolVisibility(agentCtx, selfTag) {
4177
4377
  return;
4178
4378
  const prevTag = extSeenCtx.get(ctx) ?? '';
4179
4379
  const tag = selfTag !== undefined ? String(selfTag) : prevTag;
4380
+ // ★ 2026-11-28(复审 Y31):**先判空、再登记**。
4381
+ // 反过来(先 `set` 再判空)会把 `extSeenCtx` 里这个 ctx 的 tag 抹成 `''` ——
4382
+ // `extSeenCtx` 是**模块级、全实例共享**的。多开实例同 cwd 时,B 对"本不该碰的 A 的 ctx"
4383
+ // 调一次本函数(传空 tag)就会踩掉 A 的记录;之后 A 那边 `gain_qq_tools.enable(...)` 的
4384
+ // 补注册(不传 selfTag、靠 prevTag 回落)与整表重放都会因拿不到 tag 直接 return
4385
+ // ⇒ 表现成「enable 了却调不到」,极难查。
4386
+ if (!tag) {
4387
+ traceToolReg('[ext-vis] 跳过(拿不到 selfTag)');
4388
+ return;
4389
+ }
4180
4390
  extSeenCtx.set(ctx, tag);
4391
+ // ⚠️ `''` 的语义是**「不碰」**,不是「清空这个 ctx 的记录」—— 判空在登记之前,
4392
+ // 所以传空 tag 不会把已有记录抹掉。要"撤销某个 ctx 的 tag"得另加 API(目前没有这需求)。
4181
4393
  // ★★★ 2026-10-31(主人实测后的最终结论):**改成 per-agent 注册**。
4182
4394
  // 实测对照:同一次运行里
4183
4395
  // · ensureExtToolsGlobal 注册到 apply(ctx) → QQ 会话调不到(unknown tool)
@@ -4186,10 +4398,6 @@ export function applyExtToolVisibility(agentCtx, selfTag) {
4186
4398
  // 该 agent 应有的 = 本实例自己的(__selfTag)+ 已领取的,逐个注册到它的 ctx;
4187
4399
  // 既不用 deny,也不用 root —— 非 QQ agent 不走这段,天然零泄漏。
4188
4400
  // ⚠️ 拿不到 tag 就什么都不做(否则会把"自己实例那份"也漏掉)。
4189
- if (!tag) {
4190
- traceToolReg('[ext-vis] 跳过(拿不到 selfTag)');
4191
- return;
4192
- }
4193
4401
  const all = [...extToolIndex.values()];
4194
4402
  if (!all.length)
4195
4403
  return; // 还没扫到东西:先不动
@@ -4777,6 +4985,11 @@ export function ensureExtToolsGlobal(globalCtx) {
4777
4985
  }
4778
4986
  })();
4779
4987
  }
4988
+ /**
4989
+ * ⚠️ 2026-11-26:**已废弃**(全仓无调用点)。理由同 syncContextTools ——
4990
+ * 它内部 `for (const t of [...ctxToolsRef(), ...qunAdminRef()])` 是无条件注册,
4991
+ * 复活前必须先接 toolVisible。
4992
+ */
4780
4993
  export function ensureContextToolsGlobal(globalCtx) {
4781
4994
  // 2026-10-21 修(trace 实证):restrict 报 "names unknown global tools" => 我们注册的层不是「全局层」。
4782
4995
  // cordis 的 ctx.root 才是根作用域;拿不到就退回传入值(行为不变)。
@@ -4956,7 +5169,13 @@ export function syncChannelScopedTools(agentCtx, opts) {
4956
5169
  if (opts.dataRoot) {
4957
5170
  ctxEnvMap.set(key, { dataRoot: String(opts.dataRoot), sessionKey: String(opts.sessionKey ?? '') });
4958
5171
  }
4959
- const sig = `${opts.ctxTools ? '1' : '0'}${opts.groupAdmin ? '1' : '0'}`;
5172
+ // ★ 2026-11-26(审核 R2 同类坑):sig 只有两位时,新增的判定维度改了它也不会变
5173
+ // ⇒ `if (st.sig === sig) return` 直接跳过 ⇒ 静默不生效。把可见性也并进来。
5174
+ // ★ 复审 A 的防御:**不影响 want 的维度不要进 sig**。
5175
+ // groupAdmin 关着时 want 本来就不含 qq_group_admin,此时若 qunVisible 仍随配置变化,
5176
+ // 任何一处漏传 config 的调用点都会算出不同 sig → 每 step 抖动。
5177
+ const qunVisible = opts.groupAdmin && !toolVisible('qq_group_admin', 'group', opts.config) ? '0' : '1';
5178
+ const sig = `${opts.ctxTools ? '1' : '0'}${opts.groupAdmin ? '1' : '0'}${qunVisible}`;
4960
5179
  const st = ctxScopeState.get(key);
4961
5180
  if (st && st.sig === sig)
4962
5181
  return; // 状态一致 → 不动(这是"不抖"的关键)
@@ -4974,9 +5193,12 @@ export function syncChannelScopedTools(agentCtx, opts) {
4974
5193
  }
4975
5194
  catch { /* ignore */ }
4976
5195
  }
5196
+ // ★ 2026-11-26(issue #94 / 审核 P1-2):qq_group_admin 是**最像群治理**的工具
5197
+ // (描述很长,每轮都占 context),以前只受 groupAdmin.enabled 管,
5198
+ // 用户把 visibility.tools.classes.group 关掉它还在。现在两者都要过。
4977
5199
  const want = [
4978
5200
  ...(opts.ctxTools ? ctxToolsRef() : []),
4979
- ...(opts.groupAdmin ? qunAdminRef() : []),
5201
+ ...(opts.groupAdmin && qunVisible === '1' ? qunAdminRef() : []),
4980
5202
  ];
4981
5203
  const disposers = [];
4982
5204
  for (const t of want) {
@@ -4990,7 +5212,7 @@ export function syncChannelScopedTools(agentCtx, opts) {
4990
5212
  // 全成功才认这个 sig;否则标 __retry,下一 step 重来
4991
5213
  const okAll = disposers.length === want.length;
4992
5214
  ctxScopeState.set(key, { sig: okAll ? sig : `__retry-${sig}`, disposers });
4993
- traceToolReg(`[scoped-tool] 按会话注册 ctx=${opts.ctxTools ? 1 : 0} groupAdmin=${opts.groupAdmin ? 1 : 0}`
5215
+ traceToolReg(`[scoped-tool] 按会话注册 ctx=${opts.ctxTools ? 1 : 0} groupAdmin=${opts.groupAdmin ? 1 : 0} qunVisible=${qunVisible}`
4994
5216
  + ` want=${want.length} ok=${disposers.length}`
4995
5217
  + ` dataRoot=${String(opts.dataRoot ?? '')} sk=${String(opts.sessionKey ?? '')}`);
4996
5218
  }