Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

5.2 KB
Raw Blame
import type { WakeChannelKeys, WakeMentions } from '@/server/services/conversationWake/types';

/*
 * How the chat platforms a bot connects to name their conversations, mentions and messages. The
 * wake pipeline itself reads only the neutral results: `WakeChannelKeys`, `WakeMentions`, log keys.
 */

const DISCORD_USER_MENTION = /<@!?(\d+)>/g;
const DISCORD_ROLE_MENTION = /<@&(\d+)>/g;
const DISCORD_EPOCH_MS = 1_420_070_400_000;

const LARK_CHAT_TYPES = new Set(['group', 'p2p']);
const isLarkPlatform = (platform: string) => platform === 'feishu' || platform === 'lark';

/**
 * Re-derives mentions from a Discord message's own text.
 *
 * The chat SDK adapter folds `@everyone`, `@here` and configured role pings into `isMention`
 * (`respondToGlobalMentions`, `mentionRoleIds`), so that flag cannot tell an @bot from a
 * broadcast. The gateway path also hands over `raw` with only `content`, so the text is the one
 * source both paths share.
 *
 * Expects:
 * - `botUserId` is the id Discord renders the bot as in `<@id>` (the application id)
 */
export const parseDiscordMentions = (text: string, botUserId: string): WakeMentions => {
  const userIds = [...text.matchAll(DISCORD_USER_MENTION)].map((match) => match[1]);
  const roleIds = [...text.matchAll(DISCORD_ROLE_MENTION)].map((match) => match[1]);

  return {
    botMentioned: userIds.includes(botUserId),
    everyone: /(?<!\S)@everyone\b/.test(text),
    here: /(?<!\S)@here\b/.test(text),
    otherUserIds: [...new Set(userIds.filter((id) => id !== botUserId))],
    roleIds: [...new Set(roleIds)],
  };
};

/**
 * File keys for a conversation's wake state.
 *
 * Discord opens a thread under a mention and the bot speaks there, so state is kept under the
 * parent channel *and* the thread; a later message in either finds the bot's last post. Other
 * platforms have one conversation id.
 */
export const resolveChannelKeys = (
  platform: string,
  applicationId: string,
  platformThreadId: string,
): WakeChannelKeys => {
  const base = `${platform}:${applicationId}`;

  if (platform === 'discord') {
    const [, guildId, channelId, threadId] = platformThreadId.split(':');

    if (guildId && channelId) {
      return {
        channelKey: `${base}:${guildId}:${channelId}`,
        ids: [channelId, ...(threadId ? [threadId] : [])],
        // `threadKey` is the channel key plus the thread id: a thread belongs to one channel.
        ...(threadId ? { threadKey: `${base}:${guildId}:${channelId}:${threadId}` } : {}),
      };
    }
  }

  // Other platforms encode the conversation as `platform:part:part`. The owner may know it by the
  // whole id or by the id they see in the platform's UI (Telegram chat id, Slack channel id).
  // Feishu / Lark put the chat type there (`feishu:group:oc_…`), which is no id of the chat.
  const [, ...parts] = platformThreadId.split(':');
  const ids = isLarkPlatform(platform) ? parts.filter((part) => !LARK_CHAT_TYPES.has(part)) : parts;

  return {
    channelKey: `${base}:${platformThreadId}`,
    ids: [platformThreadId, ...ids.filter(Boolean)],
  };
};

/**
 * Whether a conversation keeps a shared message log: a group conversation on a platform that
 * delivers every message said in it, not only those addressed to the bot. Direct messages are
 * private and never logged.
 *
 * - Discord: guild channels (`discord:<guild>:<channel>[:<thread>]`), not `@me`
 * - Feishu / Lark: group chats (`feishu:group:oc_…`); a legacy id without the chat type cannot
 *   tell a group from a direct message, so it is not logged
 */
export const hasConversationLog = (platform: string, platformThreadId: string): boolean => {
  const [, kind] = platformThreadId.split(':');

  if (platform === 'discord') return !!kind && kind !== '@me';
  if (isLarkPlatform(platform)) return kind === 'group';

  return false;
};

/**
 * Keys of a conversation's shared message log, the channel first and then the thread when there is
 * one. Unlike the wake state they carry no application id: every bot in a channel reads and writes
 * the same log, so the channel's last messages are stored once however many bots listen.
 *
 * A person's message is filed under the last key only (where it was said); the bot's own reply is
 * filed under all of them, because people answer it from the channel as well as from the thread.
 */
export const resolveConversationLogKeys = (
  platform: string,
  platformThreadId: string,
): string[] => {
  if (platform === 'discord') {
    const [, guildId, channelId, threadId] = platformThreadId.split(':');

    if (guildId && channelId) {
      const channel = ['discord', guildId, channelId].join(':');

      return threadId ? [channel, `${channel}:${threadId}`] : [channel];
    }
  }

  return [`${platform}:${platformThreadId.split(':').slice(1).join(':')}`];
};

/** Where a message said in this conversation is filed: the most specific log. */
export const resolveConversationLogKey = (platform: string, platformThreadId: string): string =>
  resolveConversationLogKeys(platform, platformThreadId).at(-1)!;

/** A Discord message id is a snowflake: the time it was sent is in its high bits. */
export const discordMessageTime = (id: string): number | undefined => {
  if (!/^\d{15,20}$/.test(id)) return undefined;

  return Number(BigInt(id) >> 22n) + DISCORD_EPOCH_MS;
};