@nestim/koishi-plugin-qq-group-manager 1.4.10 → 1.4.12
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/CHANGELOG.md +44 -0
- package/lib/ai/engine.d.ts +11 -5
- package/lib/ai/engine.js +256 -70
- package/lib/ai/hooks.d.ts +10 -2
- package/lib/ai/hooks.js +23 -2
- package/lib/ai/learn.d.ts +14 -2
- package/lib/ai/learn.js +94 -7
- package/lib/ai/runtime.d.ts +2 -0
- package/lib/ai/runtime.js +8 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -1
- package/lib/service.js +3 -1
- package/package.json +1 -1
- package/readme.md +25 -3
- package/src/ai/engine.ts +262 -71
- package/src/ai/hooks.ts +28 -5
- package/src/ai/learn.ts +95 -7
- package/src/ai/runtime.ts +9 -0
- package/src/index.ts +2 -1
- package/src/service.js +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,50 @@
|
|
|
2
2
|
|
|
3
3
|
本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
4
4
|
|
|
5
|
+
## 1.4.12
|
|
6
|
+
|
|
7
|
+
### 改进
|
|
8
|
+
|
|
9
|
+
- **主动话题结合上下文、记忆与联网搜索**:
|
|
10
|
+
- 提示词带当前日期、星期、时间与季节(如“2026年11月18日星期三 18:51(冬)”),
|
|
11
|
+
并明确要求不要提与当前季节/时间不符的内容;
|
|
12
|
+
- 带上该群最近 12 条聊天,要求优先接着最近的话题或梗往下说,而不是凭空抛一个无关话题;
|
|
13
|
+
- 按最近聊天检索相关记忆,一起放进提示词;
|
|
14
|
+
- 新增 `aiIdleTopicWebSearch`(默认开):用最近一句做 query;没有上下文就搜当天热点。
|
|
15
|
+
结果不相关会自动忽略,搜不到也不影响发话题。
|
|
16
|
+
|
|
17
|
+
### 记忆分类
|
|
18
|
+
|
|
19
|
+
- **自动归纳按类别分开存**:一条记忆只属于一类,标题格式为
|
|
20
|
+
`## 2026/11/18 18:51:00 · 自动归纳 · 人物关系`。
|
|
21
|
+
- 类别:人物关系 / 偏好立场 / 群内黑话 / 长期话题 / 约定事件 / 其他;
|
|
22
|
+
- 一次归纳最多产出 3 条,同类最多 2 条,不再把不同类的事实塞进一句;
|
|
23
|
+
- 压缩只在**同分类**内进行(每 `memoryLearnConsolidateEvery` 条同类压 1 条);
|
|
24
|
+
总数超过 `memoryLearnMaxEntries` 时优先压缩条数最多的分类;
|
|
25
|
+
- 旧记忆没有分类,自动按「其他」处理,不丢数据;
|
|
26
|
+
- 记忆注入时只带正文,不再把 `## 时间 · 自动归纳` 标题塞进提示词。
|
|
27
|
+
|
|
28
|
+
## 1.4.11
|
|
29
|
+
|
|
30
|
+
### 修复
|
|
31
|
+
|
|
32
|
+
- **联网搜索命中缓存也会消耗每小时配额**。之前配额计数在缓存检查之前,
|
|
33
|
+
同一个 query 在缓存有效期内重复出现,明明没有发请求也会扣次数,很快就撞上 `rate-limit`。
|
|
34
|
+
现在先查缓存,命中直接返回、不占配额;换 query 仍受 `aiWebSearchMaxPerHour` 限制。
|
|
35
|
+
被限流时日志会带上 `limit` 和 `resetIn`(还有多少秒恢复),方便区分“配额用完”和“接口故障”。
|
|
36
|
+
|
|
37
|
+
### 新增
|
|
38
|
+
|
|
39
|
+
- **aiHooks v3:`registerPersonaOverride(provider)`**。外部插件可以按群覆盖主插件默认人设 /
|
|
40
|
+
系统提示词(qqgm-chat-style 的分群提示词用的就是这个)。
|
|
41
|
+
|
|
42
|
+
- **`qqgmAiRuntime.images(session)`**。外部插件(qqgm-private)可以复用主插件的视觉链路,
|
|
43
|
+
把消息里的图片转成 data URL 后一起发给模型。
|
|
44
|
+
|
|
45
|
+
### 说明
|
|
46
|
+
|
|
47
|
+
- 不调用新接口的旧插件行为不变;`hooks.version` 升到 3。
|
|
48
|
+
|
|
5
49
|
## 1.4.10
|
|
6
50
|
|
|
7
51
|
### 新功能
|
package/lib/ai/engine.d.ts
CHANGED
|
@@ -143,13 +143,14 @@ export declare class AiEngine {
|
|
|
143
143
|
/** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
|
|
144
144
|
private summarizeRecords;
|
|
145
145
|
/**
|
|
146
|
-
*
|
|
147
|
-
* -
|
|
148
|
-
* -
|
|
146
|
+
* 自动归纳写入策略(分类版):
|
|
147
|
+
* - 记忆按分类存,一条只属于一类;
|
|
148
|
+
* - 同一分类累计 N 条(默认 5)时,把最早的 N-1 条 + 本次压成 1 条;
|
|
149
|
+
* - 自动记忆总数超过上限(默认 15)时,压缩条数最多的分类里最老的一组;
|
|
149
150
|
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
150
151
|
*/
|
|
151
152
|
private saveLearnedMemory;
|
|
152
|
-
/**
|
|
153
|
+
/** 调模型把若干条同分类自动记忆压成一条更短的 */
|
|
153
154
|
private consolidateMemories;
|
|
154
155
|
private findBot;
|
|
155
156
|
private isMention;
|
|
@@ -169,7 +170,7 @@ export declare class AiEngine {
|
|
|
169
170
|
handle(session: any): Promise<void>;
|
|
170
171
|
/** 供外部插件(如私聊插件)复用同一个模型 provider。 */
|
|
171
172
|
chat(request: any): Promise<import("./provider").ChatResult>;
|
|
172
|
-
/**
|
|
173
|
+
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
173
174
|
idleTopic(groupId: string): Promise<string>;
|
|
174
175
|
/** 需要时调用 DeepSeek Search API;失败/不支持/没结果都返回空串,继续普通回复。 */
|
|
175
176
|
private webSearch;
|
|
@@ -179,6 +180,11 @@ export declare class AiEngine {
|
|
|
179
180
|
private readForwards;
|
|
180
181
|
private recentImageRecords;
|
|
181
182
|
private collectImages;
|
|
183
|
+
/**
|
|
184
|
+
* 供外部插件(qqgm-private)复用:把一条私聊消息里的图片解析成 data URL。
|
|
185
|
+
* 不做上下文回看,只看当前消息本身。
|
|
186
|
+
*/
|
|
187
|
+
resolveSessionImages(session: any): Promise<string[]>;
|
|
182
188
|
private platformAllowed;
|
|
183
189
|
private log;
|
|
184
190
|
/** 供指令/调试使用 */
|
package/lib/ai/engine.js
CHANGED
|
@@ -99,6 +99,33 @@ function clipReply(text, maxChars) {
|
|
|
99
99
|
return slice.slice(0, boundary + 1);
|
|
100
100
|
return `${slice}…`;
|
|
101
101
|
}
|
|
102
|
+
function seasonOfMonth(month) {
|
|
103
|
+
if (month >= 3 && month <= 5)
|
|
104
|
+
return '春';
|
|
105
|
+
if (month >= 6 && month <= 8)
|
|
106
|
+
return '夏';
|
|
107
|
+
if (month >= 9 && month <= 11)
|
|
108
|
+
return '秋';
|
|
109
|
+
return '冬';
|
|
110
|
+
}
|
|
111
|
+
/** 主动话题用:把当前时间渲染成“2026年1月15日星期四 10:00(冬)” */
|
|
112
|
+
function formatNowText(date) {
|
|
113
|
+
const formatted = new Intl.DateTimeFormat('zh-CN', {
|
|
114
|
+
timeZone: 'Asia/Shanghai',
|
|
115
|
+
year: 'numeric',
|
|
116
|
+
month: 'long',
|
|
117
|
+
day: 'numeric',
|
|
118
|
+
weekday: 'long',
|
|
119
|
+
hour: '2-digit',
|
|
120
|
+
minute: '2-digit',
|
|
121
|
+
hour12: false,
|
|
122
|
+
}).format(date);
|
|
123
|
+
const month = Number(new Intl.DateTimeFormat('en-US', {
|
|
124
|
+
timeZone: 'Asia/Shanghai',
|
|
125
|
+
month: 'numeric',
|
|
126
|
+
}).format(date));
|
|
127
|
+
return `${formatted}(${seasonOfMonth(month)})`;
|
|
128
|
+
}
|
|
102
129
|
class AiEngine {
|
|
103
130
|
state;
|
|
104
131
|
/** 外部插件扩展点:提示词风格段 + 输出过滤 */
|
|
@@ -648,7 +675,7 @@ class AiEngine {
|
|
|
648
675
|
return;
|
|
649
676
|
if (cfg.memoryLearnPushBack === false)
|
|
650
677
|
return;
|
|
651
|
-
const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}
|
|
678
|
+
const text = (saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`).slice(0, 300);
|
|
652
679
|
try {
|
|
653
680
|
if (kind === "private") {
|
|
654
681
|
const bot = (kind === "private" && session?.bot) || null;
|
|
@@ -686,7 +713,7 @@ class AiEngine {
|
|
|
686
713
|
system: prompt.system,
|
|
687
714
|
user: prompt.user,
|
|
688
715
|
temperature: 0.3,
|
|
689
|
-
maxTokens:
|
|
716
|
+
maxTokens: 800,
|
|
690
717
|
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
691
718
|
});
|
|
692
719
|
if (!result || !result.ok) {
|
|
@@ -703,54 +730,66 @@ class AiEngine {
|
|
|
703
730
|
return null;
|
|
704
731
|
}
|
|
705
732
|
const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
|
|
706
|
-
|
|
707
|
-
if (!
|
|
733
|
+
const entries = (0, learn_1.parseSummaryEntries)(raw, maxChars);
|
|
734
|
+
if (!entries.length)
|
|
708
735
|
return null;
|
|
709
|
-
//
|
|
736
|
+
// 去重:分别和已有正文比较
|
|
710
737
|
let existing = [];
|
|
711
738
|
try {
|
|
712
739
|
const content = await this.host.readMemoryFile(scope);
|
|
713
|
-
existing = String(content || "")
|
|
714
|
-
.
|
|
715
|
-
.
|
|
716
|
-
.filter(Boolean)
|
|
717
|
-
.map((b) => b.split("\n").slice(1).join("\n").trim() || b);
|
|
740
|
+
existing = (0, memory_1.splitMemoryBlocks)(String(content || ""))
|
|
741
|
+
.map((item) => (0, learn_1.memoryBlockBody)(item.text))
|
|
742
|
+
.filter(Boolean);
|
|
718
743
|
}
|
|
719
744
|
catch {
|
|
720
745
|
existing = [];
|
|
721
746
|
}
|
|
722
747
|
const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
|
|
723
|
-
|
|
748
|
+
const accepted = entries.filter((entry) => !(0, learn_1.isDuplicate)(entry.text, existing, threshold));
|
|
749
|
+
if (!accepted.length) {
|
|
724
750
|
this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
|
|
725
751
|
return null;
|
|
726
752
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
753
|
+
const savedList = [];
|
|
754
|
+
for (const entry of accepted) {
|
|
755
|
+
try {
|
|
756
|
+
savedList.push(await this.saveLearnedMemory(kind, scope, entry.text, entry.category));
|
|
757
|
+
}
|
|
758
|
+
catch (error) {
|
|
759
|
+
this.host.logger?.warn?.(`[memory-learn] 写入失败(${entry.category}): ${String(error)}`);
|
|
760
|
+
}
|
|
731
761
|
}
|
|
732
|
-
|
|
733
|
-
this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
|
|
762
|
+
if (!savedList.length)
|
|
734
763
|
return null;
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
764
|
+
this.learnDaily.set(dailyKey, used + 1);
|
|
765
|
+
const consolidated = savedList.some((item) => item.consolidated);
|
|
766
|
+
const removed = savedList.reduce((sum, item) => sum + item.removed, 0);
|
|
767
|
+
const categories = savedList.map((item) => item.category).join("、");
|
|
768
|
+
this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${savedList.length} 条,分类:${categories}`
|
|
769
|
+
+ (consolidated ? `,压缩 ${removed} 条旧记忆` : ""));
|
|
770
|
+
return {
|
|
771
|
+
text: savedList.map((item) => `${item.category}:${item.text}`).join(";"),
|
|
772
|
+
consolidated,
|
|
773
|
+
removed,
|
|
774
|
+
entries: savedList.length,
|
|
775
|
+
};
|
|
739
776
|
}
|
|
740
777
|
/**
|
|
741
|
-
*
|
|
742
|
-
* -
|
|
743
|
-
* -
|
|
778
|
+
* 自动归纳写入策略(分类版):
|
|
779
|
+
* - 记忆按分类存,一条只属于一类;
|
|
780
|
+
* - 同一分类累计 N 条(默认 5)时,把最早的 N-1 条 + 本次压成 1 条;
|
|
781
|
+
* - 自动记忆总数超过上限(默认 15)时,压缩条数最多的分类里最老的一组;
|
|
744
782
|
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
745
783
|
*/
|
|
746
|
-
async saveLearnedMemory(kind, scope, text) {
|
|
784
|
+
async saveLearnedMemory(kind, scope, text, category = "其他") {
|
|
747
785
|
const cfg = this.config || {};
|
|
748
786
|
const host = this.host;
|
|
787
|
+
const cat = (0, learn_1.normalizeMemoryCategory)(category);
|
|
749
788
|
const canConsolidate = cfg.memoryLearnConsolidate !== false
|
|
750
789
|
&& typeof host.commitAutoMemory === "function";
|
|
751
790
|
if (!canConsolidate) {
|
|
752
|
-
await host.saveMemoryToFile("", text, scope, learn_1.AUTO_MEMORY_LABEL);
|
|
753
|
-
return { text, consolidated: false, removed: 0 };
|
|
791
|
+
await host.saveMemoryToFile("", text, scope, `${learn_1.AUTO_MEMORY_LABEL} · ${cat}`);
|
|
792
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
754
793
|
}
|
|
755
794
|
const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
|
|
756
795
|
const maxEntries = Math.max(1, Number(cfg.memoryLearnMaxEntries) || 15);
|
|
@@ -765,40 +804,101 @@ class AiEngine {
|
|
|
765
804
|
catch {
|
|
766
805
|
autoBlocks = [];
|
|
767
806
|
}
|
|
768
|
-
const
|
|
769
|
-
const
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
807
|
+
const sameCategory = autoBlocks.filter((block) => (0, learn_1.memoryBlockCategory)(block) === cat);
|
|
808
|
+
const projectedSame = sameCategory.length + 1;
|
|
809
|
+
const reachedBatch = projectedSame >= every;
|
|
810
|
+
const reachedCap = autoBlocks.length + 1 > maxEntries && autoBlocks.length > 0;
|
|
811
|
+
// 常规批量:同分类最早的 N-1 条 + 本次,正好 N 条压成 1 条
|
|
812
|
+
if (reachedBatch) {
|
|
813
|
+
const take = Math.max(1, Math.min(every - 1, sameCategory.length));
|
|
814
|
+
const remove = sameCategory.slice(0, take);
|
|
815
|
+
let stored = text;
|
|
816
|
+
let consolidated = false;
|
|
817
|
+
try {
|
|
818
|
+
const merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
819
|
+
if (merged) {
|
|
820
|
+
stored = merged;
|
|
821
|
+
consolidated = true;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
catch (error) {
|
|
825
|
+
this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
|
|
785
826
|
}
|
|
827
|
+
await host.commitAutoMemory(scope, {
|
|
828
|
+
add: stored,
|
|
829
|
+
remove: consolidated ? remove : [],
|
|
830
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
831
|
+
category: cat,
|
|
832
|
+
});
|
|
833
|
+
return { text: stored, consolidated, removed: consolidated ? remove.length : 0, category: cat };
|
|
786
834
|
}
|
|
787
|
-
|
|
788
|
-
|
|
835
|
+
// 超过总上限:先压缩“条数最多”的分类里最老的一组(不带本次新记忆),再追加本次
|
|
836
|
+
if (reachedCap) {
|
|
837
|
+
const byCategory = new Map();
|
|
838
|
+
for (const block of autoBlocks) {
|
|
839
|
+
const key = (0, learn_1.memoryBlockCategory)(block);
|
|
840
|
+
const list = byCategory.get(key) || [];
|
|
841
|
+
list.push(block);
|
|
842
|
+
byCategory.set(key, list);
|
|
843
|
+
}
|
|
844
|
+
let targetCategory = "";
|
|
845
|
+
let targetBlocks = [];
|
|
846
|
+
for (const [key, list] of byCategory) {
|
|
847
|
+
if (list.length >= 2 && list.length > targetBlocks.length) {
|
|
848
|
+
targetCategory = key;
|
|
849
|
+
targetBlocks = list;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (targetBlocks.length) {
|
|
853
|
+
const take = Math.max(1, Math.min(every - 1, targetBlocks.length));
|
|
854
|
+
const remove = targetBlocks.slice(0, take);
|
|
855
|
+
if (targetCategory === cat) {
|
|
856
|
+
// 同一分类:把本次新记忆一起并进去
|
|
857
|
+
let merged = "";
|
|
858
|
+
try {
|
|
859
|
+
merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
860
|
+
}
|
|
861
|
+
catch (error) {
|
|
862
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
863
|
+
}
|
|
864
|
+
if (merged) {
|
|
865
|
+
await host.commitAutoMemory(scope, {
|
|
866
|
+
add: merged,
|
|
867
|
+
remove,
|
|
868
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
869
|
+
category: cat,
|
|
870
|
+
});
|
|
871
|
+
return { text: merged, consolidated: true, removed: remove.length, category: cat };
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
else {
|
|
875
|
+
// 不同分类:只压缩旧的一组,本次仍然单独追加
|
|
876
|
+
try {
|
|
877
|
+
const merged = await this.consolidateMemories(kind, remove, "", maxChars, targetCategory);
|
|
878
|
+
if (merged) {
|
|
879
|
+
await host.commitAutoMemory(scope, {
|
|
880
|
+
add: merged,
|
|
881
|
+
remove,
|
|
882
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
883
|
+
category: targetCategory,
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
catch (error) {
|
|
888
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
789
892
|
}
|
|
790
|
-
await host.commitAutoMemory(scope, {
|
|
791
|
-
|
|
792
|
-
remove: consolidated ? remove : [],
|
|
793
|
-
label: learn_1.AUTO_MEMORY_LABEL,
|
|
794
|
-
});
|
|
795
|
-
return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
|
|
893
|
+
await host.commitAutoMemory(scope, { add: text, label: learn_1.AUTO_MEMORY_LABEL, category: cat });
|
|
894
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
796
895
|
}
|
|
797
|
-
/**
|
|
798
|
-
async consolidateMemories(kind, blocks, fresh, maxChars) {
|
|
896
|
+
/** 调模型把若干条同分类自动记忆压成一条更短的 */
|
|
897
|
+
async consolidateMemories(kind, blocks, fresh, maxChars, category = "其他") {
|
|
799
898
|
const cfg = this.config || {};
|
|
800
899
|
const marker = `## · ${learn_1.AUTO_MEMORY_LABEL}`;
|
|
801
|
-
const
|
|
900
|
+
const input = fresh ? [...blocks, `${marker}\n${fresh}`] : blocks;
|
|
901
|
+
const prompt = (0, learn_1.buildConsolidatePrompt)(input, { maxChars, kind, category });
|
|
802
902
|
const result = await this.provider.chat({
|
|
803
903
|
system: prompt.system,
|
|
804
904
|
user: prompt.user,
|
|
@@ -927,7 +1027,9 @@ class AiEngine {
|
|
|
927
1027
|
catch {
|
|
928
1028
|
return [];
|
|
929
1029
|
}
|
|
930
|
-
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1030
|
+
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1031
|
+
.map((item) => ({ ...item, text: (0, learn_1.memoryBlockBody)(item.text) }))
|
|
1032
|
+
.filter((item) => item.text);
|
|
931
1033
|
if (!blocks.length)
|
|
932
1034
|
return [];
|
|
933
1035
|
const recent = state.records.slice(-3).map((item) => item.text);
|
|
@@ -1048,10 +1150,11 @@ class AiEngine {
|
|
|
1048
1150
|
mode: 'reply',
|
|
1049
1151
|
};
|
|
1050
1152
|
const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1153
|
+
const personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
1051
1154
|
const webSearch = await this.webSearch(record, session);
|
|
1052
1155
|
const promptInput = {
|
|
1053
1156
|
selfName: this.selfName,
|
|
1054
|
-
persona: this.personaPrompt,
|
|
1157
|
+
persona: personaOverride || this.personaPrompt,
|
|
1055
1158
|
groupId: String(session.guildId),
|
|
1056
1159
|
records: this.clampContext(state.records),
|
|
1057
1160
|
current: record,
|
|
@@ -1174,20 +1277,74 @@ class AiEngine {
|
|
|
1174
1277
|
chat(request) {
|
|
1175
1278
|
return this.provider.chat(request);
|
|
1176
1279
|
}
|
|
1177
|
-
/**
|
|
1280
|
+
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
1178
1281
|
async idleTopic(groupId) {
|
|
1179
1282
|
const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
|
|
1283
|
+
const hookCtx = { session, groupId, mode: 'reply' };
|
|
1180
1284
|
let sections = [];
|
|
1285
|
+
let personaOverride = null;
|
|
1181
1286
|
try {
|
|
1182
|
-
sections = this.clampStyle(await this.hooks.collectSections(
|
|
1287
|
+
sections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1288
|
+
personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
1183
1289
|
}
|
|
1184
1290
|
catch { /* ignore */ }
|
|
1291
|
+
// 最近上下文:优先 onebot:<群号>,兼容其它 platform
|
|
1292
|
+
let state = this.state.peek(`onebot:${groupId}`);
|
|
1293
|
+
if (!state) {
|
|
1294
|
+
for (const [key, value] of this.state.entries()) {
|
|
1295
|
+
if (key.endsWith(`:${groupId}`)) {
|
|
1296
|
+
state = value;
|
|
1297
|
+
break;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
const records = state ? state.records.slice(-12) : [];
|
|
1302
|
+
const contextText = records
|
|
1303
|
+
.map((record) => (0, prompt_1.renderRecordLine)(record, this.selfName))
|
|
1304
|
+
.join('\n');
|
|
1305
|
+
// 相关记忆:用最近几句话做查询;没有上下文就取最近两条
|
|
1306
|
+
let memories = [];
|
|
1307
|
+
try {
|
|
1308
|
+
const scope = typeof this.host.memoryScopeOf === 'function'
|
|
1309
|
+
? this.host.memoryScopeOf(session)
|
|
1310
|
+
: { kind: 'group', id: groupId };
|
|
1311
|
+
const content = await this.host.readMemoryFile(scope);
|
|
1312
|
+
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1313
|
+
.map((item) => ({ ...item, text: (0, learn_1.memoryBlockBody)(item.text) }))
|
|
1314
|
+
.filter((item) => item.text);
|
|
1315
|
+
const queryTexts = records.slice(-4).map((record) => record.text).filter(Boolean);
|
|
1316
|
+
const selected = queryTexts.length
|
|
1317
|
+
? (0, memory_1.selectMemoryBlocks)(blocks, queryTexts, { limit: 3, minScore: 0.12, maxChars: 140 })
|
|
1318
|
+
: blocks.slice(-2);
|
|
1319
|
+
memories = selected.map((item) => item.text);
|
|
1320
|
+
}
|
|
1321
|
+
catch { /* ignore */ }
|
|
1322
|
+
// 联网:用最近一句做 query;没有上下文就问今天的热点
|
|
1323
|
+
let searchSection = '';
|
|
1324
|
+
if (this.config.aiIdleTopicWebSearch !== false) {
|
|
1325
|
+
const lastText = records.length ? String(records[records.length - 1].text || '') : '';
|
|
1326
|
+
const seed = lastText.length >= 4 ? lastText : '今天有什么热点话题';
|
|
1327
|
+
try {
|
|
1328
|
+
searchSection = await this.webSearch({ text: seed }, session, true);
|
|
1329
|
+
}
|
|
1330
|
+
catch { /* ignore */ }
|
|
1331
|
+
}
|
|
1332
|
+
const nowText = formatNowText(new Date(this.now()));
|
|
1185
1333
|
const system = [
|
|
1186
1334
|
`你是 QQ 群 ${groupId} 里的一个普通成员。`,
|
|
1335
|
+
personaOverride || this.personaPrompt,
|
|
1336
|
+
`现在是 ${nowText}。`,
|
|
1187
1337
|
'群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
|
|
1188
|
-
'
|
|
1338
|
+
contextText ? `【最近聊天】\n${contextText}` : '',
|
|
1339
|
+
memories.length ? `【相关记忆】\n${memories.map((item) => `- ${item}`).join('\n')}` : '',
|
|
1340
|
+
searchSection,
|
|
1341
|
+
'要求:',
|
|
1342
|
+
'- 优先接着最近聊天里的话题或梗往下说;没有可接的,再结合当前时间、季节和记忆找话题;',
|
|
1343
|
+
'- 不要提与现在时间、季节不符的内容(按上面给出的日期判断,不要凭印象说夏天/冬天);',
|
|
1344
|
+
'- 联网结果只在确实相关时参考,不相关就忽略,不要编造新闻;',
|
|
1345
|
+
'- 不要问“在吗”,不要提“很久没人说话”,不要自我介绍;',
|
|
1189
1346
|
...sections,
|
|
1190
|
-
].join('\n');
|
|
1347
|
+
].filter(Boolean).join('\n');
|
|
1191
1348
|
const result = await this.provider.chat({
|
|
1192
1349
|
system,
|
|
1193
1350
|
user: '现在发一条主动话题。',
|
|
@@ -1220,23 +1377,31 @@ class AiEngine {
|
|
|
1220
1377
|
if (this.searchUnsupportedUntil > now)
|
|
1221
1378
|
return '';
|
|
1222
1379
|
const groupId = String(session?.guildId || '');
|
|
1223
|
-
|
|
1380
|
+
// 先查缓存:命中缓存不消耗搜索配额
|
|
1381
|
+
const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
|
|
1382
|
+
const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
|
|
1383
|
+
if (cacheMinutes > 0) {
|
|
1384
|
+
const hit = this.searchCache.get(cacheKey);
|
|
1385
|
+
if (hit && now - hit.at < cacheMinutes * 60_000)
|
|
1386
|
+
return hit.section;
|
|
1387
|
+
}
|
|
1388
|
+
const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 30));
|
|
1224
1389
|
if (maxPerHour > 0) {
|
|
1225
1390
|
const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
|
|
1226
1391
|
if (list.length >= maxPerHour) {
|
|
1227
|
-
|
|
1392
|
+
const resetIn = Math.max(1, Math.ceil((list[0] + 3600_000 - now) / 1000));
|
|
1393
|
+
this.log('web-search', {
|
|
1394
|
+
ok: false,
|
|
1395
|
+
reason: 'rate-limit',
|
|
1396
|
+
limit: maxPerHour,
|
|
1397
|
+
resetIn,
|
|
1398
|
+
groupId,
|
|
1399
|
+
}, session);
|
|
1228
1400
|
return '';
|
|
1229
1401
|
}
|
|
1230
1402
|
list.push(now);
|
|
1231
1403
|
this.searchRate.set(groupId, list);
|
|
1232
1404
|
}
|
|
1233
|
-
const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
|
|
1234
|
-
const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
|
|
1235
|
-
if (cacheMinutes > 0) {
|
|
1236
|
-
const hit = this.searchCache.get(cacheKey);
|
|
1237
|
-
if (hit && now - hit.at < cacheMinutes * 60_000)
|
|
1238
|
-
return hit.section;
|
|
1239
|
-
}
|
|
1240
1405
|
const startedAt = this.now();
|
|
1241
1406
|
const outcome = await (0, websearch_1.fetchWebSearch)({
|
|
1242
1407
|
query,
|
|
@@ -1360,6 +1525,27 @@ class AiEngine {
|
|
|
1360
1525
|
return [];
|
|
1361
1526
|
return (0, vision_1.resolveImages)(items, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
|
|
1362
1527
|
}
|
|
1528
|
+
/**
|
|
1529
|
+
* 供外部插件(qqgm-private)复用:把一条私聊消息里的图片解析成 data URL。
|
|
1530
|
+
* 不做上下文回看,只看当前消息本身。
|
|
1531
|
+
*/
|
|
1532
|
+
async resolveSessionImages(session) {
|
|
1533
|
+
if (this.config.aiEnableImageRecognition === false)
|
|
1534
|
+
return [];
|
|
1535
|
+
const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
|
|
1536
|
+
if (!maxCount)
|
|
1537
|
+
return [];
|
|
1538
|
+
let own = [];
|
|
1539
|
+
try {
|
|
1540
|
+
own = this.host.extractImages(session) || [];
|
|
1541
|
+
}
|
|
1542
|
+
catch {
|
|
1543
|
+
own = [];
|
|
1544
|
+
}
|
|
1545
|
+
if (!own.length)
|
|
1546
|
+
return [];
|
|
1547
|
+
return (0, vision_1.resolveImages)(own, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
|
|
1548
|
+
}
|
|
1363
1549
|
platformAllowed(platform) {
|
|
1364
1550
|
const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
|
|
1365
1551
|
return list.includes(platform);
|
package/lib/ai/hooks.d.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface AiHookContext {
|
|
|
14
14
|
}
|
|
15
15
|
export type PromptSectionProvider = (ctx: AiHookContext) => string | Promise<string>;
|
|
16
16
|
export type OutputFilter = (text: string, ctx: AiHookContext) => string | null | Promise<string | null>;
|
|
17
|
+
/** 覆盖主插件的默认人设/系统提示词;返回空表示不覆盖。 */
|
|
18
|
+
export type PersonaOverrideProvider = (ctx: AiHookContext) => string | null | Promise<string | null>;
|
|
17
19
|
export interface AiAfterReplyContext extends AiHookContext {
|
|
18
20
|
/** 已经发送并写入上下文的最终文本 */
|
|
19
21
|
text: string;
|
|
@@ -47,12 +49,13 @@ export interface ContextEvictedContext {
|
|
|
47
49
|
export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
|
|
48
50
|
export declare class AiHookRegistry {
|
|
49
51
|
private logger?;
|
|
50
|
-
/**
|
|
51
|
-
readonly version =
|
|
52
|
+
/** 钩子接口版本;>=2 支持 contextEvicted,>=3 支持 registerPersonaOverride */
|
|
53
|
+
readonly version = 3;
|
|
52
54
|
private sections;
|
|
53
55
|
private filters;
|
|
54
56
|
private afterReplyHandlers;
|
|
55
57
|
private evictedHandlers;
|
|
58
|
+
private personaOverrides;
|
|
56
59
|
constructor(logger?: any);
|
|
57
60
|
/** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
|
|
58
61
|
setLogger(logger?: any): void;
|
|
@@ -62,8 +65,11 @@ export declare class AiHookRegistry {
|
|
|
62
65
|
filters: number;
|
|
63
66
|
afterReply: number;
|
|
64
67
|
evicted: number;
|
|
68
|
+
persona: number;
|
|
65
69
|
};
|
|
66
70
|
registerPromptSection(provider: PromptSectionProvider): () => void;
|
|
71
|
+
/** 覆盖主插件默认人设(按群);第一个返回非空文本的生效。 */
|
|
72
|
+
registerPersonaOverride(provider: PersonaOverrideProvider): () => void;
|
|
67
73
|
registerOutputFilter(filter: OutputFilter): () => void;
|
|
68
74
|
/** 文字回复已发送后触发;用于追加表情包等后续动作。 */
|
|
69
75
|
registerAfterReply(handler: AfterReplyHandler): () => void;
|
|
@@ -72,6 +78,8 @@ export declare class AiHookRegistry {
|
|
|
72
78
|
* 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
|
|
73
79
|
*/
|
|
74
80
|
registerContextEvicted(handler: ContextEvictedHandler): () => void;
|
|
81
|
+
/** 第一个非空的人设覆盖生效;失败只记日志。 */
|
|
82
|
+
collectPersonaOverride(ctx: AiHookContext): Promise<string | null>;
|
|
75
83
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
76
84
|
collectSections(ctx: AiHookContext): Promise<string[]>;
|
|
77
85
|
/** 依次执行输出过滤器;返回 null 表示丢弃本条回复。 */
|
package/lib/ai/hooks.js
CHANGED
|
@@ -13,12 +13,13 @@ exports.AiHookRegistry = void 0;
|
|
|
13
13
|
exports.getSharedAiHooks = getSharedAiHooks;
|
|
14
14
|
class AiHookRegistry {
|
|
15
15
|
logger;
|
|
16
|
-
/**
|
|
17
|
-
version =
|
|
16
|
+
/** 钩子接口版本;>=2 支持 contextEvicted,>=3 支持 registerPersonaOverride */
|
|
17
|
+
version = 3;
|
|
18
18
|
sections = new Set();
|
|
19
19
|
filters = new Set();
|
|
20
20
|
afterReplyHandlers = new Set();
|
|
21
21
|
evictedHandlers = new Set();
|
|
22
|
+
personaOverrides = new Set();
|
|
22
23
|
constructor(logger) {
|
|
23
24
|
this.logger = logger;
|
|
24
25
|
}
|
|
@@ -34,12 +35,18 @@ class AiHookRegistry {
|
|
|
34
35
|
filters: this.filters.size,
|
|
35
36
|
afterReply: this.afterReplyHandlers.size,
|
|
36
37
|
evicted: this.evictedHandlers.size,
|
|
38
|
+
persona: this.personaOverrides.size,
|
|
37
39
|
};
|
|
38
40
|
}
|
|
39
41
|
registerPromptSection(provider) {
|
|
40
42
|
this.sections.add(provider);
|
|
41
43
|
return () => this.sections.delete(provider);
|
|
42
44
|
}
|
|
45
|
+
/** 覆盖主插件默认人设(按群);第一个返回非空文本的生效。 */
|
|
46
|
+
registerPersonaOverride(provider) {
|
|
47
|
+
this.personaOverrides.add(provider);
|
|
48
|
+
return () => this.personaOverrides.delete(provider);
|
|
49
|
+
}
|
|
43
50
|
registerOutputFilter(filter) {
|
|
44
51
|
this.filters.add(filter);
|
|
45
52
|
return () => this.filters.delete(filter);
|
|
@@ -57,6 +64,20 @@ class AiHookRegistry {
|
|
|
57
64
|
this.evictedHandlers.add(handler);
|
|
58
65
|
return () => this.evictedHandlers.delete(handler);
|
|
59
66
|
}
|
|
67
|
+
/** 第一个非空的人设覆盖生效;失败只记日志。 */
|
|
68
|
+
async collectPersonaOverride(ctx) {
|
|
69
|
+
for (const provider of this.personaOverrides) {
|
|
70
|
+
try {
|
|
71
|
+
const text = await provider(ctx);
|
|
72
|
+
if (text && String(text).trim())
|
|
73
|
+
return String(text).trim();
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
this.logger?.warn?.(`[ai-hooks] persona override failed: ${String(error)}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
60
81
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
61
82
|
async collectSections(ctx) {
|
|
62
83
|
const out = [];
|