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.4 KB
Raw Blame
import { TRPCError } from '@trpc/server';
import { z } from 'zod';

import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { HomeRepository } from '@/database/repositories/home';
import {
  MAX_PINNED_ORDER_ITEMS,
  MAX_RECOMMENDED_ITEMS,
} from '@/database/repositories/home/pinnedOrder';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { type HomeBriefData, HomeService } from '@/server/services/home';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';

import { assertCanWriteTeamPin, RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE } from './_helpers/sidebarPin';

const homeProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
  const { ctx } = opts;
  const workspaceId = ctx.workspaceId ?? undefined;

  return opts.next({
    ctx: {
      agentModel: new AgentModel(ctx.serverDB, ctx.userId, workspaceId),
      homeRepository: new HomeRepository(ctx.serverDB, ctx.userId, workspaceId),
      homeService: new HomeService(ctx.userId, workspaceId),
    },
  });
});

const homeSearchProcedure = homeProcedure.use(async (opts) => {
  const { ctx } = opts;
  const workspaceId = ctx.workspaceId ?? undefined;
  const ftsSearchRepo = await createFtsSearchRepo({
    db: ctx.serverDB,
    userId: ctx.userId,
    usage: 'home_search',
    workspaceId,
  });

  return opts.next({
    ctx: {
      homeRepository: new HomeRepository(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
    },
  });
});

/**
 * Lobe AI (the inbox) is listed only for callers that ask for it. Released
 * clients still draw it as their own fixed row and would show it twice β€” with
 * the ordinary agent menu β€” if the list started returning it unasked.
 */
const includeInboxInput = z.object({ includeInbox: z.boolean().optional() }).optional();

export const homeRouter = router({
  getDailyBrief: homeProcedure.query(({ ctx }): Promise<HomeBriefData> =>
    ctx.homeService.getDailyBrief(),
  ),

  getSidebarAgentList: homeProcedure.input(includeInboxInput).query(async ({ ctx, input }) => {
    // The sidebar payload carries applied label names and colors, so it has to
    // respect the same grant as the label registry itself β€” otherwise denying
    // `agent_label:read` only closes the front door. Personal scope has no
    // workspace roles, so it always includes them.
    const includeLabels = ctx.workspaceId
      ? await hasWorkspaceScopedPermission({
          action: 'AGENT_LABEL_READ',
          db: ctx.serverDB,
          userId: ctx.userId,
          workspaceId: ctx.workspaceId,
        })
      : true;

    // Same reasoning for folders: this payload carries every shared Category's
    // id, name and order, so denying `session_group:read` has to close this
    // door too. Omitted rather than rejected β€” the agent list itself is not
    // gated on it, and losing the whole sidebar over a folder grant would be
    // worse than losing the folders.
    const includeGroups = ctx.workspaceId
      ? await hasWorkspaceScopedPermission({
          action: 'SESSION_GROUP_READ',
          db: ctx.serverDB,
          userId: ctx.userId,
          workspaceId: ctx.workspaceId,
        })
      : true;

    return ctx.homeRepository.getSidebarAgentList(
      includeLabels,
      includeGroups,
      input?.includeInbox ?? false,
    );
  }),

  searchAgents: homeSearchProcedure
    .input(z.object({ includeInbox: z.boolean().optional(), keyword: z.string() }))
    .query(async ({ input, ctx }) => {
      return ctx.homeRepository.searchAgents(input.keyword, input.includeInbox ?? false);
    }),

  /**
   * Save the drag-and-drop order of the sidebar's pinned rows. In a workspace
   * these are the team pins every member sees, so only owners/admins may
   * reorder them; in personal mode they are the user's own pins.
   */
  updatePinnedOrder: homeProcedure
    .input(z.object({ ids: z.array(z.string().max(255)).max(MAX_PINNED_ORDER_ITEMS) }))
    .mutation(async ({ input, ctx }) => {
      await assertCanWriteTeamPin(ctx);
      await ctx.homeRepository.updatePinnedOrder(input.ids);
    }),

  /**
   * Replace the workspace's recommended Agents / chat groups (in order). Every
   * member sees the list on the Agents page and new members start with it in
   * their sidebar, so only owners/admins may change it.
   */
  updateRecommendedAgents: homeProcedure
    .input(z.object({ ids: z.array(z.string().max(255)).max(MAX_RECOMMENDED_ITEMS) }))
    .mutation(async ({ input, ctx }) => {
      if (!ctx.workspaceId) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message: 'Recommended agents only exist in a workspace',
        });
      }
      await assertCanWriteTeamPin(ctx, RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE);
      await ctx.homeRepository.updateRecommendedIds(input.ids);
    }),

  updateAgentSessionGroupId: homeProcedure
    .use(withScopedPermission('agent:update'))
    .input(
      z.object({
        agentId: z.string(),
        sessionGroupId: z.string().nullable(),
      }),
    )
    .mutation(async ({ input, ctx }) => {
      return ctx.agentModel.updateSessionGroupId(input.agentId, input.sessionGroupId);
    }),
});

export type HomeRouter = typeof homeRouter;