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.

15.6 KB
Raw Blame
import { isNotNull, sql } from 'drizzle-orm';
import type { AnyPgColumn } from 'drizzle-orm/pg-core';
import {
  boolean,
  index,
  integer,
  jsonb,
  pgTable,
  primaryKey,
  text,
  uniqueIndex,
  uuid,
  varchar,
} from 'drizzle-orm/pg-core';
import { createInsertSchema } from 'drizzle-zod';
import { z } from 'zod';

import type { LobeDocumentPage } from '@/types/document';
import type { FileSource, FileUploadSessionStatus } from '@/types/files';

import { idGenerator, randomSlug } from '../utils/idGenerator';
import {
  accessedAt,
  createdAt,
  softDeleteColumns,
  timestamps,
  timestamptz,
  updatedAt,
} from './_helpers';
import { asyncTasks } from './asyncTask';
import { users } from './user';
import { workspaces } from './workspace';

export const nextDocumentUpdatedAt = () =>
  sql`GREATEST(date_trunc('milliseconds', clock_timestamp()), "documents"."updated_at" + interval '1 millisecond')`;

export const DOCUMENT_FOLDER_TYPE = 'custom/folder';

/** File type used by the parent document for a managed skill bundle. */
export const SKILL_BUNDLE_FILE_TYPE = 'skills/bundle';

/** File type used by the SKILL.md index document inside a managed skill bundle. */
export const SKILL_INDEX_FILE_TYPE = 'skills/index';

/**
 * File type of a file beside `SKILL.md` in a skill bundle, its path in
 * `filename`. Text sits in `content`; a binary file links its `files` row
 * through `fileId`. Its MIME type and a script's language sit in `metadata`.
 */
export const SKILL_FILE_FILE_TYPE = 'skills/file';

/**
 * What a bundle's files were written as before they held more than scripts.
 * Still read; rewritten as `skills/file` the next time one is written.
 */
export const SKILL_SCRIPT_FILE_TYPE = 'skills/script';

/**
 * File type of a version snapshot of a user skill's `SKILL.md`, from before
 * versions were published as archives in `files`. Still read, never written.
 */
export const SKILL_VERSION_FILE_TYPE = 'skills/version';

/**
 * Source attribution of a user-level skill: a bundle owned by the user, not
 * bound to any agent, so any agent or run can load it by name.
 */
export const USER_SKILL_SOURCE = 'user-skills';

/** Source attribution stored on documents created by skill-management tooling. */
export const SKILL_MANAGEMENT_SOURCE = 'agent-signal:skill-management';

/** Source type stored on documents created by Agent Signal skill-management tooling. */
export const SKILL_MANAGEMENT_SOURCE_TYPE = 'agent-signal';

/** Canonical filename for a skill index document. */
export const SKILL_INDEX_FILENAME = 'SKILL.md';

/** Template id applied to agent document bindings that represent managed skills. */
export const AGENT_SKILL_TEMPLATE_ID = 'agent-skill';

export const globalFiles = pgTable(
  'global_files',
  {
    hashId: varchar('hash_id', { length: 64 }).primaryKey(),
    fileType: varchar('file_type', { length: 255 }).notNull(),
    size: integer('size').notNull(),
    url: text('url').notNull(),
    metadata: jsonb('metadata'),
    creator: text('creator')
      .references(() => users.id, { onDelete: 'set null' })
      .notNull(),
    createdAt: createdAt(),
    accessedAt: accessedAt(),
  },
  (t) => [index('global_files_creator_idx').on(t.creator)],
);

export type NewGlobalFile = typeof globalFiles.$inferInsert;
export type GlobalFileItem = typeof globalFiles.$inferSelect;

/**
 * Documents table - Stores file content or web search results
 */
