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.

10.9 KB
Raw Blame
import { type NotebookDocument } from '@lobechat/types';
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 { AgentOperationModel } from '@/database/models/agentOperation';
import { DocumentModel } from '@/database/models/document';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { TopicModel } from '@/database/models/topic';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { WorkModel } from '@/database/models/work';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';
import { NotebookRuntimeService } from '@/server/services/notebook';
import {
  assertCanEditResource,
  assertCanPerformResourceAction,
} from '@/server/services/resourcePermission';

import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
import { resolveRootOperation } from './_helpers/runProvenance';

/** Request-size backstop for document content, independent of the per-plan limit. */
const DOCUMENT_CONTENT_INPUT_MAX = 10_000_000;

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

  return opts.next({
    ctx: {
      operationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),
      workModel: new WorkModel(ctx.serverDB, ctx.userId, wsId),
      documentModel: new DocumentModel(ctx.serverDB, ctx.userId, wsId),
      notebookService: new NotebookRuntimeService({
        serverDB: ctx.serverDB,
        userId: ctx.userId,
        workspaceId: wsId,
      }),
      topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),
      topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
    },
  });
});

export const notebookRouter = router({
  /**
   * Attach an existing document to a topic without copying it.
   *
   * `createDocument` always writes a new row, so linking through it duplicated
   * the document (and, inside an agent run, registered the copy as a second
   * produced Work). This only writes the `(documentId, topicId)` pair, which is
   * idempotent.
   */
  associateDocument: notebookProcedure
    .use(withScopedPermission('document:update'))
    .input(z.object({ documentId: z.string(), topicId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const [document, topic] = await Promise.all([
        ctx.documentModel.findById(input.documentId),
        ctx.topicModel.findById(input.topicId),
      ]);
      if (!document) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });
      if (!topic) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });

      return ctx.topicDocumentModel.associate(input);
    }),

  createDocument: notebookProcedure
    .use(withScopedPermission('document:create'))
    .input(
      z.object({
        // Hard backstop above any plan limit; the plan limit is enforced below.
        content: z.string().max(DOCUMENT_CONTENT_INPUT_MAX),
        description: z.string(),
        metadata: z.record(z.string(), z.any()).optional(),
        operationId: z.string().optional(),
        source: z.string().optional().default('notebook'),
        sourceType: z.enum(['file', 'web', 'api', 'topic']).optional().default('api'),
        title: z.string(),
        topicId: z.string(),
        type: z
          .enum(['article', 'markdown', 'note', 'report', 'agent/plan'])
          .optional()
          .default('markdown'),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      // Resolve provenance before creating anything. A caller may only attribute
      // a document to an owned run in this topic, including its owned ancestry.
      const operation = input.operationId
        ? await ctx.operationModel.findOwnOperationById(input.operationId)
        : null;
      if (input.operationId && (!operation || operation.topicId !== input.topicId)) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message: 'Operation does not belong to this topic',
        });
      }
      const rootOperation = operation
        ? await resolveRootOperation((id) => ctx.operationModel.findOwnOperationById(id), operation)
        : null;

      // One report written twice — through the agent documents tool and through
      // this one — used to land as two documents: two entries in the topic's
      // document list, two Works, and two deliverable cards on the goal graph,
      // all for one piece of work. A byte-identical document of the same kind
      // already in this topic is that second write, so it reuses the row
      // instead of forking the document. Nothing changed, so nothing is
      // registered either. The kind travels with the search, because a document
      // is found by its type: `agent/plan` and the labelled kinds (`article` /
      // `note` / `report`) stay distinct, so a plan is never answered with a
      // markdown note and a note is never answered with a markdown row.
      const twin = await ctx.topicDocumentModel.findVerbatimTwin({
        content: input.content,
        fileType: input.type,
        title: input.title,
        topicId: input.topicId,
      });
      if (twin) return twin;

      // Refuse before any row exists so a rejected write leaves nothing behind.
      await assertDocumentWriteWithinLimit({
        charCount: input.content.length,
        source: 'user',
        userId: ctx.userId,
        workspaceId: ctx.workspaceId,
      });

      // Create the document
      const document = await ctx.documentModel.create({
        content: input.content,
        description: input.description,
        fileType: input.type,
        metadata: input.metadata,
        source: input.source,
        sourceType: input.sourceType,
        title: input.title,
        totalCharCount: input.content.length,
        totalLineCount: input.content.split('\n').length,
      });

      // Associate with topic
      await ctx.topicDocumentModel.associate({
        documentId: document.id,
        topicId: input.topicId,
      });

      if (operation && rootOperation) {
        await ctx.workModel.registerDocument({
          agentId: operation.agentId,
          changeType: 'created',
          documentId: document.id,
          rootOperationId: rootOperation.id,
          toolIdentifier: 'lobehub-notebook',
          toolName: 'createDocument',
          topicId: input.topicId,
        });
      }

      return document;
    }),

  deleteDocument: notebookProcedure
    .use(withScopedPermission('document:delete'))
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const existing = await ctx.documentModel.findById(input.id);
      if (!existing) return { success: true };
      // Same guard as documentRouter.deleteDocument — the two routers delete
      // from the same `documents` table and must not diverge in semantics.
      if (ctx.workspaceId) {
        await assertCanPerformResourceAction({
          action: 'delete',
          db: ctx.serverDB,
          resourceId: input.id,
          resourceType: 'document',
          userId: ctx.userId,
          workspaceId: ctx.workspaceId,
        });
      }

      // Same cascade rule as documentRouter.deleteDocument: a non-owner's
      // folder delete must not take teammates' descendants with it.
      await ctx.notebookService.deleteDocument(input.id, {
        restrictToCreator: isWorkspaceNonOwner(ctx),
      });

      if (ctx.workspaceId) {
        await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
          'document',
          input.id,
        );
      }

      return { success: true };
    }),

  getDocument: notebookProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      return ctx.documentModel.findById(input.id);
    }),

  listDocuments: notebookProcedure
    .input(
      z.object({
        topicId: z.string(),
        type: z.enum(['article', 'markdown', 'note', 'report', 'agent/plan']).optional(),
      }),
    )
    .query(async ({ ctx, input }): Promise<{ data: NotebookDocument[]; total: number }> => {
      const documents = await ctx.topicDocumentModel.findByTopicId(input.topicId, {
        type: input.type,
      });

      return {
        data: documents.map((doc) => ({
          associatedAt: doc.associatedAt,
          content: doc.content,
          createdAt: doc.createdAt,
          description: doc.description,
          fileType: doc.fileType,
          id: doc.id,
          metadata: doc.metadata,
          title: doc.title,
          totalCharCount: doc.totalCharCount,
          totalLineCount: doc.totalLineCount,
          updatedAt: doc.updatedAt,
        })),
        total: documents.length,
      };
    }),

  updateDocument: notebookProcedure
    .use(withScopedPermission('document:update'))
    .input(
      z.object({
        append: z.boolean().optional(),
        content: z.string().max(DOCUMENT_CONTENT_INPUT_MAX).optional(),
        description: z.string().optional(),
        id: z.string(),
        metadata: z.record(z.string(), z.any()).optional(),
        title: z.string().optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      // General-access write guard, mirroring `document.updateDocument`.
      await assertCanEditResource({
        db: ctx.serverDB,
        resourceId: input.id,
        resourceType: 'document',
        userId: ctx.userId,
        workspaceId: ctx.workspaceId ?? undefined,
      });

      let contentToUpdate = input.content;
      let previousCharCount = 0;

      if (input.content !== undefined) {
        const existing = await ctx.documentModel.findById(input.id);
        previousCharCount = existing?.content?.length ?? 0;

        // Handle append mode
        if (input.append && input.content && existing?.content) {
          contentToUpdate = existing.content + '\n\n' + input.content;
        }
      }

      // Check the post-write total before persisting anything.
      if (contentToUpdate !== undefined) {
        await assertDocumentWriteWithinLimit({
          charCount: contentToUpdate.length,
          previousCharCount,
          source: 'user',
          userId: ctx.userId,
          workspaceId: ctx.workspaceId,
        });
      }

      await ctx.documentModel.update(input.id, {
        ...(contentToUpdate !== undefined && {
          content: contentToUpdate,
          totalCharCount: contentToUpdate.length,
          totalLineCount: contentToUpdate.split('\n').length,
        }),
        ...(input.description !== undefined && { description: input.description }),
        ...(input.metadata !== undefined && { metadata: input.metadata }),
        ...(input.title && { title: input.title }),
      });

      return ctx.documentModel.findById(input.id);
    }),
});