UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

255 lines (254 loc) • 10.3 kB
import { n as compileConfigRegexes } from "./config-regex-CvZFnWkO.js"; import { t as createSubsystemLogger } from "./subsystem-DISldKSB.js"; import { l as escapeRegExp } from "./utils-CS0Ikux6.js"; import { i as resolveAgentConfig } from "./agent-scope-bjWqU22i.js"; import { l as normalizeChannelId, s as getChannelPlugin } from "./plugins-B09-vgme.js"; //#region src/auto-reply/reply/mentions.ts function deriveMentionPatterns(identity) { const patterns = []; const name = identity?.name?.trim(); if (name) { const parts = name.split(/\s+/).filter(Boolean).map(escapeRegExp); const re = parts.length ? parts.join(String.raw`\s+`) : escapeRegExp(name); patterns.push(String.raw`\b@?${re}\b`); } const emoji = identity?.emoji?.trim(); if (emoji) patterns.push(escapeRegExp(emoji)); return patterns; } const BACKSPACE_CHAR = "\b"; const mentionMatchRegexCompileCache = /* @__PURE__ */ new Map(); const mentionStripRegexCompileCache = /* @__PURE__ */ new Map(); const MAX_MENTION_REGEX_COMPILE_CACHE_KEYS = 512; const mentionPatternWarningCache = /* @__PURE__ */ new Set(); const MAX_MENTION_PATTERN_WARNING_KEYS = 512; const log = createSubsystemLogger("mentions"); const CURRENT_MESSAGE_MARKER = "[Current message - respond to this]"; function normalizeMentionPattern(pattern) { if (!pattern.includes(BACKSPACE_CHAR)) return pattern; return pattern.split(BACKSPACE_CHAR).join("\\b"); } function normalizeMentionPatterns(patterns) { return patterns.map(normalizeMentionPattern); } function warnRejectedMentionPattern(pattern, flags, reason) { const key = `${flags}::${reason}::${pattern}`; if (mentionPatternWarningCache.has(key)) return; mentionPatternWarningCache.add(key); if (mentionPatternWarningCache.size > MAX_MENTION_PATTERN_WARNING_KEYS) { mentionPatternWarningCache.clear(); mentionPatternWarningCache.add(key); } log.warn("Ignoring unsupported group mention pattern", { pattern, flags, reason }); } function cacheMentionRegexes(cache, cacheKey, regexes) { cache.set(cacheKey, regexes); if (cache.size > MAX_MENTION_REGEX_COMPILE_CACHE_KEYS) { cache.clear(); cache.set(cacheKey, regexes); } return [...regexes]; } function compileMentionPatternsCached(params) { if (params.patterns.length === 0) return []; const cacheKey = `${params.flags}\u001e${params.patterns.join("")}`; const cached = params.cache.get(cacheKey); if (cached) return [...cached]; const compiled = compileConfigRegexes(params.patterns, params.flags); if (params.warnRejected) for (const rejected of compiled.rejected) warnRejectedMentionPattern(rejected.pattern, rejected.flags, rejected.reason); return cacheMentionRegexes(params.cache, cacheKey, compiled.regexes); } function resolveMentionPatterns(cfg, agentId) { if (!cfg) return []; const agentConfig = agentId ? resolveAgentConfig(cfg, agentId) : void 0; const agentGroupChat = agentConfig?.groupChat; if (agentGroupChat && Object.hasOwn(agentGroupChat, "mentionPatterns")) return agentGroupChat.mentionPatterns ?? []; const globalGroupChat = cfg.messages?.groupChat; if (globalGroupChat && Object.hasOwn(globalGroupChat, "mentionPatterns")) return globalGroupChat.mentionPatterns ?? []; const derived = deriveMentionPatterns(agentConfig?.identity); return derived.length > 0 ? derived : []; } function resolveFallbackProviderMentionStripRegexes(providerId) { switch (providerId?.trim().toLowerCase()) { case "discord": return [/<@!?\d+>/gi]; case "slack": return [/<@[^>\s]+>/gi]; default: return []; } } function buildMentionRegexes(cfg, agentId) { return compileMentionPatternsCached({ patterns: normalizeMentionPatterns(resolveMentionPatterns(cfg, agentId)), flags: "i", cache: mentionMatchRegexCompileCache, warnRejected: true }); } function normalizeMentionText(text) { return (text ?? "").replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, "").toLowerCase(); } function matchesMentionPatterns(text, mentionRegexes) { if (mentionRegexes.length === 0) return false; const cleaned = normalizeMentionText(text ?? ""); if (!cleaned) return false; return mentionRegexes.some((re) => re.test(cleaned)); } function matchesMentionWithExplicit(params) { const cleaned = normalizeMentionText(params.text ?? ""); const explicit = params.explicit?.isExplicitlyMentioned === true; const explicitAvailable = params.explicit?.canResolveExplicit === true; const hasAnyMention = params.explicit?.hasAnyMention === true; const transcriptCleaned = params.transcript ? normalizeMentionText(params.transcript) : ""; const textToCheck = cleaned || transcriptCleaned; if (hasAnyMention && explicitAvailable) return explicit || params.mentionRegexes.some((re) => re.test(textToCheck)); if (!textToCheck) return explicit; return explicit || params.mentionRegexes.some((re) => re.test(textToCheck)); } function stripStructuralPrefixes(text) { if (!text) return ""; return (text.includes("[Current message - respond to this]") ? text.slice(text.indexOf(CURRENT_MESSAGE_MARKER) + 35).trimStart() : text).replace(/\[[^\]]+\]\s*/g, "").replace(/^[ \t]*[A-Za-z0-9+()\-_. ]+:\s*/gm, "").replace(/\\n/g, " ").replace(/\s+/g, " ").trim(); } function stripMentions(text, ctx, cfg, agentId) { let result = text; const providerId = ctx.Provider ? normalizeChannelId(ctx.Provider) : null; const providerMentions = providerId ? getChannelPlugin(providerId)?.mentions : void 0; const configRegexes = compileMentionPatternsCached({ patterns: normalizeMentionPatterns(resolveMentionPatterns(cfg, agentId)), flags: "gi", cache: mentionStripRegexCompileCache, warnRejected: true }); const providerRegexes = providerMentions?.stripRegexes?.({ ctx, cfg, agentId }) ?? compileMentionPatternsCached({ patterns: normalizeMentionPatterns(providerMentions?.stripPatterns?.({ ctx, cfg, agentId }) ?? []), flags: "gi", cache: mentionStripRegexCompileCache, warnRejected: false }); const fallbackProviderRegexes = providerRegexes.length > 0 ? [] : resolveFallbackProviderMentionStripRegexes(providerId); for (const re of [ ...configRegexes, ...providerRegexes, ...fallbackProviderRegexes ]) result = result.replace(re, " "); if (providerMentions?.stripMentions) result = providerMentions.stripMentions({ text: result, ctx, cfg, agentId }); result = result.replace(/@[0-9+]{5,}/g, " "); return result.replace(/\s+/g, " ").trim(); } //#endregion //#region src/auto-reply/reply/history.ts const HISTORY_CONTEXT_MARKER = "[Chat messages since your last reply - for context]"; const DEFAULT_GROUP_HISTORY_LIMIT = 50; /** Maximum number of group history keys to retain (LRU eviction when exceeded). */ const MAX_HISTORY_KEYS = 1e3; /** * Evict oldest keys from a history map when it exceeds MAX_HISTORY_KEYS. * Uses Map's insertion order for LRU-like behavior. */ function evictOldHistoryKeys(historyMap, maxKeys = MAX_HISTORY_KEYS) { if (historyMap.size <= maxKeys) return; const keysToDelete = historyMap.size - maxKeys; const iterator = historyMap.keys(); for (let i = 0; i < keysToDelete; i++) { const key = iterator.next().value; if (key !== void 0) historyMap.delete(key); } } function buildHistoryContext(params) { const { historyText, currentMessage } = params; const lineBreak = params.lineBreak ?? "\n"; if (!historyText.trim()) return currentMessage; return [ HISTORY_CONTEXT_MARKER, historyText, "", CURRENT_MESSAGE_MARKER, currentMessage ].join(lineBreak); } function appendHistoryEntry(params) { const { historyMap, historyKey, entry } = params; if (params.limit <= 0) return []; const history = historyMap.get(historyKey) ?? []; history.push(entry); while (history.length > params.limit) history.shift(); if (historyMap.has(historyKey)) historyMap.delete(historyKey); historyMap.set(historyKey, history); evictOldHistoryKeys(historyMap); return history; } function recordPendingHistoryEntry(params) { return appendHistoryEntry(params); } function recordPendingHistoryEntryIfEnabled(params) { if (!params.entry) return []; if (params.limit <= 0) return []; return recordPendingHistoryEntry({ historyMap: params.historyMap, historyKey: params.historyKey, entry: params.entry, limit: params.limit }); } function buildPendingHistoryContextFromMap(params) { if (params.limit <= 0) return params.currentMessage; return buildHistoryContextFromEntries({ entries: params.historyMap.get(params.historyKey) ?? [], currentMessage: params.currentMessage, formatEntry: params.formatEntry, lineBreak: params.lineBreak, excludeLast: false }); } function buildHistoryContextFromMap(params) { if (params.limit <= 0) return params.currentMessage; return buildHistoryContextFromEntries({ entries: params.entry ? appendHistoryEntry({ historyMap: params.historyMap, historyKey: params.historyKey, entry: params.entry, limit: params.limit }) : params.historyMap.get(params.historyKey) ?? [], currentMessage: params.currentMessage, formatEntry: params.formatEntry, lineBreak: params.lineBreak, excludeLast: params.excludeLast }); } function clearHistoryEntries(params) { params.historyMap.set(params.historyKey, []); } function clearHistoryEntriesIfEnabled(params) { if (params.limit <= 0) return; clearHistoryEntries({ historyMap: params.historyMap, historyKey: params.historyKey }); } function buildHistoryContextFromEntries(params) { const lineBreak = params.lineBreak ?? "\n"; const entries = params.excludeLast === false ? params.entries : params.entries.slice(0, -1); if (entries.length === 0) return params.currentMessage; return buildHistoryContext({ historyText: entries.map(params.formatEntry).join(lineBreak), currentMessage: params.currentMessage, lineBreak }); } //#endregion export { stripStructuralPrefixes as _, buildPendingHistoryContextFromMap as a, evictOldHistoryKeys as c, CURRENT_MESSAGE_MARKER as d, buildMentionRegexes as f, stripMentions as g, normalizeMentionText as h, buildHistoryContextFromMap as i, recordPendingHistoryEntry as l, matchesMentionWithExplicit as m, buildHistoryContext as n, clearHistoryEntries as o, matchesMentionPatterns as p, buildHistoryContextFromEntries as r, clearHistoryEntriesIfEnabled as s, DEFAULT_GROUP_HISTORY_LIMIT as t, recordPendingHistoryEntryIfEnabled as u };