export const documents = pgTable(
  'documents',
  {
    id: varchar('id', { length: 255 })
      .$defaultFn(() => idGenerator('documents', 16))
      .primaryKey(),

    // Basic information
    title: text('title'),
    description: text('description'),
    content: text('content'),

    // Special type: custom/folder
    fileType: varchar('file_type', { length: 255 }).notNull(),
    filename: text('filename'),

    // Statistics
    totalCharCount: integer('total_char_count').notNull(),
    totalLineCount: integer('total_line_count').notNull(),

    // Metadata
    metadata: jsonb('metadata').$type<Record<string, any>>(),

    // Page/chunk data
    pages: jsonb('pages').$type<LobeDocumentPage[]>(),

    // Source type
    sourceType: text('source_type', {
      enum: ['file', 'web', 'api', 'topic', 'agent', 'agent-signal'],
    }).notNull(),
    source: text('source').notNull(), // File path or web URL

    // Associated file (optional)
    // forward reference needs AnyPgColumn to avoid circular type inference

    fileId: text('file_id').references((): AnyPgColumn => files.id, { onDelete: 'set null' }),

    knowledgeBaseId: text('knowledge_base_id').references(() => knowledgeBases.id, {
      onDelete: 'set null',
    }),

    // Parent document (for folder hierarchy structure)
    parentId: varchar('parent_id', { length: 255 }).references((): AnyPgColumn => documents.id, {
      onDelete: 'set null',
    }),

    // User association
    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    clientId: text('client_id'),

    editorData: jsonb('editor_data').$type<Record<string, any>>(),

    slug: varchar('slug', { length: 255 }).$defaultFn(() => randomSlug(3)),

    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    /**
     * Agent that created this document through a tool (e.g. notebook or
     * knowledge base), used to separate agent output from user-authored
     * documents. `NULL` means user-created.
     */
    createdByAgentId: text('created_by_agent_id'),

    /**
     * Visibility within the owning workspace. `public` (default) means every
     * workspace member can see the document; `private` constrains it to the
     * creator (`user_id`). Within a documents tree (folder/Page hierarchy) the
     * value is kept strongly consistent across the whole subtree by the service
     * layer — children mirror the root's visibility. Standalone pages publish
     * via `private → public`; creator-owned pages inside a library synchronize
     * bidirectionally with the library. Ignored in personal mode where the row
     * is implicitly private to its owner.
     */
    visibility: text('visibility', { enum: ['private', 'public'] })
      .default('public')
      .notNull(),

    // Timestamps
    /** Recycle bin — see `schemas/trash.ts`. */
    ...softDeleteColumns(),
    ...timestamps,
    updatedAt: timestamptz('updated_at')
      .notNull()
      .defaultNow()
      .$onUpdate(() => nextDocumentUpdatedAt()),
  },
  (table) => [
    index('documents_source_idx').on(table.source),
    index('documents_file_type_idx').on(table.fileType),
    index('documents_source_type_idx').on(table.sourceType),
    index('documents_user_id_idx').on(table.userId),
    index('documents_file_id_idx').on(table.fileId),
    index('documents_parent_id_idx').on(table.parentId),
    index('documents_knowledge_base_id_idx').on(table.knowledgeBaseId),
    uniqueIndex('documents_client_id_user_id_unique').on(table.clientId, table.userId),
    uniqueIndex('documents_slug_user_id_unique')
      .on(table.slug, table.userId)
      .where(sql`${table.workspaceId} IS NULL AND ${table.slug} IS NOT NULL`),
    index('documents_workspace_id_idx').on(table.workspaceId),
    index('documents_workspace_visibility_idx').on(
      table.workspaceId,
      table.visibility,
      table.userId,
    ),
    uniqueIndex('documents_slug_workspace_id_unique')
      .on(table.workspaceId, table.slug)
      .where(isNotNull(table.workspaceId)),
  ],
);

export type NewDocument = typeof documents.$inferInsert;
export type DocumentItem = typeof documents.$inferSelect;
export const insertDocumentSchema = createInsertSchema(documents);

