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.

7.1 KB
Raw Blame
import type { LobeChatDatabase } from '@lobechat/database';
import { Md5 } from 'ts-md5';

import { DocumentModel } from '@/database/models/document';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { createAgentMarkdownSnapshot } from '@/server/services/agentDocuments/headlessEditor';
import { DocumentService } from '@/server/services/document';
import { updateDocumentThroughRoom } from '@/server/services/pageCollab/bodyWriter';

export interface UpsertCrawledDocumentParams {
  content: string;
  /**
   * Crawler content type from `CrawlSuccessResult`. A `json` body is wrapped
   * in a fenced code block before persisting: the agent markdown snapshot
   * guard rejects raw JSON (markdown parsing would rewrite escapes and
   * emphasis), while fenced code blocks are stored byte-exact.
   */
  contentType?: 'json';
  description?: string;
  title: string;
  /**
   * When provided, the resulting document is also (idempotently) linked to
   * the topic so the notebook UI can list it. Server agent runtimes leave
   * this unset β€” they bind to the agent instead via `associateDocument`.
   */
  topicId?: string;
  url: string;
}

export interface UpsertCrawledDocumentResult {
  id: string;
  /**
   * - `created`: this URL is new for the user; a `documents` row was inserted.
   * - `updated`: the URL existed and the content changed; the row was updated
   *   and a `document_histories` snapshot was written.
   * - `unchanged`: the URL existed with byte-identical content; no write
   *   happened β€” repeat crawls of the same unchanged page short-circuit.
   */
  status: 'created' | 'updated' | 'unchanged';
}

const hashContent = (content: string): string => Md5.hashStr(content);

/**
 * Wrap a raw JSON crawl body in a fenced code block so it survives the agent
 * markdown snapshot guard: raw JSON is rejected (markdown parsing would drop
 * backslash escapes and pair `__`/`*` into emphasis), while fenced code
 * blocks are stored byte-exact and keep the JSON parseable.
 */
const wrapJsonCrawlContent = (content: string): string => `\`\`\`json\n${content.trim()}\n\`\`\``;

/**
 * Single owner of "crawl a web page, persist it as a document" semantics.
 *
 * Both the server agent runtime (`serverRuntimes/webBrowsing.ts`) and the
 * client builtin-tool executor (`store/.../lobe-web-browsing.ts`) route
 * through `upsertCrawledDocument`, so dedupe + content-hash short-circuit +
 * `document_histories` snapshot all live in one place. Splitting these
 * across two call sites previously caused (client path created a
 * fresh row every crawl while the server path was being patched to dedupe).
 */
export class WebBrowsingDocumentService {
  private readonly db: LobeChatDatabase;
  private readonly userId: string;
  private readonly workspaceId?: string;
  private readonly documentModel: DocumentModel;
  private readonly topicDocumentModel: TopicDocumentModel;
  private documentServiceInstance?: DocumentService;
  /**
   * Visibility of the agent that triggered this crawl. When set, newly-created
   * documents inherit it so private-agent output lands in the caller's private
   * Pages bucket rather than the workspace bucket.
   */
  private readonly callerAgentVisibility?: 'private' | 'public' | null;

  constructor(
    db: LobeChatDatabase,
    userId: string,
    workspaceId?: string,
    callerAgentVisibility?: 'private' | 'public' | null,
  ) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
    this.callerAgentVisibility = callerAgentVisibility;
    this.documentModel = new DocumentModel(db, userId, workspaceId, callerAgentVisibility);
    this.topicDocumentModel = new TopicDocumentModel(db, userId, workspaceId);
  }

  private get documentService() {
    this.documentServiceInstance ??= new DocumentService(
      this.db,
      this.userId,
      this.workspaceId,
      this.callerAgentVisibility,
    );
    return this.documentServiceInstance;
  }

  upsertCrawledDocument = async (
    params: UpsertCrawledDocumentParams,
  ): Promise<UpsertCrawledDocumentResult> => {
    const { content, contentType, description, title, topicId, url } = params;

    // PostgreSQL text and jsonb columns reject NUL (`\u0000`), and one stray NUL
    // in a crawled page would fail the whole insert. Raw JSON bodies must be
    // fenced before hitting the markdown snapshot guard (see
    // `UpsertCrawledDocumentParams.contentType`).
    const safeContent = content.replaceAll('\u0000', '');
    const persistedContent =
      contentType === 'json' ? wrapJsonCrawlContent(safeContent) : safeContent;

    const existing = await this.documentModel.findBySource(url, 'web');

    let documentId: string;
    let status: UpsertCrawledDocumentResult['status'];

    if (existing) {
      if (hashContent(existing.content ?? '') === hashContent(persistedContent)) {
        // Byte-identical content β†’ skip the write entirely. Both `documents`
        // and `document_histories` would only churn `updated_at`, which is
        // not worth the cost (and pollutes the history list with no-op rows).
        documentId = existing.id;
        status = 'unchanged';
      } else {
        const snapshot = await createAgentMarkdownSnapshot(persistedContent);
        // `DocumentService.updateDocument` runs inside a transaction and
        // writes a `document_histories` row when `editorData` differs from
        // the row's current snapshot, so each refresh becomes a revision.
        await updateDocumentThroughRoom(
          this.db,
          this.documentService,
          existing.id,
          {
            content: snapshot.content,
            editorData: snapshot.editorData,
            saveSource: 'llm_call',
            title,
            writeSource: 'system',
          },
          { userId: this.userId, workspaceId: this.workspaceId },
        );
        documentId = existing.id;
        status = 'updated';
      }
    } else {
      const snapshot = await createAgentMarkdownSnapshot(persistedContent);
      const created = await this.documentModel.create({
        content: snapshot.content,
        description,
        editorData: snapshot.editorData,
        fileType: 'article',
        filename: title,
        source: url,
        sourceType: 'web',
        title,
        totalCharCount: snapshot.content.length,
        totalLineCount: snapshot.content.split('\n').length,
        // Inherit the caller agent's visibility so a private agent's crawl
        // lands under the caller's private Pages. Public / null β†’ fall
        // through to the model-layer default for `sourceType='web'`.
        ...(this.callerAgentVisibility === 'private' ? { visibility: 'private' as const } : {}),
      });
      documentId = created.id;
      status = 'created';
    }

    // Topic binding fires across all three statuses: the user may open the
    // same URL in a new topic on a later crawl, and the binding should
    // appear there even if the underlying document didn't change.
    // `topicDocumentModel.associate` is idempotent on (documentId, topicId).
    if (topicId) {
      await this.topicDocumentModel.associate({ documentId, topicId });
    }

    return { id: documentId, status };
  };
}