@nestim/koishi-plugin-qq-group-manager 1.3.0 → 1.4.0

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/hooks.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * AI 扩展钩子:让外部插件给提示词追加“风格段”,并在发送前过滤输出。
3
3
  *
4
4
  * 设计目标:
5
- * - 只暴露两个最小能力,不把引擎内部结构漏出去;
5
+ * - 只暴露最小能力,不把引擎内部结构漏出去;
6
6
  * - 任何钩子抛错都不能影响正常回复(记录日志后继续);
7
7
  * - 输出过滤器返回 null 表示“这条不要发”(按 pass 处理);
8
8
  * - version 用于外部插件做兼容检查。
@@ -21,15 +21,46 @@ export interface AiAfterReplyContext extends AiHookContext {
21
21
  /** 已经发送并写入上下文的最终文本 */
22
22
  text: string;
23
23
  }
24
+
24
25
  export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
25
26
 
27
+ /** 一条被挤出上下文的消息。字段与 ChatRecord 对齐,但只挑外部需要的部分。 */
28
+ export interface EvictedRecord {
29
+ id: string;
30
+ userId: string;
31
+ name: string;
32
+ role?: string;
33
+ text: string;
34
+ self: boolean;
35
+ at: number;
36
+ command?: boolean;
37
+ }
38
+
39
+ /** 上下文挤出事件:一次可能挤掉多条。 */
40
+ export interface ContextEvictedContext {
41
+ /** 群号;私聊时为空字符串 */
42
+ groupId: string;
43
+ /** 会话类型 */
44
+ kind: 'group' | 'private';
45
+ /** 作用域 ID:群聊=群号,私聊=对方 QQ 号 */
46
+ scopeId: string;
47
+ session?: any;
48
+ /** 本次被挤出的消息,按时间先后排列 */
49
+ evicted: EvictedRecord[];
50
+ /** 当前上下文窗口大小 */
51
+ window: number;
52
+ }
53
+
54
+ export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
55
+
26
56
  export class AiHookRegistry {
27
- /** 钩子接口版本;外部插件应检查 >= 1 */
28
- readonly version = 1;
57
+ /** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
58
+ readonly version = 2;
29
59
 
30
60
  private sections = new Set<PromptSectionProvider>();
31
61
  private filters = new Set<OutputFilter>();
32
62
  private afterReplyHandlers = new Set<AfterReplyHandler>();
63
+ private evictedHandlers = new Set<ContextEvictedHandler>();
33
64
 
34
65
  constructor(private logger?: any) {}
35
66
 
@@ -49,6 +80,15 @@ export class AiHookRegistry {
49
80
  return () => this.afterReplyHandlers.delete(handler);
50
81
  }
51
82
 
83
+ /**
84
+ * 上下文挤出消息时触发(2.0+)。
85
+ * 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
86
+ */
87
+ registerContextEvicted(handler: ContextEvictedHandler): () => void {
88
+ this.evictedHandlers.add(handler);
89
+ return () => this.evictedHandlers.delete(handler);
90
+ }
91
+
52
92
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
53
93
  async collectSections(ctx: AiHookContext): Promise<string[]> {
54
94
  const out: string[] = [];
@@ -88,4 +128,16 @@ export class AiHookRegistry {
88
128
  }
89
129
  }
90
130
  }
131
+
132
+ /** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
133
+ async runContextEvicted(ctx: ContextEvictedContext): Promise<void> {
134
+ if (!this.evictedHandlers.size) return;
135
+ for (const handler of this.evictedHandlers) {
136
+ try {
137
+ await handler(ctx);
138
+ } catch (error) {
139
+ this.logger?.warn?.(`[ai-hooks] context-evicted failed: ${String(error)}`);
140
+ }
141
+ }
142
+ }
91
143
  }
package/src/ai/state.ts CHANGED
@@ -47,14 +47,17 @@ export class GroupState {
47
47
  followup: FollowupState | null = null;
48
48
  seen = new Map<string, number>();
49
49
 
50
- trim(window: number): void {
50
+ /** 挤压上下文,返回被挤出的消息(按时间先后)。 */
51
+ trim(window: number): ChatRecord[] {
51
52
  const max = Math.max(6, window || 24);
52
- if (this.records.length > max) this.records.splice(0, this.records.length - max);
53
+ if (this.records.length <= max) return [];
54
+ return this.records.splice(0, this.records.length - max);
53
55
  }
54
56
 
