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.

11.7 KB
Raw Blame
import { KnowledgeBaseIdentifier } from '@lobechat/builtin-tool-knowledge-base';
import { KnowledgeBaseExecutionRuntime } from '@lobechat/builtin-tool-knowledge-base/executionRuntime';

import { AgentModel } from '@/database/models/agent';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ProjectModel } from '@/database/models/project';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { DocumentService } from '@/server/services/document';
import { resolveDocumentWrite } from '@/server/services/document/editorData';
import { updateDocumentFromInput } from '@/server/services/document/writeFlow';
import { FileService } from '@/server/services/file';
import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
import { getKnowledgeBaseIdsMountedByBrowsers } from '@/server/services/knowledgeBaseAccess';

import { type ServerRuntimeRegistration } from './types';

export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
  factory: (context) => {
    const { userId, serverDB, agentId, agentVisibility, projectId, taskId, workspaceId } = context;
    if (!userId || !serverDB) {
      throw new Error('userId and serverDB are required for Knowledge Base execution');
    }

    const fileModel = new FileModel(serverDB, userId, workspaceId);
    const knowledgeBaseModel = new KnowledgeBaseModel(serverDB, userId, workspaceId);
    const projectModel = new ProjectModel(serverDB, userId, workspaceId);
    const knowledgeRepo = new KnowledgeRepo(serverDB, userId, workspaceId);
    const documentService = new DocumentService(serverDB, userId, workspaceId, agentVisibility);
    const documentModel = new DocumentModel(serverDB, userId, workspaceId, agentVisibility);
    const fileService = new FileService(serverDB, userId, workspaceId);
    const searchService = new KnowledgeBaseSearchService(
      serverDB,
      userId,
      workspaceId,
      agentVisibility,
      // A share visitor runs under the agent owner's scope but is not that owner.
      context.agentShareVisitor ? null : userId,
    );
    const agentModel = agentId ? new AgentModel(serverDB, userId, workspaceId) : null;

    const resolveAgentKnowledgeBaseIds = async (override?: string[]): Promise<string[]> => {
      const agentKnowledgeBaseIds = async () => {
        if (override && override.length > 0) return override;
        if (!agentModel || !agentId) return [];
        const knowledge = await agentModel.getAgentAssignedKnowledge(agentId);
        return knowledge.knowledgeBases.filter((k) => k.enabled && k.id).map((k) => k.id as string);
      };
      // Every agent working inside a project β€” its coordinator, or a member
      // running one of its tasks β€” searches the project's knowledge too.
      const projectKnowledgeBaseIds = () => {
        if (projectId) return projectModel.getEnabledKnowledgeBaseIds(projectId);
        if (taskId) return projectModel.getEnabledKnowledgeBaseIdsForTask(taskId);
        return Promise.resolve([]);
      };
      const [agentIds, projectIds] = await Promise.all([
        agentKnowledgeBaseIds(),
        projectKnowledgeBaseIds(),
      ]);
      return [...new Set([...agentIds, ...projectIds])];
    };

    return new KnowledgeBaseExecutionRuntime(
      {
        getFileContents: (fileIds) =>
          searchService.getFileContents(fileIds, {
            // "No access" keeps a knowledge base usable on the agents it is mounted on.
            resolveUsableKnowledgeBaseIds: async (restrictedIds) => {
              const mounted = new Set(await resolveAgentKnowledgeBaseIds());
              return getKnowledgeBaseIdsMountedByBrowsers(
                { serverDB, workspaceId },
                { agentId, projectId, taskId },
                restrictedIds.filter((id) => mounted.has(id)),
              );
            },
          }),
        semanticSearchForChat: async ({ knowledgeIds, query, topK }) => {
          const effectiveKnowledgeIds = await resolveAgentKnowledgeBaseIds(knowledgeIds);
          // No enabled KB in scope (none attached, or all turned off) β†’ both search paths would return nothing (BM25 is
          // KB-scoped; vector has no file scope). Skip the embedding call and
          // report the empty scope so the runtime can tell the model why.
          if (effectiveKnowledgeIds.length === 0) {
            return { chunks: [], documents: [], fileResults: [], searchedKnowledgeBaseIds: [] };
          }
          const result = await searchService.semanticSearchForChat({
            knowledgeIds: effectiveKnowledgeIds,
            query,
            topK,
          });
          return {
            chunks: result.chunks,
            documents: result.documents,
            errors: result.errors,
            fileResults: result.fileResults,
            searchedKnowledgeBaseIds: effectiveKnowledgeIds,
          };
        },
      },
      {
        addFilesToKnowledgeBase: async (knowledgeBaseId, ids) => {
          try {
            return await knowledgeBaseModel.addFilesToKnowledgeBase(knowledgeBaseId, ids);
          } catch (e: any) {
            // PG unique-constraint violation on (knowledge_base_id, file_id).
            // Re-throw with a friendly message so the ExecutionRuntime's
            // generic catch surfaces it directly.
            if (e?.cause?.code === '23505' || e?.code === '23505') {
              throw new Error('One or more files are already in this knowledge base.', {
                cause: e,
              });
            }
            throw e;
          }
        },
        createKnowledgeBase: async ({ description, name }) => {
          const data = await knowledgeBaseModel.create({ description, name });
          return data?.id ?? '';
        },
        getKnowledgeBaseById: async (id) => {
          const item = await knowledgeBaseModel.findById(id);
          if (!item) return undefined;
          return {
            avatar: item.avatar ?? null,
            description: item.description,
            id: item.id,
            name: item.name,
            updatedAt: item.updatedAt,
          };
        },
        getKnowledgeBases: async () => {
          // Defensive: when the calling agent is public, drop the caller's
          // own private KBs so a public agent can never surface them to
          // other workspace members. Documents/chunks already get this
          // treatment via `documentService`/`searchService` above.
          const items = await knowledgeBaseModel.query({
            callerAgentVisibility: agentVisibility ?? undefined,
          });
          return items.map((kb) => ({
            avatar: kb.avatar ?? null,
            description: kb.description,
            id: kb.id,
            name: kb.name,
            updatedAt: kb.updatedAt,
          }));
        },
        getKnowledgeItems: async ({ knowledgeBaseId, limit, offset }) => {
          const items = await knowledgeRepo.query({
            includeContent: false,
            knowledgeBaseId,
            limit: limit + 1,
            offset,
          });
          const hasMore = items.length > limit;
          const slice = hasMore ? items.slice(0, limit) : items;
          return {
            hasMore,
            items: slice.map((item) => ({
              fileType: item.fileType,
              id: item.id,
              name: item.name,
              size: item.size,
              sourceType: item.sourceType,
              updatedAt: item.updatedAt,
            })),
          };
        },
        removeFilesFromKnowledgeBase: (knowledgeBaseId, ids) =>
          knowledgeBaseModel.removeFilesFromKnowledgeBase(knowledgeBaseId, ids),
        removeKnowledgeBase: async (id) => {
          await knowledgeBaseModel.deleteWithFiles(id);
        },
      },
      {
        createDocument: async ({ content, fileType, knowledgeBaseId, parentId, title }) => {
          // Same Markdown write as `lh doc create`: real editor state, and no
          // body heading that repeats the title.
          const write = await resolveDocumentWrite({ content, fileType, title });
          const doc = await documentService.createDocument({
            content: write.content,
            editorData: write.editorData,
            fileType,
            knowledgeBaseId,
            parentId,
            title,
            writeSource: 'agent',
            // Inherit caller-agent visibility: private-agent output stays in
            // the owner's private bucket; public-agent output is visible to
            // the workspace. When null (no agent / cannot resolve), fall
            // through to `DocumentService.createDocument`'s existing
            // `sourceType='api'` fallback (β†’ private in workspace mode).
            ...(agentVisibility === 'private' || agentVisibility === 'public'
              ? { visibility: agentVisibility }
              : {}),
          });
          return { id: doc.id };
        },
        getDocumentById: async (id) => {
          const doc = await documentService.getDocumentById(id);
          if (!doc) return undefined;
          return {
            fileType: doc.fileType,
            id: doc.id,
            knowledgeBaseId: doc.knowledgeBaseId,
            parentId: doc.parentId,
            sourceType: doc.sourceType,
            title: doc.title,
          };
        },
        updateDocument: async ({ content, id, parentId, title }) => {
          // Same write as the editor and `lh doc edit`: restricted-library and
          // parent checks, Markdown β†’ editor data, and an open page's live room.
          const result = await updateDocumentFromInput(
            { documentModel, documentService, serverDB, userId, workspaceId },
            {
              content,
              history: {
                agentId,
                operationId: context.rootOperationId ?? context.operationId,
              },
              id,
              parentId,
              saveSource: 'llm_call',
              title,
              writeSource: 'agent',
            },
          );
          return { id: result.id };
        },
      },
      {
        getFileItemById: async (id) => {
          const item = await fileModel.findById(id);
          if (!item) return undefined;
          return {
            createdAt: item.createdAt,
            fileType: item.fileType,
            id: item.id,
            metadata: (item.metadata as Record<string, any> | null) ?? null,
            name: item.name,
            size: item.size,
            sourceType: 'file',
            updatedAt: item.updatedAt,
            url: await fileService.getFileAccessUrl(item),
          };
        },
        getKnowledgeItems: async ({ category, limit, offset, q, showFilesInKnowledgeBase }) => {
          const items = await knowledgeRepo.query({
            category,
            includeContent: false,
            limit: limit + 1,
            offset,
            q,
            showFilesInKnowledgeBase,
          });
          const hasMore = items.length > limit;
          const slice = hasMore ? items.slice(0, limit) : items;
          return {
            hasMore,
            items: await Promise.all(
              slice.map(async (item) => ({
                createdAt: item.createdAt,
                fileType: item.fileType,
                id: item.id,
                metadata: item.metadata ?? null,
                name: item.name,
                size: item.size,
                sourceType: item.sourceType,
                updatedAt: item.updatedAt,
                url:
                  item.sourceType === 'file'
                    ? await fileService.getFileAccessUrl(item)
                    : item.url || '',
              })),
            ),
          };
        },
      },
    );
  },
  identifier: KnowledgeBaseIdentifier,
};