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.

6.3 KB
Raw Blame
import { type AgentGroupDetail } from '@lobechat/types';

import {
  type ChatGroupAgentItem,
  type ChatGroupItem,
  type NewChatGroup,
  type NewChatGroupAgent,
} from '@/database/schemas';
import type { GroupMemberRole } from '@/database/utils/groupMembership';
import { lambdaClient } from '@/libs/trpc/client';

export interface GroupMemberConfig {
  avatar?: string;
  backgroundColor?: string;
  description?: string;
  model?: string;
  plugins?: string[];
  provider?: string;
  systemRole?: string;
  tags?: string[];
  title?: string;
}

export interface SupervisorConfig {
  avatar?: string;
  backgroundColor?: string;
  description?: string;
  model?: string;
  params?: any;
  provider?: string;
  systemRole?: string;
  tags?: string[];
  title?: string;
}

class ChatGroupService {
  /**
   * Get a group by forkedFromIdentifier stored in config
   * @returns group id if exists, null otherwise
   */
  getGroupByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {
    return lambdaClient.group.getGroupByForkedFromIdentifier.query({ forkedFromIdentifier });
  };

  /**
   * Create a group with a supervisor agent.
   * The supervisor agent is automatically created as a virtual agent.
   */
  createGroup = (
    params: Omit<NewChatGroup, 'userId'>,
  ): Promise<{ group: ChatGroupItem; supervisorAgentId: string }> => {
    return lambdaClient.group.createGroup.mutate({
      ...params,
      config: params.config as any,
    });
  };

  /**
   * Create a group with virtual member agents in one request.
   * This is the recommended way to create a group from a template.
   * Returns groupId, supervisorAgentId, and member agentIds.
   */
  createGroupWithMembers = (
    groupConfig: Omit<NewChatGroup, 'userId'>,
    members: GroupMemberConfig[],
    supervisorConfig?: SupervisorConfig,
  ): Promise<{ agentIds: string[]; groupId: string; supervisorAgentId: string }> => {
    return lambdaClient.group.createGroupWithMembers.mutate({
      groupConfig: {
        ...groupConfig,
        config: groupConfig.config as any,
      },
      members,
      supervisorConfig,
    });
  };

  updateGroup = (id: string, value: Partial<ChatGroupItem>): Promise<ChatGroupItem> => {
    return lambdaClient.group.updateGroup.mutate({
      id,
      value: {
        ...value,
        config: value.config as any,
      },
    });
  };

  deleteGroup = (id: string) => {
    return lambdaClient.group.deleteGroup.mutate({ id });
  };

  getGroup = (id: string): Promise<ChatGroupItem | undefined> => {
    return lambdaClient.group.getGroup.query({ id });
  };

  getGroupDetail = (id: string): Promise<AgentGroupDetail | null> => {
    return lambdaClient.group.getGroupDetail.query({ id });
  };

  getGroups = (): Promise<ChatGroupItem[]> => {
    return lambdaClient.group.getGroups.query();
  };

  addAgentsToGroup = (
    groupId: string,
    agentIds: string[],
  ): Promise<{ added: NewChatGroupAgent[]; existing: string[] }> => {
    return lambdaClient.group.addAgentsToGroup.mutate({ agentIds, groupId });
  };

  /**
   * Batch create virtual agents and add them to an existing group.
   * This is more efficient than calling createAgentOnly multiple times.
   */
  batchCreateAgentsInGroup = (groupId: string, agents: GroupMemberConfig[]) => {
    return lambdaClient.group.batchCreateAgentsInGroup.mutate({
      agents,
      groupId,
    });
  };

  removeAgentsFromGroup = (groupId: string, agentIds: string[]) => {
    return lambdaClient.group.removeAgentsFromGroup.mutate({ agentIds, groupId });
  };

  updateAgentInGroup = (
    groupId: string,
    agentId: string,
    updates: { order?: number | null; role?: GroupMemberRole | null },
  ): Promise<NewChatGroupAgent> => {
    return lambdaClient.group.updateAgentInGroup.mutate({
      agentId,
      groupId,
      updates: {
        order: updates.order === null ? undefined : updates.order,
        role: updates.role === null ? undefined : updates.role,
      },
    });
  };

  getGroupAgents = (groupId: string): Promise<ChatGroupAgentItem[]> => {
    return lambdaClient.group.getGroupAgents.query({ groupId });
  };

  /**
   * Duplicate a chat group with all its members.
   * Returns the new group ID and supervisor agent ID.
   */
  duplicateGroup = (
    groupId: string,
    newTitle?: string,
  ): Promise<{ groupId: string; supervisorAgentId: string } | null> => {
    return lambdaClient.group.duplicateGroup.mutate({ groupId, newTitle });
  };

  /**
   * Members these groups only reference (`External` in the roster). A transfer
   * leaves them where they are and clones them into the target scope.
   */
  listReferencedMembers = (
    groupIds: string[],
  ): Promise<
    {
      agentId: string;
      avatar: string | null;
      backgroundColor: string | null;
      groupId: string;
      title: string | null;
    }[]
  > => {
    return lambdaClient.group.listReferencedMembers.query({ groupIds });
  };

  transferGroup = async (
    groupId: string,
    targetWorkspaceId: string | null,
    targetVisibility?: 'private' | 'public',
  ): Promise<{ groupId: string; transferJobId?: string | null } | null> => {
    const result = await lambdaClient.group.transferGroup.mutate({
      groupId,
      targetVisibility,
      targetWorkspaceId,
    });
    // Without `targetMemberId` the endpoint always takes the scope-move path.
    return result as { groupId: string; transferJobId?: string | null } | null;
  };

  /**
   * Hand ownership to another member of the current workspace. Creates a
   * pending transfer request the recipient must accept — nothing moves yet.
   */
  requestGroupTransferToMember = async (params: {
    groupId: string;
    targetMemberId: string;
  }): Promise<{ requestId: string; status: 'pending' }> => {
    const result = await lambdaClient.group.transferGroup.mutate({
      groupId: params.groupId,
      targetMemberId: params.targetMemberId,
      targetWorkspaceId: null,
    });
    return result as { requestId: string; status: 'pending' };
  };

  /**
   * Async history-backfill progress for a transferred/copied group.
   * `topicIds` caps the reported pending set to what the client can show.
   */
  getTransferJobStatus = async (groupId: string, topicIds: string[]) => {
    return lambdaClient.group.getTransferJobStatus.query({ groupId, topicIds });
  };
}

export const chatGroupService = new ChatGroupService();