Skip to content

The open alternative to Salesforce, designed for AI.

16.6 KB
Raw Blame
import { Injectable, Logger } from '@nestjs/common';

import { type AgentRunSummary } from 'twenty-shared/ai';
import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
import { isDefined } from 'twenty-shared/utils';
import { IsNull, Not, Raw } from 'typeorm';

import { formatErrorWithCause } from 'src/engine/metadata-modules/ai/ai-chat/utils/format-error-with-cause.util';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { type QueueJobScope } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
import { computePendingWakeUpRetryDelayMs } from 'src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util';
import { CONTINUE_AGENT_RUN_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/continue-agent-run-job-name.constant';
import { DELIVER_AGENT_RUN_OUTCOME_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/deliver-agent-run-outcome-job-name.constant';
import { AGENT_WAIT_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-tool-names.constant';
import { buildWaitOutcomeToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util';
import { AgentRunJobScopeService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { type AgentConversationWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type';
import { type AgentRunOutcomeDelivery } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type';
import { type AgentRunSuspension } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-suspension.type';
import { type ContinueAgentRunJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type';
import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import {
  AiException,
  AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';

// one key for every run, so the owner's unique key leaves a conversation one suspended run
const SUSPENDED_RUN_WAKE_UP_KEY = 'RUN';

type ConversationWakeUps = Pick<
  AgentConversationWait,
  'suspendedRun' | 'hasPostedCall'
>;

const isHeldByWakeUp = ({ suspendedRun, hasPostedCall }: ConversationWakeUps) =>
  isDefined(suspendedRun) || hasPostedCall;

const buildAnswerInThreadCondition = (threadId: string) =>
  Raw((alias) => `${alias} @> :condition::jsonb`, {
    condition: JSON.stringify({ type: 'ANSWER', threadId }),
  });

// A suspended run is the AGENT_RUN wake-up its conversation owns: what wakes it up, and in its
// payload what continues it and who gets its outcome
@Injectable()
export class AgentRunSuspensionService {
  private readonly logger = new Logger(AgentRunSuspensionService.name);

  constructor(
    @InjectWorkspaceScopedRepository(PendingWakeUpEntity)
    private readonly wakeUpRepository: WorkspaceScopedRepository<PendingWakeUpEntity>,
    @InjectAgentHistoryRepository('agentChatThread')
    private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
    @InjectAgentHistoryRepository('agentMessagePart')
    private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
    private readonly threadLifecycleService: AgentChatThreadLifecycleService,
    private readonly turnRecorderService: AgentTurnRecorderService,
    private readonly pendingWakeUpService: PendingWakeUpService,
    private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
    private readonly agentRunJobScopeService: AgentRunJobScopeService,
    @InjectMessageQueue(MessageQueue.aiQueue)
    private readonly messageQueueService: MessageQueueService,
  ) {}

  async suspend({
    workspaceId,
    threadId,
    condition,
    suspension,
  }: {
    workspaceId: string;
    threadId: string;
    condition: PendingWakeUpCondition;
    suspension: AgentRunSuspension;
  }): Promise<void> {
    await this.pendingWakeUpService.arm({
      workspaceId,
      owner: {
        type: 'AGENT_RUN',
        id: threadId,
        key: SUSPENDED_RUN_WAKE_UP_KEY,
      },
      condition,
      payload: suspension,
    });
  }

  // a run waiting in the conversation would read another run's prompt on continuing, and a call
  // a caller such as a workflow step posted there waits on its own answer
  async findConversationWait({
    workspaceId,
    thread: { id: threadId, pendingQuestionMessageId },
  }: {
    workspaceId: string;
    thread: Pick<
      AgentChatThreadWorkspaceEntity,
      'id' | 'pendingQuestionMessageId'
    >;
  }): Promise<AgentConversationWait> {
    const wakeUps = await this.findConversationWakeUps({
      workspaceId,
      threadId,
    });

    return {
      pendingQuestionMessageId,
      ...wakeUps,
      isWaiting: isDefined(pendingQuestionMessageId) || isHeldByWakeUp(wakeUps),
    };
  }

  // a question the member was asked in chat does not hold the conversation from a run
  async assertConversationNotSuspended({
    workspaceId,
    threadId,
  }: {
    workspaceId: string;
    threadId: string;
  }): Promise<void> {
    if (
      isHeldByWakeUp(
        await this.findConversationWakeUps({ workspaceId, threadId }),
      )
    ) {
      throw new AiException(
        'The conversation is waiting on an earlier run; send the next message once it has finished',
        AiExceptionCode.THREAD_AWAITING_ANSWER,
      );
    }
  }

  // the wake-up stays while its run goes on, so another resolution of it is let go rather than queued behind it
  async scheduleContinuation(jobData: ContinueAgentRunJobData): Promise<void> {
    await this.messageQueueService.add<ContinueAgentRunJobData>(
      CONTINUE_AGENT_RUN_JOB_NAME,
      jobData,
      {
        deduplication: { id: `continue-agent-run-${jobData.wakeUpId}` },
        ...(await this.resolveContinuationJobScope(jobData)),
      },
    );
  }

  private async resolveContinuationJobScope({
    workspaceId,
    wakeUpId,
  }: ContinueAgentRunJobData): Promise<QueueJobScope> {
    const wakeUp = await this.pendingWakeUpService.find({
      workspaceId,
      wakeUpId,
    });

    if (!isDefined(wakeUp)) {
      return { workspaceId, isWorkspaceJob: true };
    }

    const suspension = wakeUp.payload as AgentRunSuspension;

    return this.agentRunJobScopeService.resolve({
      workspaceId,
      spec: suspension.runSpec,
    });
  }

  // A run that ended, or could not go on, leaves nothing to wait on, and its caller gets the outcome
  async settle({
    workspaceId,
    threadId,
    suspension: { caller, summary: suspendedSummary },
    outcome,
    summary = suspendedSummary,
    isAwaitingAnswer = false,
    streamId,
  }: {
    workspaceId: string;
    threadId: string;
    suspension: AgentRunSuspension;
    outcome: AgentRunCallerOutcome;
    summary?: AgentRunSummary | null;
    isAwaitingAnswer?: boolean;
    streamId?: string;
  }): Promise<void> {
    await this.closeAwaitedCalls({
      workspaceId,
      threadId,
      isAwaitingAnswer,
      streamId,
    });

    await this.deliverOutcome({
      workspaceId,
      caller,
      threadId,
      outcome,
      summary: summary ?? null,
    });
  }

  // a workflow step is marked pending only after its executor returns, so an outcome that comes sooner is delivered later
  async deliverOutcome(delivery: AgentRunOutcomeDelivery): Promise<void> {
    const { workspaceId, caller, attempt = 0 } = delivery;
    const handler = this.callerHandlerRegistry.getHandlerOrThrow(caller.type);

    if (!isDefined(handler.onOutcome)) {
      return;
    }

    try {
      const waitingState = await handler.getWaitingState({
        workspaceId,
        caller,
      });

      if (waitingState === 'GONE') {
        await handler.onCallerGone?.(delivery);

        return;
      }

      if (waitingState === 'WAITING') {
        await handler.onOutcome(delivery);

        return;
      }
    } catch (error) {
      const threadLabel = isDefined(delivery.threadId)
        ? ` in thread ${delivery.threadId}`
        : '';

      // the run already ended, so a failed delivery is tried again rather than lost with the job
      this.logger.warn(
        `Could not deliver the outcome of the run${threadLabel} of workspace ${workspaceId}: ${formatErrorWithCause(error)}`,
      );
    }

    await this.messageQueueService.add<AgentRunOutcomeDelivery>(
      DELIVER_AGENT_RUN_OUTCOME_JOB_NAME,
      { ...delivery, attempt: attempt + 1 },
      {
        delay: computePendingWakeUpRetryDelayMs(attempt),
        workspaceId,
        isWorkspaceJob: true,
      },
    );
  }

  // A caller that stops waiting drops its suspended runs, such as every step of a run that ended
  async releaseForCaller({
    workspaceId,
    caller,
  }: {
    workspaceId: string;
    // matched by containment, so a partial ref releases every run it covers
    caller: AgentRunCaller;
  }): Promise<void> {
    const wakeUps = await this.wakeUpRepository.find(workspaceId, {
      where: {
        ownerType: 'AGENT_RUN',
        payload: Raw((alias) => `${alias} @> :payload::jsonb`, {
          payload: JSON.stringify({ caller }),
        }),
      },
    });

    for (const wakeUp of wakeUps) {
      await this.release({ workspaceId, wakeUp });
    }
  }

  // A run that is dropped no longer waits, nor do the calls it waited on
  async release({
    workspaceId,
    wakeUp: { id, ownerId: threadId, condition },
  }: {
    workspaceId: string;
    wakeUp: PendingWakeUpEntity;
  }): Promise<void> {
    if (
      isDefined(
        await this.pendingWakeUpService.claim({ workspaceId, wakeUpId: id }),
      )
    ) {
      await this.closeAwaitedCalls({
        workspaceId,
        threadId,
        isAwaitingAnswer: condition.type === 'ANSWER',
      });
    }
  }

  // The calls a dropped run waited on are closed, so they no longer look waiting. An answer holding
  // the conversation's claim closes its calls itself, and a question the member asked of their own
  // stays open, as only a run that waited on an answer closes the pending question
  async closeAwaitedCalls({
    workspaceId,
    threadId,
    isAwaitingAnswer,
    streamId,
  }: {
    workspaceId: string;
    threadId: string;
    isAwaitingAnswer: boolean;
    // the stream of a run that closes its calls while it holds the conversation
    streamId?: string;
  }): Promise<void> {
    await this.recordWaitOutcome({
      workspaceId,
      threadId,
      outcome: { type: 'CANCELLED' },
    });

    if (isAwaitingAnswer) {
      await this.closePendingQuestion({ workspaceId, threadId, streamId });
    }
  }

  // A wait call stays pending in the conversation until its wake-up resolves it, then carries the
  // outcome, and the turn that waited on it ends with it
  async recordWaitOutcome({
    workspaceId,
    threadId,
    outcome,
  }: {
    workspaceId: string;
    threadId: string;
    outcome: Parameters<typeof buildWaitOutcomeToolOutput>[0];
  }): Promise<void> {
    const waitMessages = await this.messagePartRepository.query(
      workspaceId,
      ({ manager, table }) =>
        manager.query<{ messageId: string }[]>(
          `WITH closed_wait AS (
             UPDATE ${table('agentMessagePart')} part SET "toolOutput" = $2::jsonb, "updatedAt" = now()
             FROM ${table('agentMessage')} message
             WHERE message.id = part."messageId" AND message."threadId" = $1
               AND part."toolName" = ANY($3) AND part."toolOutput"->'result'->>'status' = 'pending'
             RETURNING part."messageId"
           ) SELECT DISTINCT "messageId" FROM closed_wait`,
          [
            threadId,
            JSON.stringify(buildWaitOutcomeToolOutput(outcome)),
            AGENT_WAIT_TOOL_NAMES,
          ],
        ),
    );

    for (const { messageId } of waitMessages) {
      // the turn only shows what happened, so failing to end it must not fail the run or its release
      await this.turnRecorderService
        .endWaitingTurn({
          workspaceId,
          messageId,
          status:
            outcome.type === 'CANCELLED'
              ? AgentTurnStatus.CANCELLED
              : AgentTurnStatus.COMPLETED,
        })
        .catch((error: unknown) =>
          this.logger.warn(
            `Could not end the turn of wait message ${messageId}: ${formatErrorWithCause(error)}`,
          ),
        );
    }
  }

  // A call a caller posted stops waiting with the caller's wake-up
  async closePostedCalls({
    workspaceId,
    cancelledWakeUps,
  }: {
    workspaceId: string;
    cancelledWakeUps: PendingWakeUpEntity[];
  }): Promise<void> {
    for (const { condition } of cancelledWakeUps) {
      if (condition.type === 'ANSWER') {
        await this.closePendingQuestion({
          workspaceId,
          threadId: condition.threadId,
          toolCallId: condition.toolCallId,
        });
      }
    }
  }

  // without a call to look for, the pending question is the one waited on
  async closePendingQuestion({
    workspaceId,
    threadId,
    toolCallId,
    streamId,
    turnStatus = AgentTurnStatus.CANCELLED,
  }: {
    workspaceId: string;
    threadId: string;
    toolCallId?: string;
    streamId?: string;
    turnStatus?: AgentTurnStatus.COMPLETED | AgentTurnStatus.CANCELLED;
  }): Promise<void> {
    const thread = await this.threadRepository.findOne(workspaceId, {
      where: {
        id: threadId,
        pendingQuestionMessageId: Not(IsNull()),
        activeStreamId: streamId ?? IsNull(),
      },
      select: ['id', 'pendingQuestionMessageId'],
    });
    const messageId = thread?.pendingQuestionMessageId;

    if (
      !isDefined(messageId) ||
      (isDefined(toolCallId) &&
        !(await this.messagePartRepository.existsBy(workspaceId, {
          messageId,
          toolCallId,
        })))
    ) {
      return;
    }

    await this.threadLifecycleService.closePendingQuestion({
      workspaceId,
      threadId,
      messageId,
      activeStreamId: streamId ?? null,
      turnStatus,
    });
  }

  private async findConversationWakeUps({
    workspaceId,
    threadId,
  }: {
    workspaceId: string;
    threadId: string;
  }): Promise<ConversationWakeUps> {
    const wakeUps = await this.wakeUpRepository.find(workspaceId, {
      where: [
        { ownerType: 'AGENT_RUN', ownerId: threadId },
        { condition: buildAnswerInThreadCondition(threadId) },
      ],
      select: ['id', 'ownerType', 'ownerId'],
    });

    return {
      suspendedRun:
        wakeUps.find(
          ({ ownerType, ownerId }) =>
            ownerType === 'AGENT_RUN' && ownerId === threadId,
        ) ?? null,
      hasPostedCall: wakeUps.some(({ ownerType }) => ownerType !== 'AGENT_RUN'),
    };
  }
}