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 LobeChatDatabase } from '@lobechat/database';

import type { AgentDocumentSourceType } from '@/database/models/agentDocuments/types';
import { DocumentModel } from '@/database/models/document';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { DocumentService } from '@/server/services/document';
import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';

interface DocumentServiceResult {
  content: string | null;
  createdAt: Date;
  description: string | null;
  fileType: string;
  id: string;
  source: string;
  sourceType: 'api' | 'file' | 'web';
  title: string | null;
  totalCharCount: number;
  updatedAt: Date;
}

export interface NotebookRuntimeServiceOptions {
  /**
   * Visibility of the agent that triggered this notebook side-effect. When
   * set, newly-created documents inherit it so private-agent output lands in
   * the caller's private Pages bucket rather than the workspace bucket.
   */
  callerAgentVisibility?: 'private' | 'public' | null;
  serverDB: LobeChatDatabase;
  userId: string;
  workspaceId?: string;
}

const toServiceResult = (doc: {
  content: string | null;
  createdAt: Date;
  description: string | null;
  fileType: string;
  id: string;
  source: string;
  sourceType: AgentDocumentSourceType;
  title: string | null;
  totalCharCount: number;
  updatedAt: Date;
}): DocumentServiceResult => ({
  content: doc.content,
  createdAt: doc.createdAt,
  description: doc.description,
  fileType: doc.fileType,
  id: doc.id,
  source: doc.source,
  sourceType: doc.sourceType === 'file' || doc.sourceType === 'web' ? doc.sourceType : 'api',
  title: doc.title,
  totalCharCount: doc.totalCharCount,
  updatedAt: doc.updatedAt,
});

export class NotebookRuntimeService {
  private documentService: DocumentService;
  private documentModel: DocumentModel;
  private topicDocumentModel: TopicDocumentModel;
  private callerAgentVisibility?: 'private' | 'public' | null;
  private userId: string;
  private workspaceId?: string;

  constructor(options: NotebookRuntimeServiceOptions) {
    this.userId = options.userId;
    this.workspaceId = options.workspaceId;
    this.callerAgentVisibility = options.callerAgentVisibility;
    this.documentService = new DocumentService(
      options.serverDB,
      options.userId,
      options.workspaceId,
      options.callerAgentVisibility,
    );
    this.documentModel = new DocumentModel(
      options.serverDB,
      options.userId,
      options.workspaceId,
      options.callerAgentVisibility,
    );
    this.topicDocumentModel = new TopicDocumentModel(
      options.serverDB,
      options.userId,
      options.workspaceId,
    );
  }

  associateDocumentWithTopic = async (documentId: string, topicId: string): Promise<void> => {
    await this.topicDocumentModel.associate({ documentId, topicId });
  };

  createDocument = async (params: {
    content: string;
    fileType: string;
    source: string;
    sourceType: 'api' | 'file' | 'web';
    title: string;
    totalCharCount: number;
    totalLineCount: number;
  }): Promise<DocumentServiceResult> => {
    await assertDocumentWriteWithinLimit({
      charCount: params.content.length,
      source: 'agent',
      userId: this.userId,
      workspaceId: this.workspaceId,
    });

    const doc = await this.documentModel.create({
      ...params,
      // Characters, not words: callers have passed a word count here.
      totalCharCount: params.content.length,
      ...(this.callerAgentVisibility === 'private' || this.callerAgentVisibility === 'public'
        ? { visibility: this.callerAgentVisibility }
        : {}),
    });
    return toServiceResult(doc);
  };

  deleteDocument = async (id: string, options?: { restrictToCreator?: boolean }): Promise<void> => {
    await this.topicDocumentModel.deleteByDocumentId(id);
    await this.documentService.deleteDocument(id, options);
  };

  getDocument = async (id: string): Promise<DocumentServiceResult | undefined> => {
    const doc = await this.documentModel.findById(id);
    if (!doc) return undefined;
    return toServiceResult(doc);
  };

  getDocumentsByTopicId = async (
    topicId: string,
    filter?: { type?: string },
  ): Promise<DocumentServiceResult[]> => {
    const docs = await this.topicDocumentModel.findByTopicId(topicId, filter);
    return docs.map(toServiceResult);
  };

  updateDocument = async (
    id: string,
    params: { content?: string; title?: string },
  ): Promise<DocumentServiceResult> => {
    if (params.content !== undefined) {
      const existing = await this.documentModel.findById(id);
      await assertDocumentWriteWithinLimit({
        charCount: params.content.length,
        previousCharCount: existing?.content?.length ?? 0,
        source: 'agent',
        userId: this.userId,
        workspaceId: this.workspaceId,
      });
    }

    await this.documentModel.update(id, {
      ...(params.content !== undefined && {
        content: params.content,
        totalCharCount: params.content.length,
        totalLineCount: params.content.split('\n').length,
      }),
      ...(params.title !== undefined && { title: params.title }),
    });

    const doc = await this.documentModel.findById(id);
    if (!doc) throw new Error(`Document not found after update: ${id}`);
    return toServiceResult(doc);
  };
}