feat: add discord guild map + group dm controls

This commit is contained in:
Peter Steinberger
2026-01-02 11:15:52 +01:00
parent bd3d18f660
commit eb44ae76f1
10 changed files with 303 additions and 141 deletions

View File

@@ -453,14 +453,20 @@ export async function getReplyFromConfig(
if (groupResolution?.surface) {
const surface = groupResolution.surface;
const subject = ctx.GroupSubject?.trim();
const space = ctx.GroupSpace?.trim();
const explicitRoom = ctx.GroupRoom?.trim();
const isRoomSurface = surface === "discord" || surface === "slack";
const nextRoom =
isRoomSurface && subject && subject.startsWith("#") ? subject : undefined;
explicitRoom ??
(isRoomSurface && subject && subject.startsWith("#")
? subject
: undefined);
const nextSubject = nextRoom ? undefined : subject;
sessionEntry.chatType = groupResolution.chatType ?? "group";
sessionEntry.surface = surface;
if (nextSubject) sessionEntry.subject = nextSubject;
if (nextRoom) sessionEntry.room = nextRoom;
if (space) sessionEntry.space = space;
sessionEntry.displayName = buildGroupDisplayName({
surface: sessionEntry.surface,
subject: sessionEntry.subject,

View File

@@ -12,6 +12,8 @@ export type MsgContext = {
Transcript?: string;
ChatType?: string;
GroupSubject?: string;
GroupRoom?: string;
GroupSpace?: string;
GroupMembers?: string;
SenderName?: string;
SenderE164?: string;

View File

@@ -169,42 +169,35 @@ export type DiscordDmConfig = {
enabled?: boolean;
/** Allowlist for DM senders (ids or names). */
allowFrom?: Array<string | number>;
/** If true, allow group DMs (default: false). */
groupEnabled?: boolean;
/** Optional allowlist for group DM channels (ids or slugs). */
groupChannels?: Array<string | number>;
};
export type DiscordGuildConfig = {
/** Allowlist for guild messages (guilds/users by id or name). */
allowFrom?: {
guilds?: Array<string | number>;
users?: Array<string | number>;
};
/** Allowlist for guild channels (ids or names). */
channels?: Array<string | number>;
/** Require @bot mention to respond in guilds. Default: true. */
export type DiscordGuildChannelConfig = {
allow?: boolean;
requireMention?: boolean;
/** Number of recent guild messages to include for context. */
historyLimit?: number;
};
export type DiscordGuildEntry = {
slug?: string;
requireMention?: boolean;
users?: Array<string | number>;
channels?: Record<string, DiscordGuildChannelConfig>;
};
export type DiscordConfig = {
/** If false, do not start the Discord provider. Default: true. */
enabled?: boolean;
token?: string;
/** Legacy DM allowlist (ids). Prefer discord.dm.allowFrom. */
allowFrom?: Array<string | number>;
/** Legacy guild allowlist (ids). Prefer discord.guild.allowFrom. */
guildAllowFrom?: {
guilds?: Array<string | number>;
users?: Array<string | number>;
};
/** Legacy mention requirement. Prefer discord.guild.requireMention. */
requireMention?: boolean;
mediaMaxMb?: number;
/** Legacy history limit. Prefer discord.guild.historyLimit. */
historyLimit?: number;
/** Allow agent-triggered Discord reactions (default: true). */
enableReactions?: boolean;
dm?: DiscordDmConfig;
guild?: DiscordGuildConfig;
/** New per-guild config keyed by guild id or slug. */
guilds?: Record<string, DiscordGuildEntry>;
};
export type SignalConfig = {
@@ -934,14 +927,6 @@ const ClawdisSchema = z.object({
.object({
enabled: z.boolean().optional(),
token: z.string().optional(),
allowFrom: z.array(z.union([z.string(), z.number()])).optional(),
guildAllowFrom: z
.object({
guilds: z.array(z.union([z.string(), z.number()])).optional(),
users: z.array(z.union([z.string(), z.number()])).optional(),
})
.optional(),
requireMention: z.boolean().optional(),
mediaMaxMb: z.number().positive().optional(),
historyLimit: z.number().int().min(0).optional(),
enableReactions: z.boolean().optional(),
@@ -949,8 +934,33 @@ const ClawdisSchema = z.object({
.object({
enabled: z.boolean().optional(),
allowFrom: z.array(z.union([z.string(), z.number()])).optional(),
groupEnabled: z.boolean().optional(),
groupChannels: z.array(z.union([z.string(), z.number()])).optional(),
})
.optional(),
guilds: z
.record(
z.string(),
z
.object({
slug: z.string().optional(),
requireMention: z.boolean().optional(),
users: z.array(z.union([z.string(), z.number()])).optional(),
channels: z
.record(
z.string(),
z
.object({
allow: z.boolean().optional(),
requireMention: z.boolean().optional(),
})
.optional(),
)
.optional(),
})
.optional(),
)
.optional(),
guild: z
.object({
allowFrom: z

View File

@@ -116,11 +116,13 @@ export function buildGroupDisplayName(params: {
key: string;
}) {
const surfaceKey = (params.surface?.trim().toLowerCase() || "group").trim();
const room = params.room?.trim();
const space = params.space?.trim();
const subject = params.subject?.trim();
const detail =
params.room?.trim() ||
params.subject?.trim() ||
params.space?.trim() ||
"";
(room && space
? `${space}${room.startsWith("#") ? "" : "#"}${room}`
: room || subject || space || "") || "";
const fallbackId = params.id?.trim() || params.key.replace(/^group:/, "");
const rawLabel = detail || fallbackId;
let token = normalizeGroupLabel(rawLabel);
@@ -130,7 +132,12 @@ export function buildGroupDisplayName(params: {
if (!params.room && token.startsWith("#")) {
token = token.replace(/^#+/, "");
}
if (token && !/^[@#]/.test(token) && !token.startsWith("g-")) {
if (
token &&
!/^[@#]/.test(token) &&
!token.startsWith("g-") &&
!token.includes("#")
) {
token = `g-${token}`;
}
return token ? `${surfaceKey}:${token}` : surfaceKey;

View File

@@ -25,12 +25,6 @@ export type MonitorDiscordOpts = {
token?: string;
runtime?: RuntimeEnv;
abortSignal?: AbortSignal;
allowFrom?: Array<string | number>;
guildAllowFrom?: {
guilds?: Array<string | number>;
users?: Array<string | number>;
};
requireMention?: boolean;
mediaMaxMb?: number;
historyLimit?: number;
};
@@ -54,6 +48,19 @@ type DiscordAllowList = {
names: Set<string>;
};
type DiscordGuildEntryResolved = {
id?: string;
slug?: string;
requireMention?: boolean;
users?: Array<string | number>;
channels?: Record<string, { allow?: boolean; requireMention?: boolean }>;
};
type DiscordChannelConfigResolved = {
allowed: boolean;
requireMention?: boolean;
};
export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
const cfg = loadConfig();
const token = normalizeDiscordToken(
@@ -77,29 +84,17 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
};
const dmConfig = cfg.discord?.dm;
const guildConfig = cfg.discord?.guild;
const allowFrom =
opts.allowFrom ?? dmConfig?.allowFrom ?? cfg.discord?.allowFrom;
const guildAllowFrom =
opts.guildAllowFrom ??
guildConfig?.allowFrom ??
cfg.discord?.guildAllowFrom;
const guildChannels = guildConfig?.channels;
const requireMention =
opts.requireMention ??
guildConfig?.requireMention ??
cfg.discord?.requireMention ??
true;
const guildEntries = cfg.discord?.guilds;
const allowFrom = dmConfig?.allowFrom;
const mediaMaxBytes =
(opts.mediaMaxMb ?? cfg.discord?.mediaMaxMb ?? 8) * 1024 * 1024;
const historyLimit = Math.max(
0,
opts.historyLimit ??
guildConfig?.historyLimit ??
cfg.discord?.historyLimit ??
20,
opts.historyLimit ?? cfg.discord?.historyLimit ?? 20,
);
const dmEnabled = dmConfig?.enabled ?? true;
const groupDmEnabled = dmConfig?.groupEnabled ?? false;
const groupDmChannels = dmConfig?.groupChannels;
const client = new Client({
intents: [
@@ -128,8 +123,10 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
if (!message.author) return;
const channelType = message.channel.type;
const isGroupDm = channelType === ChannelType.GroupDM;
const isDirectMessage = channelType === ChannelType.DM;
const isGuildMessage = Boolean(message.guild);
if (isGroupDm && !groupDmEnabled) return;
if (isDirectMessage && !dmEnabled) return;
const botId = client.user?.id;
const wasMentioned =
@@ -141,6 +138,58 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
message.embeds[0]?.description ||
"";
const guildInfo = isGuildMessage
? resolveDiscordGuildEntry({
guild: message.guild,
guildEntries,
})
: null;
if (
isGuildMessage &&
guildEntries &&
Object.keys(guildEntries).length > 0 &&
!guildInfo
) {
logVerbose(
`Blocked discord guild ${message.guild?.id ?? "unknown"} (not in discord.guilds)`,
);
return;
}
const channelName =
(isGuildMessage || isGroupDm) && "name" in message.channel
? message.channel.name
: undefined;
const channelSlug = channelName ? normalizeDiscordSlug(channelName) : "";
const guildSlug =
guildInfo?.slug ||
(message.guild?.name ? normalizeDiscordSlug(message.guild.name) : "");
const channelConfig = isGuildMessage
? resolveDiscordChannelConfig({
guildInfo,
channelId: message.channelId,
channelName,
channelSlug,
})
: null;
const groupDmAllowed =
isGroupDm &&
resolveGroupDmAllow({
channels: groupDmChannels,
channelId: message.channelId,
channelName,
channelSlug,
});
if (isGroupDm && !groupDmAllowed) return;
if (isGuildMessage && channelConfig?.allowed === false) {
logVerbose(
`Blocked discord channel ${message.channelId} not in guild channel allowlist`,
);
return;
}
if (isGuildMessage && historyLimit > 0 && baseText) {
const history = guildHistories.get(message.channelId) ?? [];
history.push({
@@ -153,7 +202,9 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
guildHistories.set(message.channelId, history);
}
if (isGuildMessage && requireMention) {
const resolvedRequireMention =
channelConfig?.requireMention ?? guildInfo?.requireMention ?? true;
if (isGuildMessage && resolvedRequireMention) {
if (botId && !wasMentioned) {
logger.info(
{
@@ -167,56 +218,27 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
}
if (isGuildMessage) {
const channelAllow = normalizeDiscordAllowList(guildChannels, [
"channel:",
]);
if (channelAllow) {
const channelName =
"name" in message.channel ? message.channel.name : undefined;
const channelOk = allowListMatches(channelAllow, {
id: message.channelId,
name: channelName,
});
if (!channelOk) {
logVerbose(
`Blocked discord channel ${message.channelId} not in guild.channels`,
);
return;
}
}
}
if (isGuildMessage && guildAllowFrom) {
const guilds = normalizeDiscordAllowList(guildAllowFrom.guilds, [
"guild:",
]);
const users = normalizeDiscordAllowList(guildAllowFrom.users, [
"discord:",
"user:",
]);
if (guilds || users) {
const guildId = message.guild?.id ?? "";
const userId = message.author.id;
const guildOk =
!guilds ||
allowListMatches(guilds, {
id: guildId,
name: message.guild?.name,
});
const userAllow = guildInfo?.users;
if (Array.isArray(userAllow) && userAllow.length > 0) {
const users = normalizeDiscordAllowList(userAllow, [
"discord:",
"user:",
]);
const userOk =
!users ||
allowListMatches(users, {
id: userId,
id: message.author.id,
name: message.author.username,
tag: message.author.tag,
});
if (!guildOk || !userOk) {
if (!userOk) {
logVerbose(
`Blocked discord guild sender ${userId} (guild ${guildId || "unknown"}) not in guildAllowFrom`,
`Blocked discord guild sender ${message.author.id} (not in guild users allowlist)`,
);
return;
}
}
}
if (isDirectMessage && Array.isArray(allowFrom) && allowFrom.length > 0) {
@@ -250,13 +272,9 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
const fromLabel = isDirectMessage
? buildDirectLabel(message)
: buildGuildLabel(message);
const groupSubject = (() => {
if (isDirectMessage) return undefined;
const channelName =
"name" in message.channel ? message.channel.name : message.channelId;
if (!channelName) return undefined;
return isGuildMessage ? `#${channelName}` : channelName;
})();
const groupRoom =
isGuildMessage && channelSlug ? `#${channelSlug}` : undefined;
const groupSubject = isDirectMessage ? undefined : groupRoom;
const textWithId = `${text}\n[discord message id: ${message.id} channel: ${message.channelId}]`;
let combinedBody = formatAgentEnvelope({
surface: "Discord",
@@ -298,6 +316,8 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
ChatType: isDirectMessage ? "direct" : "group",
SenderName: message.member?.displayName ?? message.author.tag,
GroupSubject: groupSubject,
GroupRoom: groupRoom,
GroupSpace: isGuildMessage ? guildSlug || undefined : undefined,
Surface: "discord" as const,
WasMentioned: wasMentioned,
MessageSid: message.id,
@@ -457,6 +477,8 @@ function normalizeDiscordAllowList(
}
const normalized = normalizeDiscordName(entry);
if (normalized) names.add(normalized);
const slugged = normalizeDiscordSlug(entry);
if (slugged) names.add(slugged);
}
if (!allowAll && ids.size === 0 && names.size === 0) return null;
@@ -468,6 +490,17 @@ function normalizeDiscordName(value?: string | null) {
return value.trim().toLowerCase();
}
function normalizeDiscordSlug(value?: string | null) {
if (!value) return "";
let text = value.trim().toLowerCase();
if (!text) return "";
text = text.replace(/^[@#]+/, "");
text = text.replace(/[\s_]+/g, "-");
text = text.replace(/[^a-z0-9-]+/g, "-");
text = text.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
return text;
}
function allowListMatches(
allowList: DiscordAllowList,
candidates: {
@@ -483,9 +516,100 @@ function allowListMatches(
if (normalizedName && allowList.names.has(normalizedName)) return true;
const normalizedTag = normalizeDiscordName(tag);
if (normalizedTag && allowList.names.has(normalizedTag)) return true;
const slugName = normalizeDiscordSlug(name);
if (slugName && allowList.names.has(slugName)) return true;
const slugTag = normalizeDiscordSlug(tag);
if (slugTag && allowList.names.has(slugTag)) return true;
return false;
}
function resolveDiscordGuildEntry(params: {
guild: import("discord.js").Guild | null;
guildEntries: Record<string, DiscordGuildEntryResolved> | undefined;
}): DiscordGuildEntryResolved | null {
const { guild, guildEntries } = params;
if (!guild || !guildEntries || Object.keys(guildEntries).length === 0) {
return null;
}
const guildId = guild.id;
const guildSlug = normalizeDiscordSlug(guild.name);
const direct = guildEntries[guildId];
if (direct) {
return {
id: guildId,
slug: direct.slug ?? guildSlug,
requireMention: direct.requireMention,
users: direct.users,
channels: direct.channels,
};
}
if (guildSlug && guildEntries[guildSlug]) {
const entry = guildEntries[guildSlug];
return {
id: guildId,
slug: entry.slug ?? guildSlug,
requireMention: entry.requireMention,
users: entry.users,
channels: entry.channels,
};
}
const matchBySlug = Object.entries(guildEntries).find(([, entry]) => {
const entrySlug = normalizeDiscordSlug(entry.slug);
return entrySlug && entrySlug === guildSlug;
});
if (matchBySlug) {
const entry = matchBySlug[1];
return {
id: guildId,
slug: entry.slug ?? guildSlug,
requireMention: entry.requireMention,
users: entry.users,
channels: entry.channels,
};
}
return null;
}
function resolveDiscordChannelConfig(params: {
guildInfo: DiscordGuildEntryResolved | null;
channelId: string;
channelName?: string;
channelSlug?: string;
}): DiscordChannelConfigResolved | null {
const { guildInfo, channelId, channelName, channelSlug } = params;
const channelEntries = guildInfo?.channels;
if (channelEntries && Object.keys(channelEntries).length > 0) {
const entry =
channelEntries[channelId] ??
(channelSlug
? channelEntries[channelSlug] ??
channelEntries[`#${channelSlug}`]
: undefined) ??
(channelName
? channelEntries[normalizeDiscordSlug(channelName)]
: undefined);
if (!entry) return { allowed: false };
return { allowed: entry.allow !== false, requireMention: entry.requireMention };
}
return { allowed: true };
}
function resolveGroupDmAllow(params: {
channels: Array<string | number> | undefined;
channelId: string;
channelName?: string;
channelSlug?: string;
}) {
const { channels, channelId, channelName, channelSlug } = params;
if (!channels || channels.length === 0) return true;
const allowList = normalizeDiscordAllowList(channels, ["channel:"]);
if (!allowList) return true;
return allowListMatches(allowList, {
id: channelId,
name: channelSlug || channelName,
});
}
async function sendTyping(message: Message) {
try {
const channel = message.channel;

View File

@@ -2210,9 +2210,6 @@ export async function startGatewayServer(
token: discordToken.trim(),
runtime: discordRuntimeEnv,
abortSignal: discordAbort.signal,
allowFrom: cfg.discord?.allowFrom,
guildAllowFrom: cfg.discord?.guildAllowFrom,
requireMention: cfg.discord?.requireMention,
mediaMaxMb: cfg.discord?.mediaMaxMb,
historyLimit: cfg.discord?.historyLimit,
})