export const files = pgTable(
  'files',
  {
    id: text('id')
      .$defaultFn(() => idGenerator('files'))
      .primaryKey(),

    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    /**
     * mime
     */
    fileType: varchar('file_type', { length: 255 }).notNull(),
    /**
     * sha256
     */
    fileHash: varchar('file_hash', { length: 64 }).references(() => globalFiles.hashId, {
      onDelete: 'no action',
    }),
    name: text('name').notNull(),
    size: integer('size').notNull(),
    url: text('url').notNull(),
    source: text('source').$type<FileSource>(),

    // Parent Folder or Document
    parentId: varchar('parent_id', { length: 255 }).references((): AnyPgColumn => documents.id, {
      onDelete: 'set null',
    }),

    clientId: text('client_id'),
    metadata: jsonb('metadata'),
    chunkTaskId: uuid('chunk_task_id').references(() => asyncTasks.id, { onDelete: 'set null' }),
    embeddingTaskId: uuid('embedding_task_id').references(() => asyncTasks.id, {
      onDelete: 'set null',
    }),

    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    /**
     * Visibility within the owning workspace. `public` (default) means every
     * workspace member can see the file; `private` constrains it to the
     * creator (`user_id`). Standalone files publish via `private → public`;
     * creator-owned files inside a library synchronize bidirectionally with
     * the library. Ignored in personal mode (`workspace_id IS NULL`) where the
     * row is implicitly private to its owner.
     */
    visibility: text('visibility', { enum: ['private', 'public'] })
      .default('public')
      .notNull(),

    /** Recycle bin — see `schemas/trash.ts`. */
    ...softDeleteColumns(),
    ...timestamps,
  },
  (table) => {
    return {
      fileHashIdx: index('file_hash_idx').on(table.fileHash),
      userIdIdx: index('files_user_id_idx').on(table.userId),
      parentIdIdx: index('files_parent_id_idx').on(table.parentId),
      chunkTaskIdIdx: index('files_chunk_task_id_idx').on(table.chunkTaskId),
      embeddingTaskIdIdx: index('files_embedding_task_id_idx').on(table.embeddingTaskId),
      clientIdUnique: uniqueIndex('files_client_id_user_id_unique').on(
        table.clientId,
        table.userId,
      ),
      workspaceIdIdx: index('files_workspace_id_idx').on(table.workspaceId),
      workspaceVisibilityIdx: index('files_workspace_visibility_idx').on(
        table.workspaceId,
        table.visibility,
        table.userId,
      ),
    };
  },
);
export type NewFile = typeof files.$inferInsert;
export type FileItem = typeof files.$inferSelect;

/**
 * One row per direct S3 upload. Active rows reserve their declared bytes until
 * the object is either attached to a durable file or cleaned up.
 */
export const fileUploads = pgTable(
  'file_uploads',
  {
    id: uuid('id').defaultRandom().primaryKey(),
    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
    pathname: text('pathname').notNull(),
    /** Exact byte count reserved before upload credentials are issued. */
    size: integer('size').notNull(),
    status: text('status').$type<FileUploadSessionStatus>().default('active').notNull(),
    multipartUploadId: text('multipart_upload_id'),
    multipartPartSize: integer('multipart_part_size'),
    /** Set after S3 confirms a single or multipart object is complete. */
    completedAt: timestamptz('completed_at'),
    fileId: text('file_id').references(() => files.id, { onDelete: 'set null' }),
    expiresAt: timestamptz('expires_at').notNull(),
    createdAt: createdAt(),
    updatedAt: updatedAt(),
  },
  (table) => [
    index('file_uploads_user_scope_status_idx').on(table.userId, table.workspaceId, table.status),
    index('file_uploads_workspace_status_idx').on(table.workspaceId, table.status),
    index('file_uploads_status_expires_at_idx').on(table.status, table.expiresAt),
    index('file_uploads_status_updated_at_id_idx').on(table.status, table.updatedAt, table.id),
    uniqueIndex('file_uploads_live_pathname_unique')
      .on(table.pathname)
      .where(sql`${table.status} IN ('active', 'cleaning')`),
  ],
);

