openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
270 lines (269 loc) • 10.7 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { R as compileConfigRegexes } from "./redact-Mj7pppxC.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as getLoadedChannelPluginById } from "./registry-loaded-NYWUyLLC.mjs";
import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs";
import "./registry-BB86xKJa.mjs";
import { n as HISTORY_CONTEXT_MARKER, r as RECENT_HISTORY_CONTEXT_MARKER } from "./history-B0kihfTi.mjs";
//#region src/channels/mention-pattern-policy.ts
function resolveProviderMentionPatternsPolicy(e, t) {
if (!e || !t) return;
const n = e.channels?.[t];
const r = isRecord(n) ? n.mentionPatterns : void 0;
return isRecord(r) ? r : void 0;
}
function resolveMentionPatternPolicy(e) {
const t = normalizeOptionalString(e.conversationId);
const n = e.providerPolicy ?? resolveProviderMentionPatternsPolicy(e.cfg, e.provider);
const r = n?.mode === "allow" || n?.mode === "deny" ? n.mode : "allow";
const i = t != null && (n?.allowIn ?? []).some((e) => normalizeOptionalString(e) === t);
const a = t != null && (n?.denyIn ?? []).some((e) => normalizeOptionalString(e) === t);
return {
effectiveMode: r,
allowMatched: i,
denyMatched: a,
enabled: r === "allow" ? !a : i && !a
};
}
//#endregion
//#region src/auto-reply/reply/mentions.ts
const NAME_IDENTITY_CHARS = String.raw`\p{L}\p{N}\p{Pc}`;
const NAME_TOKEN_CHARS = String.raw`${NAME_IDENTITY_CHARS}\p{M}`;
const JOINER_CHARS = String.raw`\u200C\u200D`;
const DECORATION_SPACING = String.raw`[${JOINER_CHARS}\s]*`;
const OPTIONAL_JOINER_GAP = String.raw`[${JOINER_CHARS}]*`;
const UNICODE_WORD_CHAR = String.raw`[${NAME_TOKEN_CHARS}${JOINER_CHARS}]`;
const JOINER_RUN = new RegExp(`[${JOINER_CHARS}]+`, "u");
const JOINER_ONLY = new RegExp(`^[${JOINER_CHARS}]+$`, "u");
const OMISSIBLE_DECORATION_CHAR = new RegExp(String.raw`[\p{So}\p{M}\u{1F3FB}-\u{1F3FF}\u200B-\u200F\u202A-\u202E\u2060-\u206F\u{E0020}-\u{E007F}]`, "u");
const EMOJI_PRESENTATION_MARKS = /* @__PURE__ */ new Set(["️", "⃣"]);
const EMOJI_PRESENTATION_BASE = /\p{Emoji}/u;
const NAME_IDENTITY_GRAPHEME = new RegExp(`[${NAME_IDENTITY_CHARS}]`, "u");
const NAME_GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, { granularity: "grapheme" });
function wrapDerivedMentionPattern(e) {
const t = e.leading ? `(?:${e.leading}${DECORATION_SPACING}|)` : "";
const n = e.trailing ? `(?:${DECORATION_SPACING}${e.trailing}(?!${UNICODE_WORD_CHAR})|(?!${UNICODE_WORD_CHAR})(?!${DECORATION_SPACING}${e.trailing}${UNICODE_WORD_CHAR}))` : `(?!${UNICODE_WORD_CHAR})`;
return `(?:@|(?<!${UNICODE_WORD_CHAR}${t}))${t}${e.core}${n}`;
}
function encodeOptionalJoiners(e) {
return e.split(/([\u200C\u200D]+)/u).filter(Boolean).map((e) => JOINER_ONLY.test(e) ? `(?:${escapeRegExp(e)}|)` : escapeRegExp(e)).join("");
}
function escapeJoinerTolerantLiteral(e) {
if (!e || JOINER_ONLY.test(e)) return "";
return encodeOptionalJoiners(e);
}
function isEmojiPresentationGrapheme(e) {
const t = Array.from(e);
const n = t[0];
return Boolean(n && EMOJI_PRESENTATION_BASE.test(n) && t.some((e) => EMOJI_PRESENTATION_MARKS.has(e)));
}
function isIdentityGrapheme(e) {
return NAME_IDENTITY_GRAPHEME.test(e) && !isEmojiPresentationGrapheme(e);
}
function isDecorationGrapheme(e) {
if (isEmojiPresentationGrapheme(e)) return true;
return Array.from(e).every((e) => /\s/u.test(e) || JOINER_RUN.test(e) || OMISSIBLE_DECORATION_CHAR.test(e));
}
function parseNameUnits(e) {
const t = Array.from(NAME_GRAPHEME_SEGMENTER.segment(e), (e) => e.segment);
const n = [];
for (const e of t) {
const t = isIdentityGrapheme(e);
const r = n.at(-1);
if (r?.identity === t) r.literal += e;
else n.push({
identity: t,
literal: e
});
}
return n.map((e) => {
if (e.identity) return {
kind: "token",
literal: e.literal
};
const t = Array.from(NAME_GRAPHEME_SEGMENTER.segment(e.literal), (e) => e.segment);
if (!t.every(isDecorationGrapheme)) return {
kind: "separator",
literal: e.literal
};
return {
kind: "decoration",
literal: e.literal,
spellings: t.filter((e) => !/^\s+$/u.test(e) && !JOINER_ONLY.test(e)).map(escapeJoinerTolerantLiteral),
spaced: /\s/u.test(e.literal)
};
});
}
function encodeSeparator(e) {
return e.literal.split(/(\s+|[\u200C\u200D]+)/u).filter(Boolean).map((e) => /^\s+$/u.test(e) ? String.raw`\s+` : JOINER_ONLY.test(e) ? encodeOptionalJoiners(e) : escapeRegExp(e)).join("");
}
function encodeEdgeDecorationLiteral(e) {
if (e?.kind !== "decoration") return "";
const t = e.spellings.join(OPTIONAL_JOINER_GAP);
if (!t) return encodeOptionalJoiners(e.literal.replace(/[^\u200C\u200D]/gu, ""));
return t;
}
function encodeInteriorDecoration(e) {
const t = e.spellings.join(DECORATION_SPACING);
if (!t) {
const t = encodeOptionalJoiners(e.literal.replace(/[^\u200C\u200D]/gu, ""));
return e.spaced ? String.raw`${t}\s${DECORATION_SPACING}` : t;
}
return `(?:${DECORATION_SPACING}${t}${DECORATION_SPACING}|\\s${e.spaced ? "+" : "*"})`;
}
function deriveNameParts(e) {
const t = parseNameUnits(e);
if (!t.some((e) => e.kind === "token")) return {
leading: "",
core: escapeJoinerTolerantLiteral(e),
trailing: ""
};
const n = t[0]?.kind === "decoration" ? 1 : 0;
const r = t.at(-1)?.kind === "decoration" ? t.length - 1 : t.length;
let i = "";
for (const e of t.slice(n, r)) i += e.kind === "token" ? escapeJoinerTolerantLiteral(e.literal) : e.kind === "separator" ? encodeSeparator(e) : encodeInteriorDecoration(e);
return {
leading: encodeEdgeDecorationLiteral(t[0]),
core: i,
trailing: encodeEdgeDecorationLiteral(t.at(-1))
};
}
function deriveMentionPatterns(e) {
const t = [];
const n = normalizeOptionalString(e?.name);
const r = n ? deriveNameParts(n) : void 0;
if (r?.core) t.push(wrapDerivedMentionPattern(r));
const i = normalizeOptionalString(e?.emoji);
const a = i ? escapeJoinerTolerantLiteral(i) : "";
if (a) t.push(a);
return t;
}
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");
function warnRejectedMentionPattern(e, t, n) {
const r = `${t}::${n}::${e}`;
if (mentionPatternWarningCache.has(r)) return;
if (mentionPatternWarningCache.size >= MAX_MENTION_PATTERN_WARNING_KEYS) mentionPatternWarningCache.clear();
mentionPatternWarningCache.add(r);
log.warn("Ignoring unsupported group mention pattern", {
pattern: e,
flags: t,
reason: n
});
}
function compileMentionPatternsCached(e) {
if (e.patterns.length === 0) return [];
const t = e.patterns.map((e) => e.replaceAll(BACKSPACE_CHAR, "\\b"));
const n = `${e.flags}\u001e${t.join("")}`;
const r = e.cache.get(n);
if (r) return [...r];
const i = compileConfigRegexes(t, e.flags);
if (e.warnRejected) for (const e of i.rejected) warnRejectedMentionPattern(e.pattern, e.flags, e.reason);
e.cache.set(n, i.regexes);
if (e.cache.size > MAX_MENTION_REGEX_COMPILE_CACHE_KEYS) {
e.cache.clear();
e.cache.set(n, i.regexes);
}
return [...i.regexes];
}
function resolveMentionPatterns(e, t) {
if (!e) return {
patterns: [],
unicode: false
};
const n = t ? resolveAgentConfig(e, t) : void 0;
for (const t of [n?.groupChat, e.messages?.groupChat]) if (t && Object.hasOwn(t, "mentionPatterns")) return {
patterns: t.mentionPatterns ?? [],
unicode: false
};
const r = deriveMentionPatterns(n?.identity);
return {
patterns: r,
unicode: r.length > 0
};
}
function buildMentionRegexes(e, t, n) {
if (!resolveMentionPatternPolicy({
...n,
cfg: e,
agentId: t
}).enabled) return [];
const r = resolveMentionPatterns(e, t);
return compileMentionPatternsCached({
patterns: r.patterns,
flags: r.unicode ? "iu" : "i",
cache: mentionMatchRegexCompileCache,
warnRejected: true
});
}
function normalizeMentionText(e) {
return normalizeLowercaseStringOrEmpty((e ?? "").replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, ""));
}
function matchesMentionPatterns(e, t) {
if (t.length === 0) return false;
const n = normalizeMentionText(e ?? "");
return t.some((e) => e.test(n));
}
function matchesMentionWithExplicit(e) {
const t = normalizeMentionText(e.text ?? "");
const n = e.explicit?.isExplicitlyMentioned === true;
const r = e.transcript ? normalizeMentionText(e.transcript) : "";
const i = t || r;
return n || e.mentionRegexes.some((e) => e.test(i));
}
function stripStructuralPrefixes(e) {
if (!e) return "";
if (e.trimStart().startsWith("[Chat messages since your last reply - for context]") || e.trimStart().startsWith("[Recent chat messages - for context]")) return e.trim();
const t = e.replace(/^(?:[ \t]*\[[^\]\n]+\][ \t]*)+/, "");
const n = t === e ? /^[ \t]*(?!\/)[^\n:]{1,120}:\s+/gm : /^[ \t]*[^\n:]{1,120}:\s+/gm;
const r = t.replace(n, "").replace(/\\n/g, " ").trim();
return r.replace(r.startsWith("/") ? /[ \t]+/g : /\s+/g, " ");
}
function stripMentions(e, t, n, r) {
let i = e;
const a = (t.Provider ? normalizeAnyChannelId(t.Provider) : null) ?? normalizeOptionalLowercaseString(t.Provider) ?? null;
const o = a ? getLoadedChannelPluginById(a)?.mentions : void 0;
const s = resolveMentionPatterns(n, r);
const c = compileMentionPatternsCached({
patterns: s.patterns,
flags: s.unicode ? "giu" : "gi",
cache: mentionStripRegexCompileCache,
warnRejected: true
});
const l = o?.stripRegexes?.({
ctx: t,
cfg: n,
agentId: r
}) ?? compileMentionPatternsCached({
patterns: o?.stripPatterns?.({
ctx: t,
cfg: n,
agentId: r
}) ?? [],
flags: "gi",
cache: mentionStripRegexCompileCache,
warnRejected: false
});
for (const e of [...c, ...l]) i = i.replace(e, " ");
if (o?.stripMentions) i = o.stripMentions({
text: i,
ctx: t,
cfg: n,
agentId: r
});
i = i.replace(/@[0-9+]{5,}/g, " ");
const u = i.trim();
return u.startsWith("/") ? u : u.replace(/\s+/g, " ");
}
//#endregion
export { stripMentions as a, normalizeMentionText as i, matchesMentionPatterns as n, stripStructuralPrefixes as o, matchesMentionWithExplicit as r, resolveMentionPatternPolicy as s, buildMentionRegexes as t };