55
- push(record: ChatRecord, window: number): void {
57
+ /** @returns 本次被挤出的消息,供外部做归纳 */
58
+ push(record: ChatRecord, window: number): ChatRecord[] {
56
59
  this.records.push(record);
57
- this.trim(window);
60
+ return this.trim(window);
58
61
  }
59
62
 
60
63
  /** 事件去重:同一 messageId 15 秒内只处理一次 */
package/src/index.ts CHANGED
@@ -59,9 +59,12 @@ export const Config = Schema.intersect([
59
59
  autoViolationWindowMinutes: Schema.natural().default(60).description('违规计数统计窗口(分钟):窗口内连续违规才累计,超时未违规则重新计数。'),
60
60
  }).description('自动管控'),
61
61
  Schema.object({
62
- enableMemory: Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容 保存到 Memory.md,[memory] search 关键词 查询、[memory] delete 关键词 删除,AI 回复可引用。'),
63
- memoryFileName: Schema.string().default('Memory.md').description('记忆库文件名(保存在 Koishi 数据目录)。请直接使用控制台左侧「探索器 Explorer」打开该文件查看/编辑记忆库内容。'),
64
- memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容。'),
62
+ enableMemory: Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容 保存,[memory] search 关键词 查询、[memory] delete 关键词 删除,AI 回复可引用。'),
63
+ memoryFileName: Schema.string().default('Memory.md').description('记忆库基础文件名(保存在 Koishi 数据目录)。按作用域分文件时用它作为前缀,例如 Memory.md → Memory_123456_群聊.md。'),
64
+ memoryPerScope: Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
65
+ memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
66
+ memoryAutoLearn: Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
67
+ memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
65
68
  }).description('记忆库'),
66
69
  Schema.object({
67
70
  enableBlacklist: Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
package/src/service.js CHANGED
@@ -762,13 +762,43 @@ class QQGroupManagerService extends koishi_1.Service {
762
762
  }
763
763
  }
764
764
  // ============ 记忆库 ============
765
- getMemoryFilePath() {
765
+ /**
766
+ * 记忆按作用域分文件:
767
+ * 群聊 → Memory_<群号>_群聊.md
768
+ * 私聊 → Memory_<QQ号>_私聊.md
769
+ *
770
+ * scope 为空时回落到旧的单文件(memoryFileName),保持兼容。
771
+ * @param {{kind:'group'|'private', id:string}|null} scope
772
+ */
773
+ getMemoryFilePath(scope) {
766
774
  const base = (this.ctx && this.ctx.baseDir) || process.cwd();
767
- const name = (this.config.memoryFileName || 'Memory.md').trim();
768
- return node_path_1.default.resolve(base, name);
769
- }
770
- async readMemoryFile() {
771
- const p = this.getMemoryFilePath();
775
+ const legacy = (this.config.memoryFileName || 'Memory.md').trim();
776
+ const kind = scope && scope.kind;
777
+ const id = scope && String(scope.id || '').replace(/[^\w.-]/g, '');
778
+ if (!kind || !id) {
779
+ return node_path_1.default.resolve(base, legacy);
780
+ }
781
+ if (this.config.memoryPerScope === false) {
782
+ return node_path_1.default.resolve(base, legacy);
783
+ }
784
+ const label = kind === 'private' ? '私聊' : '群聊';
785
+ // 从旧文件名里取基础名,例如 Memory.md → Memory
786
+ const stem = legacy.replace(/\.md$/i, '') || 'Memory';
787
+ return node_path_1.default.resolve(base, `${stem}_${id}_${label}.md`);
788
+ }
789
+ /** 把 session 归一成作用域;群聊取群号,私聊取对方 QQ 号。 */
790
+ memoryScopeOf(session) {
791
+ if (!session) return null;
792
+ const isDirect = session.isDirect === true || !session.guildId;
793
+ if (isDirect) {
794
+ const uid = String(session.userId || '').trim();
795
+ return uid ? { kind: 'private', id: uid } : null;
796
+ }
797
+ const gid = String(session.guildId || '').trim();
798
+ return gid ? { kind: 'group', id: gid } : null;
799
+ }
800
+ async readMemoryFile(scope) {
801
+ const p = this.getMemoryFilePath(scope);
772
802
  try {
773
803
  return await node_fs_1.default.promises.readFile(p, 'utf8');
774
804
  }
@@ -776,8 +806,8 @@ class QQGroupManagerService extends koishi_1.Service {
776
806
  return '';
777
807
  }
778
808
  }
779
- async writeMemoryFile(content) {
780
- const p = this.getMemoryFilePath();
809
+ async writeMemoryFile(content, scope) {
810
+ const p = this.getMemoryFilePath(scope);
781
811
  await node_fs_1.default.promises.writeFile(p, String(content), 'utf8');
782
812
  }
783
813
  extractMemoryBlocks(content) {
@@ -797,32 +827,40 @@ class QQGroupManagerService extends koishi_1.Service {
797
827
  this._memoryWriteLock = run.then(() => undefined, () => undefined);
798
828
  return run;
799
829
  }
800
- async saveMemoryToFile(userId, content) {
830
+ /**
831
+ * 追加一条记忆。
832
+ * @param {string} userId 写入者(旧字段,保留用于标记)
833
+ * @param {string} content 记忆正文
834
+ * @param {{kind:'group'|'private', id:string}|null} scope 作用域;为空则写旧单文件
835
+ * @param {string} [label] 自定义来源标记,例如「自动归纳」
836
+ */
837
+ async saveMemoryToFile(userId, content, scope, label) {
801
838
  return this.runMemoryWriteLocked(async () => {
802
839
  const now = new Date();
803
840
  const stamp = now.toLocaleString('zh-CN', { hour12: false });
804
- const block = `## ${stamp} · 用户 ${userId || 'unknown'}\n${String(content).trim()}`;
805
- const existing = (await this.readMemoryFile()).trim();
841
+ const who = label || `用户 ${userId || 'unknown'}`;
842
+ const block = `## ${stamp} · ${who}\n${String(content).trim()}`;
843
+ const existing = (await this.readMemoryFile(scope)).trim();
806
844
  const next = existing ? `${existing}\n\n---\n\n${block}\n` : `${block}\n`;
807
- await this.writeMemoryFile(next);
845
+ await this.writeMemoryFile(next, scope);
808
846
  return block;
809
847
  });
810
848
  }
811
- async searchMemory(keyword, limit = 8) {
812
- const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
849
+ async searchMemory(keyword, limit = 8, scope) {
850
+ const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
813
851
  const kw = String(keyword || '').trim();
814
852
  if (!kw)
815
853
  return blocks.slice(-limit);
816
854
  return blocks.filter((b) => b.includes(kw)).slice(-limit);
817
855
  }
818
856
  /** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
819
- async deleteMemoryByKeyword(keyword) {
857
+ async deleteMemoryByKeyword(keyword, scope) {
820
858
  const kw = String(keyword ?? '').trim();
821
859
  if (!kw)
822
860
  return { ok: false, removed: 0, message: '关键词为空。' };
823
861
  // 同样走写锁:删除与保存并发时不会互相覆盖
824
862
  return this.runMemoryWriteLocked(async () => {
825
- const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
863
+ const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
826
864
  if (!blocks.length)
827
865
  return { ok: false, removed: 0, message: '记忆库为空。' };
828
866
  const kept = blocks.filter((b) => !b.includes(kw));
@@ -830,7 +868,7 @@ class QQGroupManagerService extends koishi_1.Service {
830
868
  if (!removed)
831
869
  return { ok: false, removed: 0, message: `未找到包含「${kw}」的记忆` };
832
870
  const content = kept.length ? kept.join('\n\n---\n\n') + '\n' : '';
833
- await this.writeMemoryFile(content);
871
+ await this.writeMemoryFile(content, scope);
834
872
  return { ok: true, removed, message: `已删除 ${removed} 条` };
835
873
  });
836
874
  }
@@ -2859,17 +2897,19 @@ class QQGroupManagerService extends koishi_1.Service {
2859
2897
  await session.send(this.styleText('请给出要删除的关键词。'));
2860
2898
  return true;
2861
2899
  }
2862
- const results = await this.searchMemory(keyword, 8);
2900
+ const mscope = this.memoryScopeOf(session);
2901
+ const results = await this.searchMemory(keyword, 8, mscope);
2863
2902
  if (!results.length) {
2864
2903
  await session.send(this.styleText(`删除失败,未找到包含「${keyword}」的记忆。`));
2865
2904
  return true;
2866
2905
  }
2867
- const r = await this.deleteMemoryByKeyword(keyword);
2906
+ const r = await this.deleteMemoryByKeyword(keyword, mscope);
2868
2907
  await session.send(this.styleText(r.ok ? `已删除 ${r.removed} 条记忆。` : `删除失败:${r.message}`));
2869
2908
  return true;
2870
2909
  }
2871
2910
  if (/^(?:list|all)$/i.test(sub)) {
2872
- const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
2911
+ const mscope = this.memoryScopeOf(session);
2912
+ const blocks = this.extractMemoryBlocks(await this.readMemoryFile(mscope));
2873
2913
  if (!blocks.length) {
2874
2914
  await session.send(this.styleText('记忆库为空。'));
2875
2915
  return true;
@@ -2882,7 +2922,8 @@ class QQGroupManagerService extends koishi_1.Service {
2882
2922
  const queryMatch = sub.match(/^(?:search|query|find)\s*[::]?\s*([\s\S]*)$/i);
2883
2923
  if (queryMatch) {
2884
2924
  const keyword = queryMatch[1].trim();
2885
- const results = await this.searchMemory(keyword, 8);
2925
+ const mscope = this.memoryScopeOf(session);
2926
+ const results = await this.searchMemory(keyword, 8, mscope);
2886
2927
  if (!results.length) {
2887
2928
  await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
2888
2929
  return true;
@@ -2894,7 +2935,8 @@ class QQGroupManagerService extends koishi_1.Service {
2894
2935
  }
2895
2936
  // 保存
2896
2937
  try {
2897
- await this.saveMemoryToFile(session.userId, sub);
2938
+ const mscope = this.memoryScopeOf(session);
2939
+ await this.saveMemoryToFile(session.userId, sub, mscope);
2898
2940
  await session.send(this.styleText('已记住。'));
2899
2941
  this.logCommandResult('memory-save', { ok: true, message: 'memory saved' }, session, { content: sub });
2900
2942
  }