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.

26.2 KB
Raw Blame
import type { ChatTopicMetadata } from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull, max, ne } from 'drizzle-orm';

import { normalizeProjectRepository } from '../../models/environment';
import { EnvironmentInstanceModel } from '../../models/environmentInstance';
import { ProjectModel } from '../../models/project';
import {
  normalizeProjectDirectory,
  ProjectWorkingDirectoryModel,
} from '../../models/projectWorkingDirectory';
import { hasLiveTaskCallbackReservation } from '../../models/topic';
import {
  agents,
  devices,
  environments,
  projectEnvironments,
  projectWorkingDirectories,
  topics,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { mergeRepositories, ProjectEnvironmentRepository } from '../projectEnvironment';

/**
 * A refused directory write. It carries its tRPC code, so a permission or
 * state problem reaches the client as a 4xx with this message instead of
 * being wrapped as an internal server error.
 */
export class ProjectDirectoryError extends TRPCError {
  constructor(code: 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'NOT_FOUND', message: string) {
    super({ code, message });
    this.name = 'ProjectDirectoryError';
  }
}

export type SkippedProjectTopicReason =
  'differentLocation' | 'notFound' | 'otherProject' | 'running';

export interface SkippedProjectTopic {
  id: string;
  reason: SkippedProjectTopicReason;
}

/**
 * Point a conversation at another device directory. The cwd and CLI session
 * only hold on the old machine, so they are dropped rather than carried over.
 */
const pinTopicToDirectory = (
  metadata: ChatTopicMetadata | null | undefined,
  deviceId: string,
  path: string,
): ChatTopicMetadata => {
  const {
    heteroSessionBindingKey: _bindingKey,
    heteroSessionBindingKeyByWorkingDirectory: _bindingKeys,
    heteroSessionId: _sessionId,
    heteroSessionIdByWorkingDirectory: _sessionIds,
    ...rest
  } = metadata ?? {};
  return {
    ...rest,
    boundDeviceId: deviceId,
    workingDirectory: path,
    workingDirectoryConfig: { path },
  };
};

const isTopicInFlight = (topic: { metadata?: ChatTopicMetadata | null; status?: string | null }) =>
  topic.status === 'running' ||
  !!topic.metadata?.runningOperation ||
  hasLiveTaskCallbackReservation(topic.metadata);

export interface RelocateProjectDirectoryInput {
  /**
   * The topics the caller was authorized to move. A topic bound to the
   * directory after that check fails the relocation instead of moving
   * unchecked.
   */
  authorizedTopicIds?: string[];
  deviceId: string;
  id: string;
  path: string;
  projectId: string;
}

export interface BindProjectDirectoryInput {
  agentId?: string;
  deviceId: string;
  /** Ignored: a folder always works in the project's own environment. Kept for older clients. */
  environmentId?: string;
  name: string;
  path: string;
  projectId: string;
  repositoryUrl?: string;
  topicIds?: string[];
}

/**
 * Cross-aggregate write flows for project working directories. Binding a
 * directory upserts the environment, its device instance, the project link and
 * the directory row β€” and optionally files existing conversations β€” as one
 * transaction, so it lives here rather than on any single-aggregate model.
 * Read paths stay on {@link ProjectWorkingDirectoryModel}.
 */
export class ProjectDirectoryRepository {
  constructor(
    private readonly db: LobeChatDatabase,
    private readonly userId: string,
    private readonly workspaceId?: string,
  ) {}

  private scope() {
    return { userId: this.userId, workspaceId: this.workspaceId };
  }

  private async assertManageableProject(projectId: string) {
    const project = await new ProjectModel(
      this.db,
      this.userId,
      this.workspaceId,
    ).findManageableById(projectId);
    if (!project)
      throw new ProjectDirectoryError('NOT_FOUND', 'Project not found or access denied');
    return project;
  }

  async bind(input: BindProjectDirectoryInput) {
    const project = await this.assertManageableProject(input.projectId);
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const instanceModel = new EnvironmentInstanceModel(db, this.userId, this.workspaceId);
      const directoryModel = new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId);
      // Serialize bindings of the same device, including bindings from different projects.
      const [device] = await db
        .select()
        .from(devices)
        .where(
          and(eq(devices.deviceId, input.deviceId), buildWorkspaceWhere(this.scope(), devices)),
        )
        .for('update');
      if (!device)
        throw new ProjectDirectoryError('NOT_FOUND', 'Device not found or access denied');
      const path = normalizeProjectDirectory(input.path, device.platform);
      const repositoryUrl = input.repositoryUrl
        ? normalizeProjectRepository(input.repositoryUrl)
        : undefined;
      const existing = await instanceModel.findByDeviceAndDirectory(device.id, path);
      // A folder works in the project's own environment β€” the only one it has.
      // A folder some other environment already built is that one's.
      let environment = await ProjectEnvironmentRepository.ensure(db, project);
      if (existing && existing.environmentId !== environment.id)
        throw new ProjectDirectoryError(
          'CONFLICT',
          'This directory belongs to another environment',
        );
      // A folder that is a checkout of a repository the environment does not
      // list yet adds it, the same as adding it on the project's settings.
      if (repositoryUrl) {
        const configuration = mergeRepositories(environment.configuration, [
          { sources: [{ kind: 'git', url: repositoryUrl }] },
        ]);
        if (configuration !== environment.configuration) {
          [environment] = await db
            .update(environments)
            .set({ configuration, updatedAt: new Date() })
            .where(eq(environments.id, environment.id))
            .returning();
        }
      }
      let instance = existing;
      if (!instance) {
        instance = await instanceModel.createForDeviceBinding({
          configurationSnapshot: environment.configuration,
          deviceId: device.id,
          environmentId: environment.id,
          name: input.name.trim(),
          workingDirectory: path,
        });
      }
      if (!instance.enabled)
        throw new ProjectDirectoryError('BAD_REQUEST', 'Environment instance is disabled');
      const prior = await directoryModel.findByLocation(input.projectId, device.id, path);
      const directory =
        prior ??
        (await ProjectDirectoryRepository.placeNewDirectory(
          db,
          input.projectId,
          environment.id,
          await directoryModel.create({
            addedByUserId: this.userId,
            deviceId: device.id,
            name: input.name.trim(),
            path,
            projectId: input.projectId,
            workspaceId: this.workspaceId,
          }),
        ));
      const skippedTopics: SkippedProjectTopic[] = [];
      if (input.topicIds?.length) {
        if (!input.agentId)
          throw new ProjectDirectoryError(
            'BAD_REQUEST',
            'Agent is required when filing conversations',
          );
        const [filingAgent] = await db
          .select()
          .from(agents)
          .where(and(eq(agents.id, input.agentId), buildWorkspaceWhere(this.scope(), agents)));
        if (
          !filingAgent ||
          (filingAgent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
            filingAgent.agencyConfig.boundDeviceId !== device.deviceId)
        )
          throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
        const topicIds = [...new Set(input.topicIds)];
        const selected = await db
          .select()
          .from(topics)
          .where(
            // Workspace-scoped, not creator-scoped: a shared agent's directory
            // holds every member's conversations, and `topics.userId` only
            // records who started one. The router already authorized the
            // caller to use them. Share-visitor topics (`senderId`) stay out:
            // they are hidden from members, and filing one into a project
            // would list it there.
            and(
              inArray(topics.id, topicIds),
              eq(topics.agentId, input.agentId),
              buildWorkspaceWhere(this.scope(), topics),
              isNull(topics.deletedAt),
              isNull(topics.senderId),
            ),
          )
          .for('update');
        const found = new Set(selected.map((topic) => topic.id));
        for (const id of topicIds)
          if (!found.has(id)) skippedTopics.push({ id, reason: 'notFound' });
        const filedTopicIds: string[] = [];
        // Filing is a convenience on top of the binding: one conversation that
        // cannot move must not cost the directory or the others, so it is
        // skipped and reported instead of failing the whole bind.
        for (const topic of selected) {
          const metadata = topic.metadata ?? {};
          const source = getWorkingDirSourcePath(
            metadata.workingDirectoryConfig ?? metadata.workingDirectory,
          );
          const pinnedDevice = metadata.boundDeviceId ?? metadata.runningOperation?.deviceId;
          const reason: SkippedProjectTopicReason | undefined =
            !source ||
            normalizeProjectDirectory(source, device.platform) !== path ||
            (pinnedDevice && pinnedDevice !== device.deviceId)
              ? 'differentLocation'
              : topic.projectId && topic.projectId !== input.projectId
                ? 'otherProject'
                : metadata.runningOperation || topic.status === 'running'
                  ? 'running'
                  : undefined;
          if (reason) {
            skippedTopics.push({ id: topic.id, reason });
            continue;
          }
          await db
            .update(topics)
            .set({
              projectId: input.projectId,
              projectWorkingDirectoryId: directory.id,
              metadata: { ...metadata, boundDeviceId: device.deviceId },
            })
            .where(eq(topics.id, topic.id));
          filedTopicIds.push(topic.id);
        }
        await joinTopicAgentsToProjects(db, { topicIds: filedTopicIds });
      }
      return { ...directory, skippedTopics };
    });
  }

  async associateTopic(projectId: string, topicId: string, directoryId?: string) {
    await this.assertManageableProject(projectId);
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const directory = directoryId
        ? await new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId).resolve(
            directoryId,
            projectId,
          )
        : undefined;
      const [topic] = await db
        .select()
        .from(topics)
        .where(
          // Workspace-scoped, not creator-scoped, without share-visitor
          // topics β€” see `bind`.
          and(
            eq(topics.id, topicId),
            buildWorkspaceWhere(this.scope(), topics),
            isNull(topics.deletedAt),
            isNull(topics.senderId),
          ),
        )
        .for('update');
      if (!topic) throw new ProjectDirectoryError('NOT_FOUND', 'Topic not found or access denied');
      if (topic.projectId && topic.projectId !== projectId)
        throw new ProjectDirectoryError('CONFLICT', 'Topic already belongs to another project');
      if (topic.status === 'running' || topic.metadata?.runningOperation)
        throw new ProjectDirectoryError(
          'CONFLICT',
          'Wait for the running topic to finish before associating it',
        );
      const source = getWorkingDirSourcePath(
        topic.metadata?.workingDirectoryConfig ?? topic.metadata?.workingDirectory,
      );
      if (source && !directory)
        throw new ProjectDirectoryError('BAD_REQUEST', 'Select the existing working directory');
      const pinned = topic.metadata?.boundDeviceId;
      if (
        directory &&
        ((source && normalizeProjectDirectory(source, directory.platform) !== directory.path) ||
          (pinned && pinned !== directory.deviceId))
      )
        throw new ProjectDirectoryError(
          'BAD_REQUEST',
          'Keep the existing device and working directory',
        );
      if (topic.projectWorkingDirectoryId && topic.projectWorkingDirectoryId !== directoryId)
        throw new ProjectDirectoryError('CONFLICT', 'Keep the existing project directory binding');
      if (directory && topic.agentId) {
        const [agent] = await db
          .select()
          .from(agents)
          .where(and(eq(agents.id, topic.agentId), buildWorkspaceWhere(this.scope(), agents)));
        if (
          !agent ||
          (agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
            agent.agencyConfig.boundDeviceId !== directory.deviceId)
        )
          throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
      }
      const [updated] = await db
        .update(topics)
        .set({
          projectId,
          ...(directory
            ? {
                projectWorkingDirectoryId: directory.id,
                metadata: {
                  ...topic.metadata,
                  boundDeviceId: directory.deviceId,
                  workingDirectory: directory.path,
                  workingDirectoryConfig: { path: directory.path },
                },
              }
            : {}),
        })
        .where(eq(topics.id, topicId))
        .returning();
      await joinTopicAgentsToProjects(db, { topicIds: [topicId] });
      return updated;
    });
  }

  /**
   * Remove a directory from its project. Only the project's link goes: the
   * environment instance is keyed by (device, path) and may serve other
   * projects, and the conversations stay in the project with the foreign key
   * clearing their directory binding.
   */
  async remove(projectId: string, directoryId: string) {
    await this.assertManageableProject(projectId);
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const bound = await db
        .select()
        .from(topics)
        .where(
          and(
            eq(topics.projectId, projectId),
            eq(topics.projectWorkingDirectoryId, directoryId),
            isNull(topics.deletedAt),
          ),
        )
        .for('update');
      // A run that already resolved this directory would finish against a
      // binding that no longer exists. The row locks serialize with its
      // reservation write, as in `moveTopic`.
      if (bound.some(isTopicInFlight))
        throw new ProjectDirectoryError(
          'CONFLICT',
          'Wait for the running topics to finish before removing this directory',
        );
      const [removed] = await db
        .delete(projectWorkingDirectories)
        .where(
          and(
            eq(projectWorkingDirectories.id, directoryId),
            eq(projectWorkingDirectories.projectId, projectId),
          ),
        )
        .returning();
      if (!removed) throw new ProjectDirectoryError('NOT_FOUND', 'Project directory not found');
      return removed;
    });
  }

  /**
   * Point a directory at another device location, for a binding made with the
   * wrong path. The new location is bound like any other (same environment),
   * the directory's conversations follow it as in `moveTopic`, and the old row
   * goes β€” so no conversation is left pinned to a path its directory no longer
   * names. The caller has already confirmed the new path exists on the device.
   */
  async relocate(input: RelocateProjectDirectoryInput) {
    await this.assertManageableProject(input.projectId);
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const current = (
        await new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId).list(
          input.projectId,
        )
      ).find((row) => row.id === input.id);
      if (!current) throw new ProjectDirectoryError('NOT_FOUND', 'Project directory not found');
      const bound = await db
        .select()
        .from(topics)
        .where(
          and(
            eq(topics.projectId, input.projectId),
            eq(topics.projectWorkingDirectoryId, input.id),
            isNull(topics.deletedAt),
          ),
        )
        .for('update');
      if (bound.some(isTopicInFlight))
        throw new ProjectDirectoryError(
          'CONFLICT',
          'Wait for the running topics to finish before changing this directory',
        );
      const authorized = input.authorizedTopicIds && new Set(input.authorizedTopicIds);
      if (authorized && bound.some((topic) => !authorized.has(topic.id)))
        throw new ProjectDirectoryError(
          'CONFLICT',
          'The topics in this directory changed; try again',
        );
      const next = await new ProjectDirectoryRepository(db, this.userId, this.workspaceId).bind({
        deviceId: input.deviceId,
        environmentId: current.environmentId ?? undefined,
        name: input.path.split(/[\\/]/).findLast(Boolean) || input.path,
        path: input.path,
        projectId: input.projectId,
      });
      if (next.id === input.id) return next;
      const agentIds = [
        ...new Set(bound.flatMap((topic) => (topic.agentId ? [topic.agentId] : []))),
      ];
      const boundAgents = agentIds.length
        ? await db
            .select()
            .from(agents)
            .where(and(inArray(agents.id, agentIds), buildWorkspaceWhere(this.scope(), agents)))
        : [];
      if (
        boundAgents.some(
          (agent) =>
            agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
            agent.agencyConfig.boundDeviceId !== input.deviceId,
        )
      )
        throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
      for (const topic of bound)
        await db
          .update(topics)
          .set({
            metadata: pinTopicToDirectory(topic.metadata, input.deviceId, next.path),
            projectWorkingDirectoryId: next.id,
          })
          .where(eq(topics.id, topic.id));
      await db.delete(projectWorkingDirectories).where(eq(projectWorkingDirectories.id, input.id));
      return next;
    });
  }

  /**
   * Move a project-directory conversation to its project's directory on another
   * device. The directory belongs to the project, so switching devices means
   * switching to that project's directory there β€” never to an arbitrary path.
   * The cwd and CLI session only hold on the old machine, so they go with it.
   */
  /**
   * The cloud sandbox's place among the project's execution environments.
   * The device folders keep theirs on their own rows (`sortOrder`); the
   * sandbox keeps its on the link to the project's own environment. On a tie
   * a folder comes first: a project that never reordered anything tries its
   * folders before falling back to the sandbox.
   */
  async executionOrder(projectId: string): Promise<{ sandbox: number }> {
    const project = await new ProjectModel(this.db, this.userId, this.workspaceId).findById(
      projectId,
    );
    if (!project)
      throw new ProjectDirectoryError('NOT_FOUND', 'Project not found or access denied');
    const environment = await ProjectEnvironmentRepository.ensure(this.db, project);
    return {
      sandbox: await ProjectDirectoryRepository.sandboxOrder(this.db, projectId, environment.id),
    };
  }

  /**
   * Reorder the project's execution environments β€” its device folders and the
   * cloud sandbox (`'sandbox'`) β€” into the given order, which is the priority
   * a new conversation follows. Ids that are not this project's folders are
   * refused rather than ignored, so a stale list cannot silently half-apply.
   */
  async reorderExecutionEnvironments(projectId: string, order: string[]) {
    const project = await this.assertManageableProject(projectId);
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const environment = await ProjectEnvironmentRepository.ensure(db, project);
      const directoryIds = order.filter((id) => id !== 'sandbox');
      if (directoryIds.length > 0) {
        const owned = await db
          .select({ id: projectWorkingDirectories.id })
          .from(projectWorkingDirectories)
          .where(
            and(
              eq(projectWorkingDirectories.projectId, projectId),
              inArray(projectWorkingDirectories.id, directoryIds),
            ),
          );
        if (owned.length !== new Set(directoryIds).size)
          throw new ProjectDirectoryError('BAD_REQUEST', 'Unknown project directory in order');
      }
      for (const [index, id] of order.entries()) {
        if (id === 'sandbox')
          await db
            .update(projectEnvironments)
            .set({ sortOrder: index, updatedAt: new Date() })
            .where(
              and(
                eq(projectEnvironments.projectId, projectId),
                eq(projectEnvironments.environmentId, environment.id),
              ),
            );
        else
          await db
            .update(projectWorkingDirectories)
            .set({ sortOrder: index })
            .where(
              and(
                eq(projectWorkingDirectories.projectId, projectId),
                eq(projectWorkingDirectories.id, id),
              ),
            );
      }
    });
  }

  private static async sandboxOrder(
    db: LobeChatDatabase,
    projectId: string,
    environmentId: string,
  ): Promise<number> {
    const [link] = await db
      .select({ sortOrder: projectEnvironments.sortOrder })
      .from(projectEnvironments)
      .where(
        and(
          eq(projectEnvironments.projectId, projectId),
          eq(projectEnvironments.environmentId, environmentId),
        ),
      );
    return link?.sortOrder ?? 0;
  }

  /**
   * Give a folder just added its place: before the cloud sandbox when the
   * sandbox is last β€” the fallback stays the fallback β€” and otherwise at the
   * end, after whatever the person put ahead of it.
   */
  private static async placeNewDirectory<T extends { id: string; sortOrder: number }>(
    db: LobeChatDatabase,
    projectId: string,
    environmentId: string,
    directory: T,
  ): Promise<T> {
    const sandbox = await ProjectDirectoryRepository.sandboxOrder(db, projectId, environmentId);
    const [{ last }] = await db
      .select({ last: max(projectWorkingDirectories.sortOrder) })
      .from(projectWorkingDirectories)
      .where(
        and(
          eq(projectWorkingDirectories.projectId, projectId),
          ne(projectWorkingDirectories.id, directory.id),
        ),
      );
    const lastFolder = last ?? 0;
    // Nothing reordered yet: every place is 0, and a tie puts folders first.
    if (sandbox === 0 && lastFolder === 0) return directory;

    const sortOrder = sandbox > lastFolder ? sandbox : lastFolder + 1;
    if (sandbox > lastFolder)
      await db
        .update(projectEnvironments)
        .set({ sortOrder: sandbox + 1, updatedAt: new Date() })
        .where(
          and(
            eq(projectEnvironments.projectId, projectId),
            eq(projectEnvironments.environmentId, environmentId),
          ),
        );
    const [placed] = await db
      .update(projectWorkingDirectories)
      .set({ sortOrder })
      .where(eq(projectWorkingDirectories.id, directory.id))
      .returning();
    return { ...directory, sortOrder: placed.sortOrder };
  }

  async moveTopic(topicId: string, directoryId: string) {
    return this.db.transaction(async (tx) => {
      const db = tx as LobeChatDatabase;
      const [topic] = await db
        .select()
        .from(topics)
        .where(
          // Workspace-scoped, not creator-scoped: `topics.userId` only records
          // who started a shared topic, and any member the router authorized to
          // use it may move it.
          and(
            eq(topics.id, topicId),
            buildWorkspaceWhere(this.scope(), topics),
            isNull(topics.deletedAt),
          ),
        )
        .for('update');
      if (!topic) throw new ProjectDirectoryError('NOT_FOUND', 'Topic not found or access denied');
      if (!topic.projectId || !topic.projectWorkingDirectoryId)
        throw new ProjectDirectoryError('BAD_REQUEST', 'Topic is not bound to a project directory');
      // A start that holds the reservation may already have resolved the old
      // directory; moving under it would run the turn on the old machine while
      // the topic is persisted as bound to the new one. The row lock above
      // serializes with the reservation write.
      if (
        topic.status === 'running' ||
        topic.metadata?.runningOperation ||
        hasLiveTaskCallbackReservation(topic.metadata)
      )
        throw new ProjectDirectoryError(
          'CONFLICT',
          'Wait for the running topic to finish before moving it',
        );
      // Scoped to the topic's own project: another project's directory is not
      // a device switch, it is a different conversation context.
      const directory = await new ProjectWorkingDirectoryModel(
        db,
        this.userId,
        this.workspaceId,
      ).resolve(directoryId, topic.projectId);
      if (directory.id === topic.projectWorkingDirectoryId) return topic;
      if (topic.agentId) {
        const [agent] = await db
          .select()
          .from(agents)
          .where(and(eq(agents.id, topic.agentId), buildWorkspaceWhere(this.scope(), agents)));
        if (
          !agent ||
          (agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
            agent.agencyConfig.boundDeviceId !== directory.deviceId)
        )
          throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
      }
      const [updated] = await db
        .update(topics)
        .set({
          metadata: pinTopicToDirectory(topic.metadata, directory.deviceId, directory.path),
          projectWorkingDirectoryId: directory.id,
        })
        .where(eq(topics.id, topicId))
        .returning();
      return updated;
    });
  }
}