-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic-agent.js
More file actions
73 lines (67 loc) · 2.17 KB
/
Copy pathdynamic-agent.js
File metadata and controls
73 lines (67 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Dynamic agent helpers for WeCom self-built application.
*
* Agent IDs use "wecom-app-" prefix to avoid collisions with the
* AI Bot plugin ("wecom-dm-"/"wecom-group-").
*/
export function generateAgentId(chatType, peerId) {
const sanitizedId = String(peerId)
.toLowerCase()
.replace(/[^a-z0-9_-]/g, "_");
if (chatType === "group") {
return `wecom-app-group-${sanitizedId}`;
}
return `wecom-app-dm-${sanitizedId}`;
}
export function getDynamicAgentConfig(config) {
const ch = config?.channels?.["wecom-app"] || {};
return {
enabled: ch.dynamicAgents?.enabled !== false,
dmCreateAgent: ch.dm?.createAgentOnFirstMessage !== false,
groupEnabled: ch.groupChat?.enabled !== false,
groupRequireMention: ch.groupChat?.requireMention !== false,
groupMentionPatterns: ch.groupChat?.mentionPatterns || ["@"],
};
}
export function shouldUseDynamicAgent({ chatType, config }) {
const dynamicConfig = getDynamicAgentConfig(config);
if (!dynamicConfig.enabled) {
return false;
}
if (chatType === "group") {
return dynamicConfig.groupEnabled;
}
return dynamicConfig.dmCreateAgent;
}
export function shouldTriggerGroupResponse(content, config) {
const dynamicConfig = getDynamicAgentConfig(config);
if (!dynamicConfig.groupEnabled) {
return false;
}
if (!dynamicConfig.groupRequireMention) {
return true;
}
const patterns = dynamicConfig.groupMentionPatterns;
for (const pattern of patterns) {
const escaped = escapeRegExp(pattern);
const re = new RegExp(`(?:^|(?<=\\s|[^\\w]))${escaped}`, "u");
if (re.test(content)) {
return true;
}
}
return false;
}
export function extractGroupMessageContent(content, config) {
const dynamicConfig = getDynamicAgentConfig(config);
let cleanContent = content;
const patterns = dynamicConfig.groupMentionPatterns;
for (const pattern of patterns) {
const escapedPattern = escapeRegExp(pattern);
const regex = new RegExp(`(?:^|(?<=\\s))${escapedPattern}\\S*\\s*`, "gu");
cleanContent = cleanContent.replace(regex, "");
}
return cleanContent.trim();
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}