@nestim/koishi-plugin-qq-group-manager 1.4.6 → 1.4.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/src/ai/trigger.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * 触发放行判定(纯函数,便于单测)。
3
3
  *
4
- * 三道闸门保留,但语义收紧:
5
- * 1) 冷却:同一群两次"真正调用模型"之间至少间隔 aiMinReplyIntervalSeconds;
6
- * 2) 阈值:hybrid/threshold 下需累计够 aiMessageThreshold 条消息;
7
- * 3) 概率:random/hybrid 下每条消息掷一次骰。
8
- * 点名与"点名后跟随"直接放行(不占冷却)。
4
+ * 冷却的语义已经统一:**所有真正调用模型的行为**(含 @、点名后跟随)
5
+ * 都受同一个冷却约束,按「上一次调用模型的时刻」计算,而不是按
6
+ * 「上一次成功发出回复」——模型返回 <pass/>、被过滤器拦下、请求失败
7
+ * 都算用过一次,避免一直失败却一直重试。
8
+ *
9
+ * 被 @ 但仍在冷却里时返回 remainingMs,由引擎决定是否在群里提示还剩多久。
9
10
  */
10
11
 
11
12
  export interface TriggerInput {
@@ -16,38 +17,56 @@ export interface TriggerInput {
16
17
  now: number;
17
18
  lastAttemptAt: number;
18
19
  minIntervalMs: number;
19
- /** 上一次真正发出回复的时间(用于 @ 冷却) */
20
- lastReplyAt: number;
21
- /** 被 @ 后两次回复的最小间隔 */
22
- mentionCooldownMs: number;
20
+ /** 兼容字段:旧版按“上次回复”计算的 @ 冷却,已合并进 minIntervalMs */
21
+ lastReplyAt?: number;
22
+ mentionCooldownMs?: number;
23
23
  inFlight: boolean;
24
24
  mention: boolean;
25
25
  followup: boolean;
26
26
  rng: () => number;
27
+ /** 伪随机:随机未命中时把下一次概率往上抬,直到必定触发 */
28
+ pseudoRandom?: boolean;
29
+ /** 当前已累计的概率加成(0~1) */
30
+ randomBoost?: number;
31
+ /** 每次未命中增加多少(默认 0.01) */
32
+ pseudoRandomStep?: number;
27
33
  }
28
34
 
29
35
  export interface TriggerDecision {
30
36
  fire: boolean;
31
37
  forced: boolean;
32
38
  reason: string;
39
+ /** 冷却中时距离可以再次调用模型的剩余毫秒数 */
40
+ remainingMs?: number;
41
+ /** 本次判定后应保存的伪随机加成;未发生随机掷骰时为 undefined(保持不变) */
42
+ nextBoost?: number;
43
+ /** 本次实际使用的概率(基础值 + 加成),用于日志排查 */
44
+ effectiveProbability?: number;
33
45
  }
34
46
 
35
47
  export function decideTrigger(input: TriggerInput): TriggerDecision {
36
48
  if (input.inFlight) return { fire: false, forced: false, reason: 'in-flight' };
37
49
 
38
- if (input.mention) {
39
- const cooldown = Math.max(0, Number(input.mentionCooldownMs) || 0);
40
- if (cooldown > 0 && input.now - (Number(input.lastReplyAt) || 0) < cooldown) {
41
- return { fire: false, forced: false, reason: 'mention-cooldown' };
50
+ // ---------- 1) 模型调用冷却:@ 也不能绕过 ----------
51
+ const cooldown = Math.max(0, Number(input.minIntervalMs) || 0);
52
+ const lastAttempt = Number(input.lastAttemptAt) || 0;
53
+ if (cooldown > 0 && lastAttempt > 0) {
54
+ const elapsed = input.now - lastAttempt;
55
+ if (elapsed < cooldown) {
56
+ return {
57
+ fire: false,
58
+ forced: false,
59
+ reason: input.mention ? 'cooldown-mention' : 'cooldown',
60
+ remainingMs: Math.max(0, cooldown - elapsed),
61
+ };
42
62
  }
43
- return { fire: true, forced: true, reason: 'direct-mention' };
44
63
  }
45
- if (input.followup) return { fire: true, forced: true, reason: 'followup' };
46
64
 
47
- if (input.minIntervalMs > 0 && input.now - input.lastAttemptAt < input.minIntervalMs) {
48
- return { fire: false, forced: false, reason: 'cooldown' };
49
- }
65
+ // ---------- 2) 点名与点名后跟随:越过阈值/概率,但不越过冷却 ----------
66
+ if (input.mention) return { fire: true, forced: true, reason: 'direct-mention' };
67
+ if (input.followup) return { fire: true, forced: true, reason: 'followup' };
50
68
 
69
+ // ---------- 3) 阈值 ----------
51
70
  const needThreshold = input.mode === 'threshold' || input.mode === 'hybrid';
52
71
  if (needThreshold && input.counter < Math.max(1, input.threshold)) {
53
72
  return {
@@ -57,13 +76,44 @@ export function decideTrigger(input: TriggerInput): TriggerDecision {
57
76
  };
58
77
  }
59
78
 
79
+ // ---------- 4) 概率(支持伪随机:连续未命中会逐步抬高概率) ----------
60
80
  const needRandom = input.mode === 'random' || input.mode === 'hybrid';
61
81
  if (needRandom) {
62
- const probability = Math.max(0, Math.min(1, Number(input.probability) || 0));
63
- if (probability <= 0) return { fire: false, forced: false, reason: 'random-disabled' };
64
- if (input.rng() >= probability) {
65
- return { fire: false, forced: false, reason: `random-miss(${probability})` };
82
+ const base = Math.max(0, Math.min(1, Number(input.probability) || 0));
83
+ const boost = Math.max(0, Number(input.randomBoost) || 0);
84
+ const effective = Math.min(1, base + boost);
85
+ const round4 = (value: number) => Math.round(value * 10000) / 10000;
86
+
87
+ if (effective <= 0) {
88
+ return {
89
+ fire: false,
90
+ forced: false,
91
+ reason: 'random-disabled',
92
+ nextBoost: round4(boost),
93
+ effectiveProbability: 0,
94
+ };
95
+ }
96
+
97
+ // 加成到 1 时必定触发,不再消耗随机数
98
+ if (effective >= 1 || input.rng() < effective) {
99
+ return {
100
+ fire: true,
101
+ forced: false,
102
+ reason: `trigger(${input.mode})`,
103
+ nextBoost: 0,
104
+ effectiveProbability: round4(effective),
105
+ };
66
106
  }
107
+
108
+ const step = Math.max(0, Number(input.pseudoRandomStep) || 0);
109
+ const nextBoost = input.pseudoRandom ? Math.min(1, round4(boost + step)) : round4(boost);
110
+ return {
111
+ fire: false,
112
+ forced: false,
113
+ reason: `random-miss(${effective.toFixed(2)})`,
114
+ nextBoost,
115
+ effectiveProbability: round4(effective),
116
+ };
67
117
  }
68
118
 
69
119
  return { fire: true, forced: false, reason: `trigger(${input.mode})` };
package/src/index.ts CHANGED
@@ -32,6 +32,12 @@ export const Config = Schema.intersect([
32
32
  groupRules: Schema.array(Schema.object({
33
33
  guildId: Schema.string().required().description('群号。'),
34
34
  enableAiReply: Schema.boolean().description('该群是否启用 AI 回复(留空则跟随全局设置)。'),
35
+ aiMessageThreshold: Schema.natural().description('该群触发的消息数阈值(留空跟随全局 aiMessageThreshold)。'),
36
+ aiRandomReplyProbability: Schema.percent().description('该群随机触发概率(0~1,控制台按百分比显示;留空跟随全局)。'),
37
+ aiPseudoRandom: Schema.boolean().description('该群是否启用伪随机(连续未命中逐步提高概率;留空跟随全局)。'),
38
+ aiPseudoRandomStep: Schema.number().min(0).max(1).step(0.001).description('该群伪随机每次未命中增加的概率(留空跟随全局)。'),
39
+ aiMinReplyIntervalSeconds: Schema.natural().description('该群模型调用冷却(秒;留空跟随全局 aiMinReplyIntervalSeconds)。'),
40
+ aiCooldownNotice: Schema.boolean().description('该群被 @ 但处于冷却时是否提示还剩多久(留空跟随全局)。'),
35
41
  bannedWords: Schema.array(String).role('table').default([]).description('该群专属违禁词列表(同样支持“关键词|分值”与顺序模糊匹配)。'),
36
42
  whitelistKeywords: Schema.array(String).role('table').default([]).description('该群违禁词白名单:消息只要命中其中任意一个关键词,就整条跳过违禁词评分(用于校学生会招新等允许的宣传场景)。'),
37
43
  strongKeywords: Schema.array(String).role('table').description('该群强关键词(留空则跟随全局设置)。命中后无视白名单豁免,用于堵住「附一个白名单词即可绕过管控」的漏洞。'),
@@ -64,13 +70,18 @@ export const Config = Schema.intersect([
64
70
  memoryPerScope: Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
65
71
  memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
66
72
  memoryAutoLearn: Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
67
- memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
73
+ memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
68
74
  memoryLearnIdleHours: Schema.natural().min(1).max(72).default(8).description('空闲兜底:距最后一条消息超过这么多小时且期间有新消息,就归纳一次。一直没新消息则不触发。'),
69
75
  memoryLearnThresholdScale: Schema.number().min(1).max(10).step(0.5).default(1).description('归纳阈值 = aiContextWindow × 该倍数。填 1 表示攒满一个上下文窗口就归纳。'),
70
76
  memoryLearnMaxChars: Schema.natural().min(40).max(300).default(150).description('单条自动记忆的字数上限。'),
71
77
  memoryLearnPushBack: Schema.boolean().default(true).description('归纳后把结果回推到原会话:私聊发私聊、群聊发对应群。'),
72
78
  memoryLearnDuplicateThreshold: Schema.number().min(0.3).max(0.95).step(0.05).default(0.55).description('与已有记忆相似度超过该值就跳过,避免同一件事反复记。'),
73
79
  memoryLearnDailyLimit: Schema.natural().min(1).max(200).default(30).description('每个作用域每天最多归纳几次,防止刷模型额度。'),
80
+ memoryLearnConsolidate: Schema.boolean().default(true).description('自动归纳压缩:每累计 N 条就合并成一条更短的记忆,避免记忆越堆越长、反复占用提示词。'),
81
+ memoryLearnConsolidateEvery: Schema.natural().min(2).max(20).default(5).description('每多少条自动记忆压缩一次(默认 5)。'),
82
+ memoryLearnMaxEntries: Schema.natural().min(1).max(100).default(15).description('自动归纳记忆的条数上限(不含手动 [memory] 保存的内容);超过后会强制压缩。'),
83
+ memoryLearnConsolidateMaxChars: Schema.natural().min(40).max(300).default(90).description('压缩后单条记忆的字数上限。'),
84
+ memoryLearnModel: Schema.string().default('').description('自动归纳/压缩使用的模型(留空沿用 aiModel)。可用更便宜的模型降低开销。'),
74
85
  }).description('记忆库'),
75
86
  Schema.object({
76
87
  enableBlacklist: Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
@@ -119,7 +130,10 @@ export const Config = Schema.intersect([
119
130
  aiBaseUrl: Schema.string().default('https://api.openai.com/v1').description('接口基础地址(OpenAI 兼容模式需以 /v1 结尾;Gemini 模式可留默认)。'),
120
131
  aiModel: Schema.string().default('gpt-4o-mini').description('模型名称,如 gpt-4o-mini / doubao-1.5-lite / gemini-2.0-flash。'),
121
132
  aiAgentName: Schema.string().default('bot').description('默认智能体自称(可在配置页修改)。'),
122
- aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('被 @ 后两次回复的最小间隔(秒),防止连续 @ 刷屏。'),
133
+ aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('(兼容字段)旧的 @ 冷却;现在所有模型调用统一走 aiMinReplyIntervalSeconds。'),
134
+ aiCooldownNotice: Schema.boolean().default(true).description('被 @ 但处于模型调用冷却时,是否在群里提示还剩多久(纯本地消息,不调用模型)。'),
135
+ aiCooldownNoticeText: Schema.string().default('还在冷却,{seconds} 秒后再叫我。').description('冷却提示文案,可用 {seconds} 与 {minutes} 占位。'),
136
+ aiCooldownNoticeIntervalSeconds: Schema.natural().min(0).max(600).default(20).description('同一群两次冷却提示的最小间隔(秒),防止连续 @ 刷屏;0 = 不限制。'),
123
137
  aiIdleTopicMinutes: Schema.natural().min(0).max(1440).default(120).description('群内无消息多少分钟后主动抛话题;0=关闭。'),
124
138
  aiIdleTopicMinHour: Schema.natural().min(0).max(23).default(9).description('主动话题允许的最早小时(0-23)。'),
125
139
  aiIdleTopicMaxHour: Schema.natural().min(0).max(24).default(23).description('主动话题允许的最晚小时(不含)。'),
@@ -138,8 +152,12 @@ export const Config = Schema.intersect([
138
152
  ]).role('radio').default('hybrid').description('AI 触发策略:threshold 只看消息数、random 只看概率、hybrid 两者都要满足。@点名与点名后跟随会越过这些闸门。是否真正接话由模型在回复时用 <pass/> 自行决定。'),
139
153
  aiMessageThreshold: Schema.natural().default(16).description('阈值触发所需累计消息数。threshold / hybrid 模式下未达此数一律不触发;计数器在模型给出回复或主动放弃后清零。'),
140
154
  aiRandomReplyProbability: Schema.percent().default(0.08).description('随机触发概率(每条消息掷一次骰)。random / hybrid 模式下未掷中直接跳过,不会调用 AI 接口。填 0 等同于关闭随机触发。'),
155
+ aiPseudoRandom: Schema.boolean().default(true).description('伪随机:随机触发没命中时,下一次概率按步长累加(命中后归零),加到 1 时必定回复,避免真随机长期不触发。'),
156
+ aiPseudoRandomStep: Schema.number().min(0).max(1).step(0.001).default(0.01).description('伪随机每次未命中增加的概率(默认 0.01 = 1%)。只在真正掷骰且未命中时累加,冷却/阈值跳过不算。'),
141
157
  aiMinReplyIntervalSeconds: Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
142
158
  aiContextWindow: Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
159
+ aiContextMaxChars: Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
160
+ aiStyleMaxChars: Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
143
161
  aiTemperature: Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),
144
162
  aiMaxOutputTokens: Schema.natural().default(400).description('AI 最大输出 token 数。群聊一句话不需要太大,过大会增加延迟。'),
145
163
  aiMaxReplyChars: Schema.natural().min(20).max(500).default(120).description('单条回复的最大字符数,超出会在句末截断。'),
package/src/service.js CHANGED
@@ -889,6 +889,42 @@ class QQGroupManagerService extends koishi_1.Service {
889
889
  return block;
890
890
  });
891
891
  }
892
+ /**
893
+ * 自动归纳专用写入:追加一条新记忆,并可同时删掉若干旧条目。
894
+ * 用于「每 N 条压缩成 1 条」——remove 里的旧条目会被新条目替换。
895
+ */
896
+ async commitAutoMemory(scope, payload) {
897
+ const add = String(payload && payload.add || '').trim();
898
+ if (!add)
899
+ return null;
900
+ const remove = new Set((payload && payload.remove || [])
901
+ .map((item) => String(item || '').trim())
902
+ .filter(Boolean));
903
+ const label = String(payload && payload.label || '自动归纳');
904
+ return this.runMemoryWriteLocked(async () => {
905
+ const now = new Date();
906
+ const stamp = now.toLocaleString('zh-CN', { hour12: false });
907
+ const block = `## ${stamp} · ${label}\n${add}`;
908
+ const existing = (await this.readMemoryFile(scope)).trim();
909
+ const blocks = this.extractMemoryBlocks(existing);
910
+ const kept = [];
911
+ let insertAt = -1;
912
+ for (const item of blocks) {
913
+ if (remove.has(item)) {
914
+ if (insertAt < 0)
915
+ insertAt = kept.length;
916
+ continue;
917
+ }
918
+ kept.push(item);
919
+ }
920
+ if (insertAt < 0)
921
+ insertAt = kept.length;
922
+ kept.splice(insertAt, 0, block);
923
+ const next = kept.length ? `${kept.join('\n\n---\n\n')}\n` : `${block}\n`;
924
+ await this.writeMemoryFile(next, scope);
925
+ return block;
926
+ });
927
+ }
892
928
  async searchMemory(keyword, limit = 8, scope) {
893
929
  const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
894
930
  const kw = String(keyword || '').trim();
@@ -2174,6 +2210,12 @@ class QQGroupManagerService extends koishi_1.Service {
2174
2210
  }
2175
2211
  await session.send(koishi_1.h.text(text));
2176
2212
  }
2213
+ /** 系统提示(例如「冷却中」),不引用原消息、不写入 AI 上下文 */
2214
+ async sendNotice(session, text) {
2215
+ if (!text)
2216
+ return;
2217
+ await session.send(koishi_1.h.text(String(text)));
2218
+ }
2177
2219
  extractTextForFilter(session) {
2178
2220
  const raw = (session.content ?? '')
2179
2221
  .replace(/<[^>]+>/g, ' ')