export type NewFileUpload = typeof fileUploads.$inferInsert;
export type FileUploadItem = typeof fileUploads.$inferSelect;

/** Knowledge-base visibility — shared by column def and insert schema. */
export const KNOWLEDGE_BASE_VISIBILITY = ['private', 'public'] as const;

/**
 * `knowledge_bases.type` values marking a library dedicated to one owner (an
 * agent's or project's own space). A NULL type is an ordinary user library.
 * Owned libraries are reached through their owner, never through library lists.
 */
export const DEDICATED_KNOWLEDGE_BASE_TYPES = ['agent', 'project'] as const;
export type DedicatedKnowledgeBaseType = (typeof DEDICATED_KNOWLEDGE_BASE_TYPES)[number];

export const knowledgeBases = pgTable(
  'knowledge_bases',
  {
    id: text('id')
      .$defaultFn(() => idGenerator('knowledgeBases'))
      .primaryKey(),

    name: text('name').notNull(),
    description: text('description'),
    avatar: text('avatar'),

    // different types of knowledge bases need to be distinguished
    type: text('type'),
    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    clientId: text('client_id'),

    isPublic: boolean('is_public').default(false),

    settings: jsonb('settings'),

    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    /**
     * Visibility within the owning workspace. `public` (default) means every
     * workspace member sees the KB in their sidebar; `private` constrains
     * discoverability to the creator (`user_id`). The only legal transition is
     * `private → public` via `publishKnowledgeBaseToWorkspace`. Ignored in
     * personal mode (`workspace_id IS NULL`).
     *
     * Independent of `isPublic` (marketplace discovery). Files and documents
     * keep their own visibility columns for direct-resource authorization, but
     * creator-owned rows inside a KB are synchronized to this value when the
     * library is published or made private.
     */
    visibility: text('visibility', { enum: KNOWLEDGE_BASE_VISIBILITY }).default('public').notNull(),

    /** Recycle bin — see `schemas/trash.ts`. */
    ...softDeleteColumns(),
    ...timestamps,
  },
  (t) => [
    uniqueIndex('knowledge_bases_client_id_user_id_unique').on(t.clientId, t.userId),
    index('knowledge_bases_user_id_idx').on(t.userId),
    index('knowledge_bases_workspace_id_idx').on(t.workspaceId),
    index('knowledge_bases_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
  ],
);

// See insertSessionGroupSchema: Zod 4 + drizzle-zod text-enum inference pollution.
// `.optional()` preserves defaulted-column omit semantics at runtime.
// Enum values from KNOWLEDGE_BASE_VISIBILITY so column def and schema stay in sync.
export const insertKnowledgeBasesSchema = createInsertSchema(knowledgeBases, {
  visibility: z.enum(KNOWLEDGE_BASE_VISIBILITY).optional(),
});

export type NewKnowledgeBase = typeof knowledgeBases.$inferInsert;
export type KnowledgeBaseItem = typeof knowledgeBases.$inferSelect;

export const knowledgeBaseFiles = pgTable(
  'knowledge_base_files',
  {
    knowledgeBaseId: text('knowledge_base_id')
      .references(() => knowledgeBases.id, { onDelete: 'cascade' })
      .notNull(),

    fileId: text('file_id')
      .references(() => files.id, { onDelete: 'cascade' })
      .notNull(),

    userId: text('user_id')
      .references(() => users.id, { onDelete: 'cascade' })
      .notNull(),
    workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),

    createdAt: createdAt(),
  },
  (t) => [
    primaryKey({ columns: [t.knowledgeBaseId, t.fileId] }),
    index('knowledge_base_files_kb_id_idx').on(t.knowledgeBaseId),
    index('knowledge_base_files_user_id_idx').on(t.userId),
    index('knowledge_base_files_file_id_idx').on(t.fileId),
    index('knowledge_base_files_workspace_id_idx').on(t.workspaceId),
  ],
);