Skip to content

The open alternative to Salesforce, designed for AI.

Keep the AI engine free of workflow code and remove duplicated agent run code (#27416)

Félix Malfait1fecfa669e39
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepLogsToolCallRow.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepLogsToolCallRow.tsx
index 846f37f654c..343e6183b3a 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepLogsToolCallRow.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepLogsToolCallRow.tsx
@@ -1,6 +1,6 @@
import { styled } from '@linaria/react';
import { useState } from 'react';
-import { type AiToolCallLog } from 'twenty-shared/workflow';
+import { type AgentRunToolCallLog } from 'twenty-shared/ai';
import { useToolDisplayContext } from '@/ai/hooks/useToolDisplayContext';
import { getToolIcon } from '@/ai/utils/getToolIcon';
@@ -142,7 +142,7 @@ type TabType = 'output' | 'input';
export const WorkflowRunStepLogsToolCallRow = ({
toolCall,
}: {
- toolCall: AiToolCallLog;
+ toolCall: AgentRunToolCallLog;
}) => {
const theme = useTheme();
const { t } = useLingui();
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/crons/jobs/pending-wake-up-sweep.cron.job.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/crons/jobs/pending-wake-up-sweep.cron.job.ts
index 9ff49389212..3d407ae95dd 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/crons/jobs/pending-wake-up-sweep.cron.job.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/crons/jobs/pending-wake-up-sweep.cron.job.ts
@@ -47,8 +47,12 @@ export class PendingWakeUpSweepCronJob {
[OVERDUE_WAKE_UPS_BATCH_SIZE],
);
+ // a wake-up stays overdue until its job claims it, so each sweep would queue it again
for (const overdueWakeUp of overdueWakeUps) {
- await this.pendingWakeUpService.scheduleOverdueResolution(overdueWakeUp);
+ await this.pendingWakeUpService.scheduleResolution({
+ wakeUp: overdueWakeUp,
+ deduplicationId: `overdue-pending-wake-up-${overdueWakeUp.id}`,
+ });
}
if (overdueWakeUps.length > 0) {
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.exception.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.exception.ts
deleted file mode 100644
index 90156cdbe9b..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.exception.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { type MessageDescriptor } from '@lingui/core';
-import { msg } from '@lingui/core/macro';
-import { assertUnreachable } from 'twenty-shared/utils';
-
-import {
- appendCommonExceptionCode,
- CustomException,
-} from 'src/utils/custom-exception';
-
-export const PendingWakeUpExceptionCode = appendCommonExceptionCode({
- OWNER_HANDLER_NOT_REGISTERED: 'OWNER_HANDLER_NOT_REGISTERED',
-} as const);
-
-const getPendingWakeUpExceptionUserFriendlyMessage = (
- code: keyof typeof PendingWakeUpExceptionCode,
-) => {
- switch (code) {
- case PendingWakeUpExceptionCode.OWNER_HANDLER_NOT_REGISTERED:
- case PendingWakeUpExceptionCode.INTERNAL_SERVER_ERROR:
- return msg`Something went wrong. Please try again.`;
- default:
- assertUnreachable(code);
- }
-};
-
-export class PendingWakeUpException extends CustomException<
- keyof typeof PendingWakeUpExceptionCode
-> {
- constructor(
- message: string,
- code: keyof typeof PendingWakeUpExceptionCode,
- { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
- ) {
- super(message, code, {
- userFriendlyMessage:
- userFriendlyMessage ??
- getPendingWakeUpExceptionUserFriendlyMessage(code),
- });
- }
-}
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts
index 38b8284d0ad..6d280586e9f 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts
@@ -6,7 +6,6 @@ import { PendingWakeUpSweepCronJob } from 'src/engine/core-modules/pending-wake-
import { PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { ResumePendingWakeUpJob } from 'src/engine/core-modules/pending-wake-up/jobs/resume-pending-wake-up.job';
import { PendingWakeUpDatabaseEventListener } from 'src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener';
-import { PendingWakeUpEventRecordService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
import { PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';
import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
@@ -25,7 +24,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
providers: [
PendingWakeUpService,
PendingWakeUpOwnerHandlerRegistryService,
- PendingWakeUpEventRecordService,
PendingWakeUpResolverService,
ResumePendingWakeUpJob,
PendingWakeUpDatabaseEventListener,
@@ -36,7 +34,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
exports: [
PendingWakeUpService,
PendingWakeUpOwnerHandlerRegistryService,
- PendingWakeUpEventRecordService,
PendingWakeUpSweepCronCommand,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-event-record.service.spec.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-event-record.service.spec.ts
deleted file mode 100644
index 9fec20e2ada..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-event-record.service.spec.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { PendingWakeUpEventRecordService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service';
-import { type FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
-
-const EVENT = {
- eventName: 'company.updated',
- recordId: 'company-id',
- record: { id: 'company-id', secret: 'hidden' },
- updatedFields: ['name', 'secret'],
-};
-
-const decide = ({
- recordRead,
- recordReadAttempt = 0,
- onRecordReadGivenUp = jest.fn(),
-}: {
- recordRead: {
- success: boolean;
- result?: { records: object[] };
- error?: string;
- };
- recordReadAttempt?: number;
- onRecordReadGivenUp?: jest.Mock;
-}) =>
- new PendingWakeUpEventRecordService({
- execute: jest.fn().mockResolvedValue(recordRead),
- } as unknown as FindRecordsService).decideOnEventRecord({
- event: EVENT,
- authContext: {} as WorkspaceAuthContext,
- rolePermissionConfig: { intersectionOf: ['role-id'] },
- recordReadAttempt,
- context: 'context',
- onRecordReadGivenUp,
- });
-
-describe('PendingWakeUpEventRecordService.decideOnEventRecord', () => {
- it('wakes the owner up with only what it can read of the record', async () => {
- expect(
- await decide({
- recordRead: {
- success: true,
- result: { records: [{ id: 'company-id', name: 'Acme' }] },
- },
- }),
- ).toEqual({
- type: 'RESOLVE',
- event: {
- ...EVENT,
- record: { id: 'company-id', name: 'Acme' },
- updatedFields: ['name'],
- },
- context: 'context',
- });
- });
-
- it('keeps waiting on a record the owner cannot read', async () => {
- expect(
- await decide({ recordRead: { success: true, result: { records: [] } } }),
- ).toEqual({
- type: 'IGNORE',
- });
- });
-
- it('tries a failed read again later', async () => {
- expect(
- await decide({ recordRead: { success: false }, recordReadAttempt: 2 }),
- ).toMatchObject({ type: 'RETRY_LATER', recordReadAttempt: 3 });
- });
-
- it('keeps waiting once the read kept failing, and says so', async () => {
- const onRecordReadGivenUp = jest.fn();
-
- expect(
- await decide({
- recordRead: { success: false, error: 'boom' },
- recordReadAttempt: 8,
- onRecordReadGivenUp,
- }),
- ).toEqual({ type: 'IGNORE' });
- expect(onRecordReadGivenUp).toHaveBeenCalledWith('boom');
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service.ts
deleted file mode 100644
index d43305fa47c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import { isPlainObject } from 'twenty-shared/utils';
-
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { type PendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-event.type';
-import { type PendingWakeUpBeforeClaimDecision } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
-import { computePendingWakeUpRetryDelayMs } from 'src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util';
-import { restrictPendingWakeUpEventToReadableRecord } from 'src/engine/core-modules/pending-wake-up/utils/restrict-pending-wake-up-event-to-readable-record.util';
-import { FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
-
-const RECORD_READ_MAX_ATTEMPTS = 8;
-
-@Injectable()
-export class PendingWakeUpEventRecordService {
- constructor(private readonly findRecordsService: FindRecordsService) {}
-
- // The event's record is read with its owner's permissions: a record the owner cannot read must not
- // wake it up, so the wait goes on for another event. A failed read cannot tell a transient error from
- // an object the owner cannot read, so it is retried a few times
- async decideOnEventRecord<TResolveContext>({
- event,
- authContext,
- rolePermissionConfig,
- recordReadAttempt,
- context,
- onRecordReadGivenUp,
- }: {
- event: PendingWakeUpEvent;
- authContext: WorkspaceAuthContext;
- rolePermissionConfig: RolePermissionConfig;
- recordReadAttempt: number;
- context: TResolveContext;
- onRecordReadGivenUp: (error?: string) => void;
- }): Promise<PendingWakeUpBeforeClaimDecision<TResolveContext>> {
- const [objectName, action] = event.eventName.split('.');
-
- const { success, result, error } = await this.findRecordsService.execute({
- objectName,
- // a deleted record only reads when the filter asks for deleted records
- filter:
- action === 'deleted'
- ? { id: { eq: event.recordId }, deletedAt: { is: 'NOT_NULL' } }
- : { id: { eq: event.recordId } },
- limit: 1,
- authContext,
- rolePermissionConfig,
- shouldBuildEffectiveSelectFields: false,
- });
-
- if (!success) {
- if (recordReadAttempt < RECORD_READ_MAX_ATTEMPTS) {
- return {
- type: 'RETRY_LATER',
- recordReadAttempt: recordReadAttempt + 1,
- delayMs: computePendingWakeUpRetryDelayMs(recordReadAttempt),
- };
- }
-
- onRecordReadGivenUp(error);
-
- return { type: 'IGNORE' };
- }
-
- const record = result?.records[0];
-
- if (!isPlainObject(record)) {
- return { type: 'IGNORE' };
- }
-
- return {
- type: 'RESOLVE',
- event: restrictPendingWakeUpEventToReadableRecord({
- event,
- readableRecord: record,
- }),
- context,
- };
- }
-}
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service.ts
index 3caff73b923..fa9c4ed9745 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service.ts
@@ -1,38 +1,11 @@
import { Injectable } from '@nestjs/common';
-import { isDefined } from 'twenty-shared/utils';
-
-import {
- PendingWakeUpException,
- PendingWakeUpExceptionCode,
-} from 'src/engine/core-modules/pending-wake-up/pending-wake-up.exception';
import { type PendingWakeUpOwnerHandler } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
import { type PendingWakeUpOwnerType } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-type.type';
+import { HandlerRegistry } from 'src/engine/utils/handler-registry';
-// owners register here so the engine resolves their wake-ups without importing them
@Injectable()
-export class PendingWakeUpOwnerHandlerRegistryService {
- private readonly handlers = new Map<
- PendingWakeUpOwnerType,
- PendingWakeUpOwnerHandler
- >();
-
- register(handler: PendingWakeUpOwnerHandler): void {
- this.handlers.set(handler.ownerType, handler);
- }
-
- getHandlerOrThrow(
- ownerType: PendingWakeUpOwnerType,
- ): PendingWakeUpOwnerHandler {
- const handler = this.handlers.get(ownerType);
-
- if (!isDefined(handler)) {
- throw new PendingWakeUpException(
- `No handler is registered for ${ownerType} wake-ups`,
- PendingWakeUpExceptionCode.OWNER_HANDLER_NOT_REGISTERED,
- );
- }
-
- return handler;
- }
-}
+export class PendingWakeUpOwnerHandlerRegistryService extends HandlerRegistry<
+ PendingWakeUpOwnerType,
+ PendingWakeUpOwnerHandler
+> {}
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
index 3f81555f9e1..d6570602f6a 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
@@ -1,17 +1,33 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
+import { type PendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-event.type';
+import { type PendingWakeUpOwnerHandler } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
import { type ResumePendingWakeUpJobData } from 'src/engine/core-modules/pending-wake-up/types/resume-pending-wake-up-job-data.type';
import { buildPendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/utils/build-pending-wake-up-outcome.util';
+import { restrictPendingWakeUpEventToReadableRecord } from 'src/engine/core-modules/pending-wake-up/utils/restrict-pending-wake-up-event-to-readable-record.util';
+import { FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
+
+const RECORD_READ_MAX_ATTEMPTS = 8;
+
+const RETRY_BASE_DELAY_MS = 2_000;
+const RETRY_MAX_DELAY_MS = 60_000;
+
+const computeRetryDelayMs = (attempt: number): number =>
+ Math.min(RETRY_BASE_DELAY_MS * 2 ** attempt, RETRY_MAX_DELAY_MS);
@Injectable()
export class PendingWakeUpResolverService {
+ private readonly logger = new Logger(PendingWakeUpResolverService.name);
+
constructor(
private readonly pendingWakeUpService: PendingWakeUpService,
private readonly pendingWakeUpOwnerHandlerRegistryService: PendingWakeUpOwnerHandlerRegistryService,
+ private readonly findRecordsService: FindRecordsService,
) {}
async resolve({
@@ -34,30 +50,39 @@ export class PendingWakeUpResolverService {
this.pendingWakeUpOwnerHandlerRegistryService.getHandlerOrThrow(
wakeUp.ownerType,
);
+ const ownerState = await handler.getOwnerState(wakeUp);
- const decision = await handler.beforeClaim({
- wakeUp,
- event,
- attempt,
- recordReadAttempt,
- });
-
- if (decision.type === 'IGNORE') {
- return;
- }
-
- if (decision.type === 'RETRY_LATER') {
+ if (ownerState.status === 'NOT_READY') {
await this.pendingWakeUpService.scheduleResolution({
wakeUp,
event,
- attempt: decision.attempt,
- recordReadAttempt: decision.recordReadAttempt,
- delayMs: decision.delayMs,
+ attempt: attempt + 1,
+ delayMs: computeRetryDelayMs(attempt),
});
return;
}
+ const shouldReadEventRecord =
+ ownerState.status === 'WAITING' && isDefined(event);
+
+ const readableEvent = shouldReadEventRecord
+ ? await this.readEventRecord({
+ wakeUp,
+ event,
+ recordReadAttempt,
+ readPermissions: await handler.getReadPermissions({
+ wakeUp,
+ owner: ownerState.owner,
+ }),
+ })
+ : event;
+
+ // an event whose record the owner cannot read yet keeps it waiting
+ if (shouldReadEventRecord && !isDefined(readableEvent)) {
+ return;
+ }
+
const claimedWakeUp = await this.pendingWakeUpService.claim({
workspaceId,
wakeUpId,
@@ -71,9 +96,67 @@ export class PendingWakeUpResolverService {
claimedWakeUp,
outcome: buildPendingWakeUpOutcome({
condition: claimedWakeUp.condition,
- event: decision.event ?? event,
+ event: readableEvent,
}),
- context: decision.context,
+ owner: ownerState.owner,
+ isOwnerGone: ownerState.status === 'GONE',
+ });
+ }
+
+ // The event's record is read with its owner's permissions: a record the owner cannot read must not
+ // wake it up, so the wait goes on for another event. A failed read cannot tell a transient
+ // error from an object the owner cannot read, so it is retried a few times
+ private async readEventRecord({
+ wakeUp,
+ event,
+ recordReadAttempt,
+ readPermissions,
+ }: {
+ wakeUp: PendingWakeUpEntity;
+ event: PendingWakeUpEvent;
+ recordReadAttempt: number;
+ readPermissions: Awaited<
+ ReturnType<PendingWakeUpOwnerHandler['getReadPermissions']>
+ >;
+ }): Promise<PendingWakeUpEvent | undefined> {
+ const [objectName, action] = event.eventName.split('.');
+
+ const { success, result, error } = await this.findRecordsService.execute({
+ objectName,
+ // a deleted record only reads when the filter asks for deleted records
+ filter:
+ action === 'deleted'
+ ? { id: { eq: event.recordId }, deletedAt: { is: 'NOT_NULL' } }
+ : { id: { eq: event.recordId } },
+ limit: 1,
+ ...readPermissions,
+ shouldBuildEffectiveSelectFields: false,
});
+
+ if (!success) {
+ if (recordReadAttempt < RECORD_READ_MAX_ATTEMPTS) {
+ await this.pendingWakeUpService.scheduleResolution({
+ wakeUp,
+ event,
+ recordReadAttempt: recordReadAttempt + 1,
+ delayMs: computeRetryDelayMs(recordReadAttempt),
+ });
+ } else {
+ this.logger.warn(
+ `Wait ${wakeUp.id} of ${wakeUp.ownerType} owner ${wakeUp.ownerId} kept waiting after its ${event.eventName} record could not be read: ${error}`,
+ );
+ }
+
+ return undefined;
+ }
+
+ const record = result?.records[0];
+
+ return isPlainObject(record)
+ ? restrictPendingWakeUpEventToReadableRecord({
+ event,
+ readableRecord: record,
+ })
+ : undefined;
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up.service.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up.service.ts
index a9a3c545ac0..ff5954aa20b 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up.service.ts
@@ -10,12 +10,18 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/servi
import { RESUME_PENDING_WAKE_UP_JOB_NAME } from 'src/engine/core-modules/pending-wake-up/constants/resume-pending-wake-up-job-name.constant';
import { PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
-import { type PendingWakeUpOwner } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner.type';
import { type PendingWakeUpOwnerType } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-type.type';
import { type ResumePendingWakeUpJobData } from 'src/engine/core-modules/pending-wake-up/types/resume-pending-wake-up-job-data.type';
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';
+// key tells apart the wake-ups one owner holds at once, like the steps of a workflow run
+type PendingWakeUpOwner = {
+ type: PendingWakeUpOwnerType;
+ id: string;
+ key: string;
+};
+
type ScheduledWakeUp = Pick<
PendingWakeUpEntity,
'id' | 'workspaceId' | 'ownerType' | 'ownerId'
@@ -86,12 +92,14 @@ export class PendingWakeUpService {
attempt,
recordReadAttempt,
delayMs = 0,
+ deduplicationId,
}: Pick<
ResumePendingWakeUpJobData,
'event' | 'attempt' | 'recordReadAttempt'
> & {
wakeUp: ScheduledWakeUp;
delayMs?: number;
+ deduplicationId?: string;
}): Promise<void> {
await this.messageQueueService.add<ResumePendingWakeUpJobData>(
RESUME_PENDING_WAKE_UP_JOB_NAME,
@@ -103,20 +111,13 @@ export class PendingWakeUpService {
recordReadAttempt,
},
{
- ...this.buildResumeJobOptions(wakeUp),
+ ...this.pendingWakeUpOwnerHandlerRegistryService
+ .getHandlerOrThrow(wakeUp.ownerType)
+ .buildResumeJobOptions(wakeUp.ownerId),
delay: Math.max(delayMs, 0),
- },
- );
- }
-
- // A wake-up stays overdue until its job claims it, so each sweep would queue it again
- async scheduleOverdueResolution(wakeUp: ScheduledWakeUp): Promise<void> {
- await this.messageQueueService.add<ResumePendingWakeUpJobData>(
- RESUME_PENDING_WAKE_UP_JOB_NAME,
- { workspaceId: wakeUp.workspaceId, wakeUpId: wakeUp.id },
- {
- ...this.buildResumeJobOptions(wakeUp),
- deduplication: { id: `overdue-pending-wake-up-${wakeUp.id}` },
+ ...(isDefined(deduplicationId)
+ ? { deduplication: { id: deduplicationId } }
+ : {}),
},
);
}
@@ -160,38 +161,18 @@ export class PendingWakeUpService {
});
}
+ // without a key, every wake-up the owner holds
async cancel({
workspaceId,
- owner,
- }: {
- workspaceId: string;
- owner: PendingWakeUpOwner;
- }): Promise<void> {
- await this.pendingWakeUpRepository.delete(workspaceId, {
- ownerType: owner.type,
- ownerId: owner.id,
- ownerKey: owner.key,
- });
- }
-
- async cancelAllForOwner({
- workspaceId,
- ownerType,
- ownerId,
+ owner: { type, id, key },
}: {
workspaceId: string;
- ownerType: PendingWakeUpOwnerType;
- ownerId: string;
+ owner: Omit<PendingWakeUpOwner, 'key'> & { key?: string };
}): Promise<void> {
await this.pendingWakeUpRepository.delete(workspaceId, {
- ownerType,
- ownerId,
+ ownerType: type,
+ ownerId: id,
+ ...(isDefined(key) ? { ownerKey: key } : {}),
});
}
-
- private buildResumeJobOptions({ ownerType, ownerId }: ScheduledWakeUp) {
- return this.pendingWakeUpOwnerHandlerRegistryService
- .getHandlerOrThrow(ownerType)
- .buildResumeJobOptions(ownerId);
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
index 0b44fa16907..08db3b5a368 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
@@ -1,36 +1,29 @@
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type QueueJobOptions } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
-import { type PendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-event.type';
import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-outcome.type';
-import { type PendingWakeUpOwnerType } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-type.type';
-
-export type PendingWakeUpBeforeClaimDecision<TResolveContext> =
- // the event, when given, replaces the one that woke the owner up
- | { type: 'RESOLVE'; event?: PendingWakeUpEvent; context: TResolveContext }
- | {
- type: 'RETRY_LATER';
- delayMs: number;
- attempt?: number;
- recordReadAttempt?: number;
- }
- // the wake-up stays pending for a later event or its own time
- | { type: 'IGNORE' };
-
-export type PendingWakeUpOwnerHandler<TResolveContext = unknown> = {
- ownerType: PendingWakeUpOwnerType;
+import { type PendingWakeUpOwnerState } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type';
+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
+export type PendingWakeUpOwnerHandler<TOwner = unknown> = {
buildResumeJobOptions(ownerId: string): QueueJobOptions;
- beforeClaim(input: {
+ getOwnerState(
+ wakeUp: PendingWakeUpEntity,
+ ): Promise<PendingWakeUpOwnerState<TOwner>>;
+
+ getReadPermissions(input: {
wakeUp: PendingWakeUpEntity;
- event?: PendingWakeUpEvent;
- attempt: number;
- recordReadAttempt: number;
- }): Promise<PendingWakeUpBeforeClaimDecision<TResolveContext>>;
+ owner: TOwner;
+ }): Promise<{
+ authContext: WorkspaceAuthContext;
+ rolePermissionConfig: RolePermissionConfig;
+ }>;
resolve(input: {
claimedWakeUp: PendingWakeUpEntity;
outcome: PendingWakeUpOutcome;
- context: TResolveContext;
+ owner: TOwner | null;
+ isOwnerGone: boolean;
}): Promise<void>;
};
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type.ts
new file mode 100644
index 00000000000..f4fe64304b7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type.ts
@@ -0,0 +1,7 @@
+// WAITING: the owner takes the outcome, an event only once its record reads with the owner's permissions;
+// NOT_READY: the owner arms its wake-up before it records that it waits, so the wake-up is held until it does;
+// GONE: the owner stopped waiting, or no longer exists, and resolving only drops the wake-up
+export type PendingWakeUpOwnerState<TOwner> =
+ | { status: 'NOT_READY' }
+ | { status: 'WAITING'; owner: TOwner }
+ | { status: 'GONE'; owner: TOwner | null };
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner.type.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner.type.ts
deleted file mode 100644
index a9b235aafec..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner.type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { type PendingWakeUpOwnerType } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-type.type';
-
-// key tells apart the wake-ups one owner holds at once, like the steps of a workflow run
-export type PendingWakeUpOwner = {
- type: PendingWakeUpOwnerType;
- id: string;
- key: string;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util.ts
deleted file mode 100644
index d3542d44e6f..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-const RETRY_BASE_DELAY_MS = 2_000;
-const RETRY_MAX_DELAY_MS = 60_000;
-
-export const computePendingWakeUpRetryDelayMs = (attempt: number): number =>
- Math.min(RETRY_BASE_DELAY_MS * 2 ** attempt, RETRY_MAX_DELAY_MS);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
index 9fa53822c89..85b661f6a2b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
@@ -16,7 +16,6 @@ import { AgentMessagePartResolver } from 'src/engine/metadata-modules/ai/ai-agen
import { AgentMessageResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-message.resolver';
import { AgentRunResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
-import { AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service';
import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
@@ -63,7 +62,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
],
providers: [
AgentAsyncExecutorService,
- AgentCallerInboxService,
AgentActorContextService,
AgentCallerConversationService,
AgentRunCallerHandlerRegistryService,
@@ -84,7 +82,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
],
exports: [
AgentAsyncExecutorService,
- AgentCallerInboxService,
AgentActorContextService,
AgentCallerConversationService,
AgentRunCallerHandlerRegistryService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-message-thread-lock-max-retries.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-message-thread-lock-max-retries.const.ts
deleted file mode 100644
index 393ac2ecebf..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-message-thread-lock-max-retries.const.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-// about two seconds: long enough to wait for another message being sent, not for a run
-export const AGENT_MESSAGE_THREAD_LOCK_MAX_RETRIES = 4;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-excluded-tool-names.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const.ts
similarity index 86%
rename from packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-excluded-tool-names.const.ts
rename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const.ts
index 38b8d7f9226..cd45327dc34 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-excluded-tool-names.const.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const.ts
@@ -1,6 +1,6 @@
import { type ActionToolId } from 'src/engine/core-modules/tool-provider/constants/action-tool-label.constant';
-export const WORKFLOW_AGENT_EXCLUDED_TOOL_NAMES = [
+export const AGENT_RUN_EXCLUDED_TOOL_NAMES = [
'search_help_center',
'create_file_upload',
'complete_file_upload',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-max-continuations.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-max-continuations.const.ts
deleted file mode 100644
index 766d68e821b..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-max-continuations.const.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-// bounds what one run can spend by pausing again and again, as each continuation runs the model anew
-export const AGENT_RUN_MAX_CONTINUATIONS = 50;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-registry-tool-categories.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const.ts
similarity index 58%
rename from packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-registry-tool-categories.const.ts
rename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const.ts
index 5493b17e129..6859391c99d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-registry-tool-categories.const.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const.ts
@@ -1,6 +1,6 @@
import { ToolCategory } from 'twenty-shared/ai';
-export const WORKFLOW_AGENT_REGISTRY_TOOL_CATEGORIES: ToolCategory[] = [
+export const PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES: ToolCategory[] = [
ToolCategory.DATABASE_CRUD,
ToolCategory.ACTION,
];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity.ts
index b4ef7189089..963d48261b1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity.ts
@@ -1,3 +1,4 @@
+import { type AgentRunSummary } from 'twenty-shared/ai';
import {
Column,
CreateDateColumn,
@@ -11,7 +12,6 @@ import { CREATE_AGENT_RUN_SUSPENSION_TABLE_UPGRADE_COMMAND_NAME } from 'src/data
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
// A run paused on an answer or a wait, kept until the engine continues it and hands its
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/agent-wait-pending-output.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/agent-wait-pending-output.type.ts
deleted file mode 100644
index bcb81ab85ca..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/agent-wait-pending-output.type.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
-
-export type AgentWaitPendingOutput = {
- success: true;
- message: string;
- result: { status: 'pending'; wait: PendingWakeUpCondition };
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-pending-output.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-pending-output.util.ts
index bb12a80c24d..ea5a0a59b16 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-pending-output.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-pending-output.util.ts
@@ -1,14 +1,16 @@
import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
-import { type AgentWaitPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/agent-wait-pending-output.type';
-
export const buildWaitPendingOutput = ({
message,
wait,
}: {
message: string;
wait: PendingWakeUpCondition;
-}): AgentWaitPendingOutput => ({
+}): {
+ success: true;
+ message: string;
+ result: { status: 'pending'; wait: PendingWakeUpCondition };
+} => ({
success: true,
message,
result: { status: 'pending', wait },
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/find-agent-run-wait.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/find-agent-run-wait.util.ts
index 2628bacc41c..f629f0e03ce 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/find-agent-run-wait.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/find-agent-run-wait.util.ts
@@ -1,14 +1,16 @@
-import { pendingWakeUpConditionSchema } from 'twenty-shared/pending-wake-up';
+import {
+ type PendingWakeUpCondition,
+ pendingWakeUpConditionSchema,
+} from 'twenty-shared/pending-wake-up';
import { isPlainObject } from 'twenty-shared/utils';
import { AGENT_WAIT_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-tool-names.constant';
-import { type AgentRunWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-wait.type';
import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-history/utils/is-awaiting-pausing-tool-output.util';
-// The wait a run paused on, when it paused on a wait tool call
+// The wait call a run paused on, when it paused on one, and what wakes it up
export const findAgentRunWait = (
toolResults: { toolCallId: string; toolName: string; output: unknown }[],
-): AgentRunWait | undefined => {
+): { toolCallId: string; condition: PendingWakeUpCondition } | undefined => {
for (const { toolCallId, toolName, output } of toolResults) {
if (
!AGENT_WAIT_TOOL_NAMES.includes(toolName) ||
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
index 4d81e4c725c..ab76cbfc389 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
@@ -34,6 +34,8 @@ const buildService = ({ isCreated = true } = {}) => {
const service = new AgentCallerConversationService(
agentInboxService as never,
agentRunSuspensionService as never,
+ {} as never,
+ {} as never,
);
return { service, agentInboxService, agentRunSuspensionService };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
index 9638ec52cac..a2ad11d47e2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
@@ -1,5 +1,6 @@
import { Logger } from '@nestjs/common';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
@@ -71,6 +72,7 @@ const RUN_INPUT: AgentRunnerRunInput = {
userWorkspaceId: 'user-workspace-id',
rolePermissionConfig: { intersectionOf: [] },
conversationActor: { type: 'application', applicationId: 'app-id' },
+ usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
},
resolveCreatedBy: async () => CREATED_BY,
};
@@ -102,6 +104,7 @@ const buildService = (execution = buildExecution()) => {
{} as never,
{} as never,
{} as never,
+ {} as never,
);
return {
@@ -157,6 +160,7 @@ describe('AgentRunnerService', () => {
/^base prompt\n\n.*wait_for_event/,
),
priorMessages: PRIOR_MESSAGES,
+ usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
}),
);
expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service.ts
index 42d2b1084a0..1a0b6076f82 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service.ts
@@ -8,6 +8,7 @@ import { Repository } from 'typeorm';
import { buildCreatedByFromFullNameMetadata } from 'src/engine/core-modules/actor/utils/build-created-by-from-full-name-metadata.util';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';
+import { type ApplicationWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { buildApplicationAuthContext } from 'src/engine/core-modules/auth/utils/build-application-auth-context.util';
import { buildUserAuthContext } from 'src/engine/core-modules/auth/utils/build-user-auth-context.util';
import { fromUserEntityToFlat } from 'src/engine/core-modules/user/utils/from-user-entity-to-flat.util';
@@ -20,7 +21,6 @@ import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
-import { type ApplicationAgentContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/application-agent-context.type';
import { type RunAsWorkspaceMemberContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/run-as-workspace-member-context.type';
import {
PermissionsException,
@@ -66,7 +66,11 @@ export class AgentActorContextService {
}: {
workspaceId: string;
agent: Pick<AgentEntity, 'id' | 'applicationId'>;
- }): Promise<ApplicationAgentContext | null> {
+ }): Promise<{
+ application: FlatApplication;
+ authContext: ApplicationWorkspaceAuthContext;
+ agentRoleId: string | undefined;
+ } | null> {
const [workspace, application, agentRoleId] = await Promise.all([
this.workspaceRepository.findOneOrFail({ where: { id: workspaceId } }),
this.applicationLookupService.findById({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index 4c6838edbb0..b4ca22a334b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -46,11 +46,11 @@ import { getToolMetricName } from 'src/engine/core-modules/tool-provider/utils/g
import { isToolOutputSuccessful } from 'src/engine/core-modules/tool-provider/utils/is-tool-output-successful.util';
import { OUTPUT_NAVIGATION_TOOL_NAMES } from 'src/engine/core-modules/tool/tools/output-navigation-tool/constants/output-navigation-tool-names.constant';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { OPEN_ENDED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/open-ended-agent-registry-tool-categories.const';
-import { WORKFLOW_AGENT_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-excluded-tool-names.const';
-import { WORKFLOW_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-registry-tool-categories.const';
+import { AGENT_RUN_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const';
+import { PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const';
import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util';
import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
@@ -177,10 +177,10 @@ export class AgentAsyncExecutorService {
const tools = await this.toolRegistry.getToolsByCategories(
{ ...preloadedToolContext, requireExplicitObjectGrants: true },
{
- categories: WORKFLOW_AGENT_REGISTRY_TOOL_CATEGORIES,
+ categories: PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES,
excludeTools: [
...OUTPUT_NAVIGATION_TOOL_NAMES,
- ...WORKFLOW_AGENT_EXCLUDED_TOOL_NAMES,
+ ...AGENT_RUN_EXCLUDED_TOOL_NAMES,
...additionalExcludedToolNames,
],
},
@@ -250,7 +250,7 @@ export class AgentAsyncExecutorService {
);
const excludedToolNames = new Set<string>([
...OUTPUT_NAVIGATION_TOOL_NAMES,
- ...WORKFLOW_AGENT_EXCLUDED_TOOL_NAMES,
+ ...AGENT_RUN_EXCLUDED_TOOL_NAMES,
...additionalExcludedToolNames,
]);
@@ -330,6 +330,7 @@ export class AgentAsyncExecutorService {
priorMessages = [],
pausingTools = {},
canProposeToolCalls = false,
+ usageOperationType,
}: {
agent: AgentEntity | null;
messages: RunAgentMessage[];
@@ -347,6 +348,7 @@ export class AgentAsyncExecutorService {
additionalRoleRestrictionIds?: string[];
additionalExcludedToolNames?: readonly string[];
toolLoadingStrategy?: AgentToolLoadingStrategy;
+ usageOperationType: UsageOperationType;
}): Promise<AgentExecutionResult> {
if (!isNonEmptyArray(messages) && !isNonEmptyArray(priorMessages)) {
throw new AiException(
@@ -359,7 +361,7 @@ export class AgentAsyncExecutorService {
await this.aiBillingService.assertAiExecutionAllowed({
workspaceId,
- operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ operationType: usageOperationType,
spenders: { userWorkspaceId, agentId: agent?.id },
});
@@ -471,7 +473,7 @@ export class AgentAsyncExecutorService {
),
},
workspaceId,
- operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ operationType: usageOperationType,
spenders: { userWorkspaceId, agentId: agent?.id },
});
@@ -588,7 +590,7 @@ export class AgentAsyncExecutorService {
workspaceId,
userWorkspaceId: userWorkspaceId ?? null,
agentId: agent?.id ?? null,
- operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ operationType: usageOperationType,
},
});
},
@@ -713,7 +715,7 @@ export class AgentAsyncExecutorService {
creditsUsedMicro,
totalTokens,
modelId,
- UsageOperationType.AI_WORKFLOW_TOKEN,
+ usageOperationType,
agent?.id ?? null,
userWorkspaceId,
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
index 5e5a56e7f6b..ab946245ca6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
@@ -1,23 +1,47 @@
import { Injectable } from '@nestjs/common';
+import { PROPOSE_TOOL_CALL_TOOL_NAME } from 'twenty-shared/ai';
+import { type SendInboxMessageInput } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
+import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
+import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
+import { buildProposeToolCallPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';
+import { type ProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type';
+import { findMissingRequiredToolArguments } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util';
+import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';
+import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
+import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
-import { type AgentRunnerOpenedConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type';
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+import { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-status.util';
import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
-// Opens the conversation of a run a caller drives, such as a workflow step. Kept apart from the
-// runner so callers avoid the agent execution and tool dependencies
+const MAX_ASK_ATTEMPTS = 10;
+
+type AgentCallerAwaitedToolCall = {
+ toolName: string;
+ arguments: Record<string, unknown>;
+ caller: AgentRunCaller;
+};
+
+// The conversations a caller, such as a workflow step, holds with a member's inbox: the one its agent
+// run writes to, and the messages it sends itself, which may ask the member to approve a call. The
+// caller waits on that answer as on a suspended run, so it gets it through its handler
@Injectable()
export class AgentCallerConversationService {
constructor(
private readonly agentInboxService: AgentInboxService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
+ private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
+ private readonly toolRegistryService: ToolRegistryService,
) {}
// A conversation the run opens is filed under done, and only comes back to
@@ -40,8 +64,12 @@ export class AgentCallerConversationService {
recipientWorkspaceMemberId: string | null;
// used without a recipient; a member who cannot have the conversation leaves it to no inbox
fallbackRecipientWorkspaceMemberId?: string | null;
- }): Promise<AgentRunnerOpenedConversation> {
- const openThreadUnderKey = (key: string) => {
+ }): Promise<
+ | ({ status: 'OPENED' } & AgentRunConversation)
+ // the recipient deleted both the conversation its key names and the fallback one
+ | { status: 'DELETED' }
+ > {
+ const openThreadUnderKey = async (key: string) => {
const openThread = (workspaceMemberId: string | null) =>
this.agentInboxService.openThread({
workspaceId,
@@ -52,12 +80,27 @@ export class AgentCallerConversationService {
isArchivedOnCreate: true,
});
- return isDefined(recipientWorkspaceMemberId)
- ? openThread(recipientWorkspaceMemberId)
- : this.openThreadWithFallbackRecipient({
- fallbackRecipientWorkspaceMemberId,
- openThread,
- });
+ if (
+ isDefined(recipientWorkspaceMemberId) ||
+ !isDefined(fallbackRecipientWorkspaceMemberId)
+ ) {
+ return openThread(recipientWorkspaceMemberId);
+ }
+
+ // a fallback recipient who cannot have the conversation, such as one who cannot use AI,
+ // leaves a conversation no inbox receives
+ try {
+ return await openThread(fallbackRecipientWorkspaceMemberId);
+ } catch (error) {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return openThread(null);
+ }
+
+ throw error;
+ }
};
const keyedConversation = await openThreadUnderKey(threadKey);
@@ -84,32 +127,171 @@ export class AgentCallerConversationService {
return { status: 'OPENED', threadId: thread.id, isCreated };
}
- // a member who cannot have the conversation, such as one who cannot use AI,
- // leaves a conversation no inbox receives
- private async openThreadWithFallbackRecipient({
- fallbackRecipientWorkspaceMemberId,
- openThread,
+ async sendMessage({
+ workspaceId,
+ sender,
+ message,
+ awaitedToolCall,
}: {
- fallbackRecipientWorkspaceMemberId: string | null;
- openThread: (
- workspaceMemberId: string | null,
- ) => ReturnType<AgentInboxService['openThread']>;
- }): ReturnType<AgentInboxService['openThread']> {
- if (!isDefined(fallbackRecipientWorkspaceMemberId)) {
- return openThread(null);
+ workspaceId: string;
+ sender: AgentInboxSender;
+ message: Omit<SendInboxMessageInput, 'toolCall'>;
+ awaitedToolCall?: AgentCallerAwaitedToolCall;
+ }): Promise<
+ | { status: 'DELIVERED'; threadId: string }
+ // the member deleted the conversation, so the call can no longer be answered
+ | { status: 'DISMISSED'; threadId: string }
+ // the caller waits, and gets the answer through its handler's onOutcome
+ | { status: 'AWAITING'; threadId: string }
+ // a message sent before already holds the answer
+ | { status: 'ANSWERED'; threadId: string; answer: ProposedToolCallAnswer }
+ > {
+ if (!isDefined(awaitedToolCall)) {
+ const { threadId } = await this.agentInboxService.sendMessage({
+ workspaceId,
+ sender,
+ input: message,
+ });
+
+ return { status: 'DELIVERED', threadId };
}
- try {
- return await openThread(fallbackRecipientWorkspaceMemberId);
- } catch (error) {
- if (
- error instanceof AiException &&
- error.code === AiExceptionCode.THREAD_NOT_FOUND
- ) {
- return openThread(null);
+ // resolved once, and only when a message is written
+ let pendingToolCall:
+ | ReturnType<AgentCallerConversationService['buildPendingToolCall']>
+ | undefined;
+ const buildAwaitingToolCall = () =>
+ (pendingToolCall ??= this.buildPendingToolCall({
+ workspaceId,
+ awaitedToolCall,
+ summary: message.text,
+ }));
+
+ // a message sent again finds the call it posted before: a pending one is still awaited, an answered
+ // one is reused so nothing runs twice, and one closed unanswered, such as by a run that ended and
+ // was retried, is asked again in a new message
+ for (let attempt = 0; attempt < MAX_ASK_ATTEMPTS; attempt++) {
+ const { threadId, isDismissed, awaitedToolOutput } =
+ await this.agentInboxService.sendMessage({
+ workspaceId,
+ sender,
+ input: {
+ ...message,
+ idempotencyKey:
+ attempt === 0
+ ? message.idempotencyKey
+ : `${message.idempotencyKey}:${attempt}`,
+ },
+ buildAwaitingToolCall,
+ });
+
+ if (isDismissed) {
+ return { status: 'DISMISSED', threadId };
+ }
+
+ const status = readToolCallStatus(awaitedToolOutput);
+
+ if (status === 'skipped') {
+ continue;
}
- throw error;
+ if (status === 'pending' || status === 'running') {
+ await this.agentRunSuspensionService.awaitCallerCall({
+ workspaceId,
+ threadId,
+ caller: awaitedToolCall.caller,
+ });
+
+ return { status: 'AWAITING', threadId };
+ }
+
+ const answer = readProposedToolCallAnswer(awaitedToolOutput);
+
+ if (!isDefined(answer)) {
+ throw new AiException(
+ 'The answer to the proposed call could not be read',
+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,
+ );
+ }
+
+ return { status: 'ANSWERED', threadId, answer };
+ }
+
+ throw new AiException(
+ `The action was asked ${MAX_ASK_ATTEMPTS} times without an answer`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ // resolved with the caller's permissions, the ones it acts with itself
+ private async buildPendingToolCall({
+ workspaceId,
+ awaitedToolCall: { toolName, arguments: toolArguments, caller },
+ summary,
+ }: {
+ workspaceId: string;
+ awaitedToolCall: AgentCallerAwaitedToolCall;
+ summary: string;
+ }) {
+ const { authContext, rolePermissionConfig, application } =
+ await this.callerHandlerRegistry
+ .getHandlerOrThrow(caller.type)
+ .buildExecutionContext({ workspaceId, caller });
+
+ const toolContext = {
+ workspaceId,
+ roleId: getRoleIdsFromRolePermissionConfig(rolePermissionConfig)[0] ?? '',
+ rolePermissionConfig,
+ authContext,
+ application,
+ } satisfies ToolContext;
+
+ const catalog = await this.toolRegistryService.getCatalog(toolContext);
+ const inputSchemas = await this.toolRegistryService.resolveSchemas({
+ toolNames: [toolName],
+ context: toolContext,
+ precomputedCatalog: catalog,
+ });
+ const missingArgumentNames = findMissingRequiredToolArguments({
+ inputSchema: inputSchemas.get(toolName),
+ toolArguments,
+ });
+
+ if (missingArgumentNames.length > 0) {
+ throw new AiException(
+ `The action is missing required arguments: ${missingArgumentNames.join(', ')}`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ const input = { toolName, arguments: toolArguments, summary };
+
+ const resolution = await resolveProposedToolCall({
+ input,
+ findTool: async (catalogToolName) =>
+ catalog.find((catalogEntry) => catalogEntry.name === catalogToolName),
+ executeTool: ({ toolName: executedToolName, args }) =>
+ this.toolRegistryService.resolveAndExecute(
+ executedToolName,
+ args,
+ toolContext,
+ ),
+ });
+
+ if ('error' in resolution) {
+ throw new AiException(
+ `The tool call cannot be proposed: ${resolution.error}`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
}
+
+ return {
+ toolName: PROPOSE_TOOL_CALL_TOOL_NAME,
+ input,
+ output: {
+ ...buildProposeToolCallPendingOutput(resolution.proposal),
+ awaitedByCaller: true,
+ },
+ };
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service.ts
deleted file mode 100644
index 9b15550e0c4..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import { PROPOSE_TOOL_CALL_TOOL_NAME } from 'twenty-shared/ai';
-import { type SendInboxMessageInput } from 'twenty-shared/application';
-import { isDefined } from 'twenty-shared/utils';
-
-import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
-import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
-import { buildProposeToolCallPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';
-import { findMissingRequiredToolArguments } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util';
-import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';
-import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
-import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
-import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
-import { type AgentCallerInboxDelivery } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-caller-inbox-delivery.type';
-import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
-import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
-import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
-import { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-status.util';
-import {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
-import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
-
-const MAX_ASK_ATTEMPTS = 10;
-
-type AgentCallerAwaitedToolCall = {
- toolName: string;
- arguments: Record<string, unknown>;
- caller: AgentRunCaller;
-};
-
-// A caller, such as a workflow step, messages a member's inbox and may ask them to approve a call.
-// The caller then waits on the answer as on a suspended run, so it gets it through its handler
-@Injectable()
-export class AgentCallerInboxService {
- constructor(
- private readonly agentInboxService: AgentInboxService,
- private readonly agentRunSuspensionService: AgentRunSuspensionService,
- private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
- private readonly toolRegistryService: ToolRegistryService,
- ) {}
-
- async sendMessage({
- workspaceId,
- sender,
- message,
- awaitedToolCall,
- }: {
- workspaceId: string;
- sender: AgentInboxSender;
- message: Omit<SendInboxMessageInput, 'toolCall'>;
- awaitedToolCall?: AgentCallerAwaitedToolCall;
- }): Promise<AgentCallerInboxDelivery> {
- if (!isDefined(awaitedToolCall)) {
- const { threadId } = await this.agentInboxService.sendMessage({
- workspaceId,
- sender,
- input: message,
- });
-
- return { status: 'DELIVERED', threadId };
- }
-
- let pendingToolCall:
- | ReturnType<AgentCallerInboxService['buildPendingToolCall']>
- | undefined;
- const buildAwaitingToolCall = () => {
- pendingToolCall ??= this.buildPendingToolCall({
- workspaceId,
- awaitedToolCall,
- summary: message.text,
- });
-
- return pendingToolCall;
- };
-
- // a message sent again finds the call it posted before: a pending one is still awaited, an answered
- // one is reused so nothing runs twice, and one closed unanswered, such as by a run that ended and
- // was retried, is asked again in a new message
- for (let attempt = 0; attempt < MAX_ASK_ATTEMPTS; attempt++) {
- const { threadId, isDismissed, awaitedToolOutput } =
- await this.agentInboxService.sendMessage({
- workspaceId,
- sender,
- input: {
- ...message,
- idempotencyKey:
- attempt === 0
- ? message.idempotencyKey
- : `${message.idempotencyKey}:${attempt}`,
- },
- buildAwaitingToolCall,
- });
-
- if (isDismissed) {
- return { status: 'DISMISSED', threadId };
- }
-
- const status = readToolCallStatus(awaitedToolOutput);
-
- if (status === 'skipped') {
- continue;
- }
-
- if (status === 'pending' || status === 'running') {
- await this.agentRunSuspensionService.awaitCallerCall({
- workspaceId,
- threadId,
- caller: awaitedToolCall.caller,
- });
-
- return { status: 'AWAITING', threadId };
- }
-
- const answer = readProposedToolCallAnswer(awaitedToolOutput);
-
- if (!isDefined(answer)) {
- throw new AiException(
- 'The answer to the proposed call could not be read',
- AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,
- );
- }
-
- return { status: 'ANSWERED', threadId, answer };
- }
-
- throw new AiException(
- `The action was asked ${MAX_ASK_ATTEMPTS} times without an answer`,
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
-
- // resolved with the caller's permissions, the ones it acts with itself
- private async buildPendingToolCall({
- workspaceId,
- awaitedToolCall: { toolName, arguments: toolArguments, caller },
- summary,
- }: {
- workspaceId: string;
- awaitedToolCall: AgentCallerAwaitedToolCall;
- summary: string;
- }) {
- const { authContext, rolePermissionConfig, application } =
- await this.callerHandlerRegistry
- .getHandlerOrThrow(caller.type)
- .buildExecutionContext({ workspaceId, caller });
-
- const toolContext = {
- workspaceId,
- roleId: getRoleIdsFromRolePermissionConfig(rolePermissionConfig)[0] ?? '',
- rolePermissionConfig,
- authContext,
- application,
- } satisfies ToolContext;
-
- const catalog = await this.toolRegistryService.getCatalog(toolContext);
- const inputSchemas = await this.toolRegistryService.resolveSchemas({
- toolNames: [toolName],
- context: toolContext,
- precomputedCatalog: catalog,
- });
- const missingArgumentNames = findMissingRequiredToolArguments({
- inputSchema: inputSchemas.get(toolName),
- toolArguments,
- });
-
- if (missingArgumentNames.length > 0) {
- throw new AiException(
- `The action is missing required arguments: ${missingArgumentNames.join(', ')}`,
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
-
- const input = { toolName, arguments: toolArguments, summary };
-
- const resolution = await resolveProposedToolCall({
- input,
- findTool: async (catalogToolName) =>
- catalog.find((catalogEntry) => catalogEntry.name === catalogToolName),
- executeTool: ({ toolName: executedToolName, args }) =>
- this.toolRegistryService.resolveAndExecute(
- executedToolName,
- args,
- toolContext,
- ),
- });
-
- if ('error' in resolution) {
- throw new AiException(
- `The tool call cannot be proposed: ${resolution.error}`,
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
-
- return {
- toolName: PROPOSE_TOOL_CALL_TOOL_NAME,
- input,
- output: {
- ...buildProposeToolCallPendingOutput(resolution.proposal),
- awaitedByCaller: true,
- },
- };
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service.ts
index 9bc95c526fe..dc668b87a3f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service.ts
@@ -1,36 +1,11 @@
import { Injectable } from '@nestjs/common';
-import { isDefined } from 'twenty-shared/utils';
-
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type';
-import {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
+import { HandlerRegistry } from 'src/engine/utils/handler-registry';
-// callers register here so the engine hands them their runs' outcomes without importing them
@Injectable()
-export class AgentRunCallerHandlerRegistryService {
- private readonly handlers = new Map<
- AgentRunCaller['type'],
- AgentRunCallerHandler
- >();
-
- register(handler: AgentRunCallerHandler): void {
- this.handlers.set(handler.callerType, handler);
- }
-
- getHandlerOrThrow(callerType: AgentRunCaller['type']): AgentRunCallerHandler {
- const handler = this.handlers.get(callerType);
-
- if (!isDefined(handler)) {
- throw new AiException(
- `No handler is registered for ${callerType} agent runs`,
- AiExceptionCode.AGENT_EXECUTION_FAILED,
- );
- }
-
- return handler;
- }
-}
+export class AgentRunCallerHandlerRegistryService extends HandlerRegistry<
+ AgentRunCaller['type'],
+ AgentRunCallerHandler
+> {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
index 2f576b85389..36186b6b601 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
@@ -16,7 +16,6 @@ import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/util
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
-import { AGENT_MESSAGE_THREAD_LOCK_MAX_RETRIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-message-thread-lock-max-retries.const';
import {
AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,
AGENT_RUN_THREAD_LOCK_TTL_MS,
@@ -32,6 +31,9 @@ import {
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+// long enough to wait for another message being sent, not for a run
+const MESSAGE_THREAD_LOCK_MAX_WAIT_MS = 2_000;
+
@Injectable()
export class AgentRunConversationService {
private readonly logger = new Logger(AgentRunConversationService.name);
@@ -49,13 +51,12 @@ export class AgentRunConversationService {
workspaceId,
threadId,
work,
- maxRetries = AGENT_RUN_THREAD_LOCK_TTL_MS /
- AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,
+ maxWaitMs = AGENT_RUN_THREAD_LOCK_TTL_MS,
}: {
workspaceId: string;
threadId: string;
work: () => Promise<TResult>;
- maxRetries?: number;
+ maxWaitMs?: number;
}): Promise<TResult> {
return this.cacheLockService.withLock(
work,
@@ -63,7 +64,7 @@ export class AgentRunConversationService {
{
ttl: AGENT_RUN_THREAD_LOCK_TTL_MS,
ms: AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,
- maxRetries,
+ maxRetries: maxWaitMs / AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,
},
);
}
@@ -85,7 +86,7 @@ export class AgentRunConversationService {
return await this.withThreadLock({
workspaceId,
threadId,
- maxRetries: AGENT_MESSAGE_THREAD_LOCK_MAX_RETRIES,
+ maxWaitMs: MESSAGE_THREAD_LOCK_MAX_WAIT_MS,
work: () => {
isLocked = true;
@@ -212,12 +213,20 @@ export class AgentRunConversationService {
isAwaitingAnswer,
});
+ // the waiting call is already saved and can be answered from the conversation, so a
+ // failure to bring it back to the inbox must not fail the run
if (isAwaitingAnswer) {
- await this.recordWaitingActivity({
- workspaceId,
- threadId,
- text: findLastMessageText(replyParts) ?? title,
- });
+ await this.threadService
+ .recordThreadActivity({
+ workspaceId,
+ threadId,
+ text: findLastMessageText(replyParts) ?? title,
+ })
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not record waiting activity on thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
+ ),
+ );
}
return { isAwaitingAnswer };
@@ -240,22 +249,6 @@ export class AgentRunConversationService {
});
}
- // the waiting call is already saved and can be answered from the conversation, so a
- // failure to bring it back to the inbox must not fail the run
- private async recordWaitingActivity(args: {
- workspaceId: string;
- threadId: string;
- text: string;
- }): Promise<void> {
- await this.threadService
- .recordThreadActivity(args)
- .catch((error: unknown) =>
- this.logger.warn(
- `Could not record waiting activity on thread ${args.threadId}: ${error instanceof Error ? error.message : String(error)}`,
- ),
- );
- }
-
private buildMessageParts(message: RunAgentMessage): ExtendedUIMessagePart[] {
const fileParts = (message.attachments ?? []).map(
(attachment): ExtendedFileUIPart => ({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
index 6fe856b5538..c426682efe6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
@@ -1,18 +1,13 @@
-import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
+import { Injectable, type OnModuleInit } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { type QueueJobOptions } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
-import { PendingWakeUpEventRecordService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
-import { type PendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-event.type';
import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-outcome.type';
-import {
- type PendingWakeUpBeforeClaimDecision,
- type PendingWakeUpOwnerHandler,
-} from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
-import { computePendingWakeUpRetryDelayMs } from 'src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util';
+import { type PendingWakeUpOwnerHandler } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
+import { type PendingWakeUpOwnerState } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type';
import { type AgentRunSuspensionEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity';
import { buildWaitOutcomeToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
@@ -29,28 +24,15 @@ import {
const RECENT_MESSAGES_TO_SEARCH_FOR_PENDING_CALL = 50;
-type AgentRunResolveContext = {
- suspension: AgentRunSuspensionEntity | null;
- // the caller stopped waiting, so the run is dropped instead of continued
- isCallerGone: boolean;
-};
-
// An AGENT_RUN wake-up is owned by a suspended run and keyed by the wait call it paused on
@Injectable()
export class AgentRunPendingWakeUpHandlerService
- implements PendingWakeUpOwnerHandler<AgentRunResolveContext>, OnModuleInit
+ implements PendingWakeUpOwnerHandler<AgentRunSuspensionEntity>, OnModuleInit
{
- readonly ownerType = 'AGENT_RUN';
-
- private readonly logger = new Logger(
- AgentRunPendingWakeUpHandlerService.name,
- );
-
constructor(
private readonly pendingWakeUpOwnerHandlerRegistryService: PendingWakeUpOwnerHandlerRegistryService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
- private readonly pendingWakeUpEventRecordService: PendingWakeUpEventRecordService,
@InjectAgentHistoryRepository('agentMessage')
private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessagePart')
@@ -58,93 +40,64 @@ export class AgentRunPendingWakeUpHandlerService
) {}
onModuleInit(): void {
- this.pendingWakeUpOwnerHandlerRegistryService.register(this);
+ this.pendingWakeUpOwnerHandlerRegistryService.register('AGENT_RUN', this);
}
buildResumeJobOptions(): QueueJobOptions {
return {};
}
- async beforeClaim({
- wakeUp,
- event,
- attempt,
- recordReadAttempt,
- }: {
- wakeUp: PendingWakeUpEntity;
- event?: PendingWakeUpEvent;
- attempt: number;
- recordReadAttempt: number;
- }): Promise<PendingWakeUpBeforeClaimDecision<AgentRunResolveContext>> {
- const { workspaceId, ownerId: suspensionId } = wakeUp;
-
+ async getOwnerState({
+ workspaceId,
+ ownerId: suspensionId,
+ }: PendingWakeUpEntity): Promise<
+ PendingWakeUpOwnerState<AgentRunSuspensionEntity>
+ > {
const suspension = await this.agentRunSuspensionService.findOne({
workspaceId,
where: { id: suspensionId },
});
- // claiming a wake-up whose run is gone only drops it
if (!isDefined(suspension)) {
- return {
- type: 'RESOLVE',
- context: { suspension, isCallerGone: false },
- };
+ return { status: 'GONE', owner: null };
}
- const waitingState =
- await this.agentRunSuspensionService.getCallerWaitingState({
- workspaceId,
- suspension,
- });
-
- // the wait is armed before its caller records that it waits, so the wake-up is held until it does
- if (waitingState === 'NOT_READY') {
- return {
- type: 'RETRY_LATER',
- attempt: attempt + 1,
- delayMs: computePendingWakeUpRetryDelayMs(attempt),
- };
- }
+ const status = await this.callerHandlerRegistry
+ .getHandlerOrThrow(suspension.caller.type)
+ .getWaitingState({ workspaceId, caller: suspension.caller });
- if (waitingState === 'GONE' || !isDefined(event)) {
- return {
- type: 'RESOLVE',
- context: { suspension, isCallerGone: waitingState === 'GONE' },
- };
- }
+ return status === 'NOT_READY' ? { status } : { status, owner: suspension };
+ }
- const { authContext, rolePermissionConfig } =
- await this.callerHandlerRegistry
- .getHandlerOrThrow(suspension.caller.type)
- .buildExecutionContext({ workspaceId, caller: suspension.caller });
-
- return this.pendingWakeUpEventRecordService.decideOnEventRecord({
- event,
- authContext,
- rolePermissionConfig,
- recordReadAttempt,
- context: { suspension, isCallerGone: false },
- onRecordReadGivenUp: (error) =>
- this.logger.warn(
- `Wait ${wakeUp.id} of agent run ${suspensionId} kept waiting after its ${event.eventName} record could not be read: ${error}`,
- ),
- });
+ // the run reads what its caller lets it read
+ async getReadPermissions({
+ wakeUp: { workspaceId },
+ owner: { caller },
+ }: {
+ wakeUp: PendingWakeUpEntity;
+ owner: AgentRunSuspensionEntity;
+ }) {
+ return this.callerHandlerRegistry
+ .getHandlerOrThrow(caller.type)
+ .buildExecutionContext({ workspaceId, caller });
}
async resolve({
claimedWakeUp: { workspaceId, ownerKey: toolCallId },
outcome,
- context: { suspension, isCallerGone },
+ owner: suspension,
+ isOwnerGone,
}: {
claimedWakeUp: PendingWakeUpEntity;
outcome: PendingWakeUpOutcome;
- context: AgentRunResolveContext;
+ owner: AgentRunSuspensionEntity | null;
+ isOwnerGone: boolean;
}): Promise<void> {
if (!isDefined(suspension)) {
return;
}
- if (isCallerGone) {
+ if (isOwnerGone) {
await this.agentRunSuspensionService.release({ workspaceId, suspension });
return;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
index 0fa748d2b5b..144ebfd1375 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import isEqual from 'lodash.isequal';
+import { type AgentRunSummary } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { IsNull, Not, Raw } from 'typeorm';
import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
@@ -18,10 +19,7 @@ import { buildWaitOutcomeToolOutput } from 'src/engine/metadata-modules/ai/ai-ag
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
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 AgentRunCallerWaitingState } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-waiting-state.type';
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
-import { type AgentRunWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-wait.type';
import { type ContinueAgentRunJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type';
import { isToolOutputAwaitedByCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util';
import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
@@ -39,8 +37,6 @@ import {
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';
-const AGENT_RUN_OWNER_TYPE = 'AGENT_RUN';
-
// The suspended runs callers wait on: what continues them, and who gets their outcome
@Injectable()
export class AgentRunSuspensionService {
@@ -147,26 +143,6 @@ export class AgentRunSuspensionService {
}
}
- async armWait({
- workspaceId,
- suspensionId,
- wait,
- }: {
- workspaceId: string;
- suspensionId: string;
- wait: AgentRunWait;
- }): Promise<void> {
- await this.pendingWakeUpService.arm({
- workspaceId,
- owner: {
- type: AGENT_RUN_OWNER_TYPE,
- id: suspensionId,
- key: wait.toolCallId,
- },
- condition: wait.condition,
- });
- }
-
async scheduleContinuation({
workspaceId,
suspension,
@@ -184,18 +160,6 @@ export class AgentRunSuspensionService {
);
}
- async getCallerWaitingState({
- workspaceId,
- suspension: { caller },
- }: {
- workspaceId: string;
- suspension: AgentRunSuspensionEntity;
- }): Promise<AgentRunCallerWaitingState> {
- return this.callerHandlerRegistry
- .getHandlerOrThrow(caller.type)
- .getWaitingState({ workspaceId, caller });
- }
-
// The caller marks its call before it records the suspension, so a call without one is not ready yet
async findWaitingSuspension({
workspaceId,
@@ -213,10 +177,9 @@ export class AgentRunSuspensionService {
return { status: 'NOT_READY' };
}
- const status = await this.getCallerWaitingState({
- workspaceId,
- suspension,
- });
+ const status = await this.callerHandlerRegistry
+ .getHandlerOrThrow(suspension.caller.type)
+ .getWaitingState({ workspaceId, caller: suspension.caller });
return status === 'NOT_READY' ? { status } : { status, suspension };
}
@@ -308,10 +271,9 @@ export class AgentRunSuspensionService {
workspaceId: string;
suspension: Pick<AgentRunSuspensionEntity, 'id' | 'threadId'>;
}): Promise<void> {
- await this.pendingWakeUpService.cancelAllForOwner({
+ await this.pendingWakeUpService.cancel({
workspaceId,
- ownerType: AGENT_RUN_OWNER_TYPE,
- ownerId: suspension.id,
+ owner: { type: 'AGENT_RUN', id: suspension.id },
});
await this.suspensionRepository.delete(workspaceId, { id: suspension.id });
await this.closeAwaitedCalls({
@@ -329,7 +291,20 @@ export class AgentRunSuspensionService {
workspaceId: string;
threadId: string;
}): Promise<void> {
- await this.closeWaitCalls({ workspaceId, threadId });
+ // a wait call is not a question, so it stays pending until its wake-up resolves it or its run is dropped
+ await this.messagePartRepository.query(workspaceId, ({ manager, table }) =>
+ manager.query(
+ `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'`,
+ [
+ threadId,
+ JSON.stringify(buildWaitOutcomeToolOutput({ type: 'CANCELLED' })),
+ AGENT_WAIT_TOOL_NAMES,
+ ],
+ ),
+ );
const thread = await this.threadRepository.findOne(workspaceId, {
where: {
@@ -385,27 +360,4 @@ export class AgentRunSuspensionService {
status: AgentTurnStatus.CANCELLED,
});
}
-
- // a wait call is not a question, so it stays pending until its wake-up resolves it or its run is dropped
- private async closeWaitCalls({
- workspaceId,
- threadId,
- }: {
- workspaceId: string;
- threadId: string;
- }): Promise<void> {
- await this.messagePartRepository.query(workspaceId, ({ manager, table }) =>
- manager.query(
- `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'`,
- [
- threadId,
- JSON.stringify(buildWaitOutcomeToolOutput({ type: 'CANCELLED' })),
- AGENT_WAIT_TOOL_NAMES,
- ],
- ),
- );
- }
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
index 5aef55e91a2..10b057669d1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
@@ -21,6 +21,7 @@ import { buildCreatedByFromApplication } from 'src/engine/core-modules/actor/uti
import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
@@ -61,8 +62,6 @@ type AgentApiRunCaller = Extract<AgentRunCaller, { type: 'AGENT_API_RUN' }>;
export class AgentRunService
implements AgentRunCallerHandler<AgentApiRunCaller>, OnModuleInit
{
- readonly callerType = 'AGENT_API_RUN';
-
private readonly logger = new Logger(AgentRunService.name);
constructor(
@@ -75,7 +74,7 @@ export class AgentRunService
) {}
onModuleInit(): void {
- this.callerHandlerRegistry.register(this);
+ this.callerHandlerRegistry.register('AGENT_API_RUN', this);
}
async run({
@@ -106,8 +105,21 @@ export class AgentRunService
const thread = input.thread ?? null;
- if (isDefined(thread)) {
- this.assertCanContinueConversation({ callerApplication, messages });
+ if (isDefined(thread) && !isDefined(callerApplication)) {
+ throw new AiException(
+ 'Continuing a conversation requires an application access token',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ if (
+ isDefined(thread) &&
+ messages.some((message) => message.role !== 'user')
+ ) {
+ throw new AiException(
+ 'A conversation already holds its replies, so only user messages can be sent to it',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
}
const agent = await this.agentRepository.findOne(workspace.id, {
@@ -193,11 +205,10 @@ export class AgentRunService
agent,
prompt: {
messages,
- senderUserWorkspaceId: this.resolveRunSender({
- runAsContext,
- callerApplication,
- requestUserWorkspaceId,
- }),
+ // a member calling without runAs still sent the input, while an app's call has no member behind it
+ senderUserWorkspaceId:
+ runAsContext?.authContext.userWorkspaceId ??
+ (isDefined(callerApplication) ? null : requestUserWorkspaceId),
senderApplicationId: callerApplication?.id ?? null,
},
executionContext: await this.buildExecutionContext({
@@ -284,6 +295,7 @@ export class AgentRunService
userWorkspaceId: runAsContext.authContext.userWorkspaceId,
}
: { type: 'application', applicationId: agentContext.application.id },
+ usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
};
}
@@ -330,27 +342,6 @@ export class AgentRunService
}
}
- // a member calling without runAs still sent the input, while an app's call has no member behind it
- private resolveRunSender({
- runAsContext,
- callerApplication,
- requestUserWorkspaceId,
- }: {
- runAsContext?: RunAsWorkspaceMemberContext;
- callerApplication?: FlatApplication;
- requestUserWorkspaceId: string | null;
- }): string | null {
- if (isDefined(runAsContext)) {
- return runAsContext.authContext.userWorkspaceId;
- }
-
- if (isDefined(callerApplication)) {
- return null;
- }
-
- return requestUserWorkspaceId;
- }
-
private buildRunCreator({
callerApplication,
application,
@@ -369,28 +360,6 @@ export class AgentRunService
: buildCreatedByFromApplication({ application });
}
- private assertCanContinueConversation({
- callerApplication,
- messages,
- }: {
- callerApplication?: FlatApplication;
- messages: RunAgentMessage[];
- }): void {
- if (!isDefined(callerApplication)) {
- throw new AiException(
- 'Continuing a conversation requires an application access token',
- AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
- );
- }
-
- if (messages.some((message) => message.role !== 'user')) {
- throw new AiException(
- 'A conversation already holds its replies, so only user messages can be sent to it',
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
- }
-
private async resolveRunAsContext({
runAsWorkspaceMemberId,
callerApplication,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
index 7b6c64786b8..e51cbe3ed7d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
@@ -4,11 +4,12 @@ import { isNonEmptyString } from '@sniptt/guards';
import {
ASK_QUESTION_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
+ type AgentRunSummary,
} from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
-import { AGENT_RUN_MAX_CONTINUATIONS } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-max-continuations.const';
+import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
import { AgentRunSuspensionEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity';
import { AGENT_WAIT_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-prompt.constant';
import { createAgentWaitTools } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/create-agent-wait-tools.util';
@@ -18,11 +19,7 @@ import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-module
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
-import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
-import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
-import { type AgentRunnerResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type';
import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
import { type ContinueAgentRunJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type';
import { buildAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util';
@@ -39,6 +36,15 @@ import {
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';
+const AGENT_RUN_MAX_CONTINUATIONS = 50;
+
+type AgentRunnerResult = {
+ threadId: string;
+ outcome: AgentRunnerOutcome;
+ // the run so far, across every segment of a continued run
+ summary: AgentRunSummary;
+};
+
// Runs an agent turn and records it in its conversation. A run that pauses on an answer or a wait
// is suspended: the engine continues it on its own, through this same runner, and hands the
// outcome to its caller's handler
@@ -52,6 +58,7 @@ export class AgentRunnerService {
private readonly conversationReaderService: AgentConversationReaderService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
+ private readonly pendingWakeUpService: PendingWakeUpService,
@InjectWorkspaceScopedRepository(AgentRunSuspensionEntity)
private readonly suspensionRepository: WorkspaceScopedRepository<AgentRunSuspensionEntity>,
@InjectWorkspaceScopedRepository(AgentEntity)
@@ -82,14 +89,9 @@ export class AgentRunnerService {
}
const { caller, runSpec, threadId } = suspension;
+ const handler = this.callerHandlerRegistry.getHandlerOrThrow(caller.type);
- const waitingState =
- await this.agentRunSuspensionService.getCallerWaitingState({
- workspaceId,
- suspension,
- });
-
- if (waitingState === 'GONE') {
+ if ((await handler.getWaitingState({ workspaceId, caller })) === 'GONE') {
await this.agentRunSuspensionService.release({ workspaceId, suspension });
return;
@@ -106,21 +108,29 @@ export class AgentRunnerService {
return;
}
- const handler = this.callerHandlerRegistry.getHandlerOrThrow(caller.type);
-
let result: AgentRunnerResult;
try {
+ const agent = isDefined(runSpec.agentId)
+ ? await this.agentRepository.findOne(workspaceId, {
+ where: { id: runSpec.agentId },
+ })
+ : null;
+
+ if (isDefined(runSpec.agentId) && !isDefined(agent)) {
+ throw new AiException(
+ `Agent with id ${runSpec.agentId} not found`,
+ AiExceptionCode.AGENT_NOT_FOUND,
+ );
+ }
+
result = await this.runSegment({
input: {
workspaceId,
conversation: { threadId, isCreated: false },
caller,
spec: runSpec,
- agent: await this.findAgentOrThrow({
- workspaceId,
- agentId: runSpec.agentId,
- }),
+ agent,
prompt: null,
executionContext: await handler.buildExecutionContext({
workspaceId,
@@ -154,6 +164,8 @@ export class AgentRunnerService {
}
}
+ // nothing else writes to the conversation while the run goes on: another run would read it half
+ // written, and a run that suspends would read a member's message once it goes on
private runSegment({
input,
suspension,
@@ -162,8 +174,6 @@ export class AgentRunnerService {
// the suspension a continued run resumes from
suspension: AgentRunSuspensionEntity | null;
}): Promise<AgentRunnerResult> {
- // nothing else writes to the conversation while the run goes on: another run would read it half
- // written, and a run that suspends would read a member's message once it goes on
return this.agentRunConversationService.withThreadLock({
workspaceId: input.workspaceId,
threadId: input.conversation.threadId,
@@ -181,13 +191,12 @@ export class AgentRunnerService {
const {
workspaceId,
conversation: { threadId, isCreated },
- caller,
spec,
agent,
prompt,
executionContext,
- resolveCreatedBy,
} = input;
+ const agentId = agent?.id ?? null;
if (!isCreated && !isDefined(suspension)) {
await this.agentRunSuspensionService.assertConversationNotSuspended({
@@ -203,40 +212,74 @@ export class AgentRunnerService {
threadId,
actor: executionContext.conversationActor,
});
- const agentId = agent?.id ?? null;
- const turnId = await this.recordConversation(threadId, async () =>
- this.agentRunConversationService.openTurn({
- workspaceId,
- threadId,
- title: spec.title,
- agentId,
- senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,
- senderApplicationId: prompt?.senderApplicationId ?? null,
- createdBy: await resolveCreatedBy(),
- messages: prompt?.messages ?? [],
- }),
+ const turnId = await this.tryRecording(
+ `record the agent turn in thread ${threadId}`,
+ async () =>
+ this.agentRunConversationService.openTurn({
+ workspaceId,
+ threadId,
+ title: spec.title,
+ agentId,
+ senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,
+ senderApplicationId: prompt?.senderApplicationId ?? null,
+ createdBy: await input.resolveCreatedBy(),
+ messages: prompt?.messages ?? [],
+ }),
);
const startedAtMs = Date.now();
- let executionResult: AgentExecutionResult;
+ let execution: AgentExecutionResult;
try {
- executionResult = await withDedicatedAiTrace(() =>
+ // the toolset and prompt come from the spec alone, so a continued run gets those it paused with
+ execution = await withDedicatedAiTrace(() =>
this.agentAsyncExecutorService.executeAgent({
- ...this.buildExecution(input),
+ agent,
+ messages: prompt?.messages ?? [],
priorMessages,
+ // every run here goes on in the background, unlike a chat, so it can wait. The wait tools are
+ // the engine's, so it explains them; the caller's own instructions come last
+ baseSystemPrompt: [
+ spec.baseSystemPrompt,
+ AGENT_WAIT_PROMPT,
+ ...(isNonEmptyString(spec.instructions) ? [spec.instructions] : []),
+ ].join('\n\n'),
+ pausingTools: {
+ ...createAgentWaitTools(),
+ ...(spec.capabilities.canAskHumans
+ ? {
+ [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
+ isWorkspaceSetupThread: false,
+ }),
+ [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
+ }
+ : {}),
+ },
+ canProposeToolCalls: spec.capabilities.canProposeToolCalls,
+ actorContext: executionContext.actorContext,
+ authContext: executionContext.authContext,
+ workspaceId,
+ userWorkspaceId: executionContext.userWorkspaceId,
+ runAsRoleId: executionContext.runAsRoleId,
+ additionalRoleRestrictionIds:
+ executionContext.additionalRoleRestrictionIds,
+ additionalExcludedToolNames: spec.additionalExcludedToolNames,
+ toolLoadingStrategy: spec.toolLoadingStrategy,
+ usageOperationType: executionContext.usageOperationType,
}),
);
} catch (error) {
if (isDefined(turnId)) {
- await this.recordConversation(threadId, () =>
- this.agentRunConversationService.failTurn({
- workspaceId,
- turnId,
- error,
- }),
+ await this.tryRecording(
+ `record the agent turn in thread ${threadId}`,
+ () =>
+ this.agentRunConversationService.failTurn({
+ workspaceId,
+ turnId,
+ error,
+ }),
);
}
@@ -246,37 +289,32 @@ export class AgentRunnerService {
const durationMs = Date.now() - startedAtMs;
const closedTurn = isDefined(turnId)
- ? await this.recordConversation(threadId, () =>
- this.agentRunConversationService.closeTurn({
- workspaceId,
- threadId,
- turnId,
- title: spec.title,
- agentId,
- execution: executionResult,
- }),
+ ? await this.tryRecording(
+ `record the agent turn in thread ${threadId}`,
+ () =>
+ this.agentRunConversationService.closeTurn({
+ workspaceId,
+ threadId,
+ turnId,
+ title: spec.title,
+ agentId,
+ execution,
+ }),
)
: null;
const summary = sumAgentRunSummaries({
previousSummary: suspension?.summary ?? null,
- nextSummary: buildAgentRunSummary({
- execution: executionResult,
- durationMs,
- }),
+ nextSummary: buildAgentRunSummary({ execution, durationMs }),
});
return {
threadId,
summary,
outcome: await this.settleTurn({
- workspaceId,
- threadId,
- caller,
- spec,
- execution: executionResult,
- isRecorded: isDefined(closedTurn),
- isAwaitingAnswer: closedTurn?.isAwaitingAnswer ?? false,
+ input,
+ execution,
+ closedTurn,
summary,
suspension,
}),
@@ -284,23 +322,16 @@ export class AgentRunnerService {
}
private async settleTurn({
- workspaceId,
- threadId,
- caller,
- spec,
+ input: { workspaceId, conversation, caller, spec },
execution,
- isRecorded,
- isAwaitingAnswer,
+ closedTurn,
summary,
suspension,
}: {
- workspaceId: string;
- threadId: string;
- caller: AgentRunCaller;
- spec: AgentRunSpec;
+ input: AgentRunnerRunInput;
execution: AgentExecutionResult;
- isRecorded: boolean;
- isAwaitingAnswer: boolean;
+ // null when the turn could not be recorded
+ closedTurn: { isAwaitingAnswer: boolean } | null;
summary: AgentRunSummary;
suspension: AgentRunSuspensionEntity | null;
}): Promise<AgentRunnerOutcome> {
@@ -308,6 +339,7 @@ export class AgentRunnerService {
return { status: 'COMPLETED', result: execution.result };
}
+ const { threadId } = conversation;
const wait = findAgentRunWait(
execution.steps[execution.steps.length - 1]?.toolResults ?? [],
);
@@ -315,20 +347,38 @@ export class AgentRunnerService {
isDefined(suspension) &&
suspension.resumeCount + 1 >= AGENT_RUN_MAX_CONTINUATIONS;
- // continuing reads the conversation, so a pause it does not hold could never be continued
+ // continuing reads the conversation, so a pause it does not hold could never be continued.
+ // A failure to suspend only fails the run, like a pause that could not be recorded
const suspensionId =
!execution.hasNoMoreAvailableCredits &&
!hasPausedTooOften &&
- isRecorded &&
- (isAwaitingAnswer || isDefined(wait))
- ? await this.keepSuspended({
- workspaceId,
- threadId,
- caller,
- spec,
- summary,
- suspension,
- })
+ isDefined(closedTurn) &&
+ (closedTurn.isAwaitingAnswer || isDefined(wait))
+ ? await this.tryRecording(
+ `suspend the agent run in thread ${threadId}`,
+ async () => {
+ if (!isDefined(suspension)) {
+ return (
+ await this.agentRunSuspensionService.suspend({
+ workspaceId,
+ threadId,
+ caller,
+ runSpec: spec,
+ summary,
+ })
+ ).id;
+ }
+
+ // a caller that stopped waiting while the run went on has released it
+ const { affected } = await this.suspensionRepository.update(
+ workspaceId,
+ { id: suspension.id },
+ { summary } as QueryDeepPartialEntity<AgentRunSuspensionEntity>,
+ );
+
+ return affected === 0 ? null : suspension.id;
+ },
+ )
: null;
if (!isDefined(suspensionId)) {
@@ -369,149 +419,30 @@ export class AgentRunnerService {
}
if (isDefined(wait)) {
- await this.agentRunSuspensionService.armWait({
+ await this.pendingWakeUpService.arm({
workspaceId,
- suspensionId,
- wait,
+ owner: { type: 'AGENT_RUN', id: suspensionId, key: wait.toolCallId },
+ condition: wait.condition,
});
}
return { status: 'SUSPENDED', suspensionId };
}
- // A failure to suspend only fails the run, like a pause that could not be recorded
- private async keepSuspended({
- workspaceId,
- threadId,
- caller,
- spec,
- summary,
- suspension,
- }: {
- workspaceId: string;
- threadId: string;
- caller: AgentRunCaller;
- spec: AgentRunSpec;
- summary: AgentRunSummary;
- suspension: AgentRunSuspensionEntity | null;
- }): Promise<string | null> {
- try {
- if (!isDefined(suspension)) {
- const { id } = await this.agentRunSuspensionService.suspend({
- workspaceId,
- threadId,
- caller,
- runSpec: spec,
- summary,
- });
-
- return id;
- }
-
- // a caller that stopped waiting while the run went on has released it
- const { affected } = await this.suspensionRepository.update(
- workspaceId,
- { id: suspension.id },
- { summary } as QueryDeepPartialEntity<AgentRunSuspensionEntity>,
- );
-
- return affected === 0 ? null : suspension.id;
- } catch (error) {
- this.logger.error(
- `Failed to suspend the agent run in thread ${threadId}`,
- error instanceof Error ? error.stack : error,
- );
-
- return null;
- }
- }
-
- // The toolset and prompt come from the spec alone, so a continued run gets those it paused with
- private buildExecution({
- workspaceId,
- spec,
- agent,
- prompt,
- executionContext,
- }: AgentRunnerRunInput): Omit<
- Parameters<AgentAsyncExecutorService['executeAgent']>[0],
- 'priorMessages'
- > {
- const { canAskHumans, canProposeToolCalls } = spec.capabilities;
-
- return {
- agent,
- messages: prompt?.messages ?? [],
- // every run here goes on in the background, unlike a chat, so it can wait. The wait tools are
- // the engine's, so it explains them; the caller's own instructions come last
- baseSystemPrompt: [
- spec.baseSystemPrompt,
- AGENT_WAIT_PROMPT,
- ...(isNonEmptyString(spec.instructions) ? [spec.instructions] : []),
- ].join('\n\n'),
- pausingTools: {
- ...createAgentWaitTools(),
- ...(canAskHumans
- ? {
- [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
- isWorkspaceSetupThread: false,
- }),
- [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
- }
- : {}),
- },
- canProposeToolCalls,
- actorContext: executionContext.actorContext,
- authContext: executionContext.authContext,
- workspaceId,
- userWorkspaceId: executionContext.userWorkspaceId,
- runAsRoleId: executionContext.runAsRoleId,
- additionalRoleRestrictionIds:
- executionContext.additionalRoleRestrictionIds,
- additionalExcludedToolNames: spec.additionalExcludedToolNames,
- toolLoadingStrategy: spec.toolLoadingStrategy,
- };
- }
-
// A record of the run, not its outcome, so a write failure must not fail the run
- private async recordConversation<TResult>(
- threadId: string,
+ private async tryRecording<TResult>(
+ description: string,
record: () => Promise<TResult>,
): Promise<TResult | null> {
try {
return await record();
} catch (error) {
this.logger.error(
- `Failed to record the agent turn in thread ${threadId}`,
+ `Failed to ${description}`,
error instanceof Error ? error.stack : error,
);
return null;
}
}
-
- private async findAgentOrThrow({
- workspaceId,
- agentId,
- }: {
- workspaceId: string;
- agentId: string | null;
- }): Promise<AgentEntity | null> {
- if (!isDefined(agentId)) {
- return null;
- }
-
- const agent = await this.agentRepository.findOne(workspaceId, {
- where: { id: agentId },
- });
-
- if (!isDefined(agent)) {
- throw new AiException(
- `Agent with id ${agentId} not found`,
- AiExceptionCode.AGENT_NOT_FOUND,
- );
- }
-
- return agent;
- }
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-caller-inbox-delivery.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-caller-inbox-delivery.type.ts
deleted file mode 100644
index a064540da42..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-caller-inbox-delivery.type.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { type ProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type';
-
-export type AgentCallerInboxDelivery =
- | { status: 'DELIVERED'; threadId: string }
- // the member deleted the conversation, so the call can no longer be answered
- | { status: 'DISMISSED'; threadId: string }
- // the caller waits, and gets the answer through its handler's onOutcome
- | { status: 'AWAITING'; threadId: string }
- // a message sent before already holds the answer
- | { status: 'ANSWERED'; threadId: string; answer: ProposedToolCallAnswer };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
index 704e5da4668..b795c9d76c7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
@@ -1,3 +1,4 @@
+import { type AgentRunSummary } from 'twenty-shared/ai';
import { type ActorMetadata } from 'twenty-shared/types';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
@@ -5,13 +6,10 @@ import { type AgentRunCallerInput } from 'src/engine/metadata-modules/ai/ai-agen
import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type';
import { type AgentRunCallerWaitingState } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-waiting-state.type';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
export type AgentRunCallerHandler<
TCaller extends AgentRunCaller = AgentRunCaller,
> = {
- callerType: TCaller['type'];
-
buildExecutionContext(
input: AgentRunCallerInput<TCaller>,
): Promise<AgentRunExecutionContext>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
index 0236276060d..11ca1ef0985 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
@@ -2,10 +2,11 @@ import { type ActorMetadata } from 'twenty-shared/types';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
-// The permissions a run acts with, which its caller derives on each segment instead of the engine storing them
+// How a run acts and is billed, which its caller derives on each segment instead of the engine storing it
export type AgentRunExecutionContext = {
authContext: WorkspaceAuthContext;
actorContext?: ActorMetadata;
@@ -20,4 +21,6 @@ export type AgentRunExecutionContext = {
conversationActor?: AgentConversationActor;
// the application the caller is bound to, whose tools are the only ones a call it posts can propose
application?: FlatApplication;
+ // what the run's tokens are billed and reported as
+ usageOperationType: UsageOperationType;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-prompt.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-prompt.type.ts
deleted file mode 100644
index d9fa8a94b9e..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-prompt.type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { type RunAgentMessage } from 'twenty-shared/application';
-
-// what a run is asked, and who asked it
-export type AgentRunPrompt = {
- messages: RunAgentMessage[];
- senderUserWorkspaceId: string | null;
- senderApplicationId: string | null;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts
deleted file mode 100644
index 3643289228c..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type AgentRunToolCallLog } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type';
-
-export type AgentRunSummary = {
- modelId: string;
- usage: {
- inputTokens: number;
- outputTokens: number;
- reasoningTokens?: number;
- cacheReadTokens?: number;
- cacheCreationTokens?: number;
- totalTokens: number;
- };
- cost: {
- totalCostInDollars: number;
- creditsUsedMicro: number;
- };
- nativeWebSearchCallCount: number;
- toolCalls: AgentRunToolCallLog[];
- durationMs: number;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts
deleted file mode 100644
index 89a58d58199..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export type AgentRunToolCallLog = {
- toolName: string;
- toolCallId: string;
- providerExecuted?: boolean;
- input?: unknown;
- output?: unknown;
- errorMessage?: string;
- state: 'started' | 'success' | 'error' | 'awaiting-approval';
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-wait.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-wait.type.ts
deleted file mode 100644
index 19163fdc24c..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-wait.type.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
-
-// the wait call a run paused on, and what wakes it up
-export type AgentRunWait = {
- toolCallId: string;
- condition: PendingWakeUpCondition;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts
deleted file mode 100644
index cc256be9bdc..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
-
-export type AgentRunnerOpenedConversation =
- | ({ status: 'OPENED' } & AgentRunConversation)
- // the recipient deleted both the conversation its key names and the fallback one
- | { status: 'DELETED' };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts
deleted file mode 100644
index ae1b2b9d3d8..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
-import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
-
-export type AgentRunnerResult = {
- threadId: string;
- outcome: AgentRunnerOutcome;
- // the run so far, across every segment of a continued run
- summary: AgentRunSummary;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
index bc893bce0a2..c448f309055 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
@@ -1,9 +1,9 @@
+import { type RunAgentMessage } from 'twenty-shared/application';
import { type ActorMetadata } from 'twenty-shared/types';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
-import { type AgentRunPrompt } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-prompt.type';
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
@@ -15,8 +15,12 @@ export type AgentRunnerRunInput = {
caller: AgentRunCaller;
spec: AgentRunSpec;
agent: AgentEntity | null;
- // absent when the run continues its conversation without a new message
- prompt: AgentRunPrompt | null;
+ // what the run is asked and who asked it; absent when the run continues its conversation without a new message
+ prompt: {
+ messages: RunAgentMessage[];
+ senderUserWorkspaceId: string | null;
+ senderApplicationId: string | null;
+ } | null;
executionContext: AgentRunExecutionContext;
// resolved while recording the turn, so a failed lookup does not stop the run
resolveCreatedBy: () => Promise<ActorMetadata>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/application-agent-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/application-agent-context.type.ts
deleted file mode 100644
index 8f0042e357f..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/application-agent-context.type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import { type ApplicationWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-
-export type ApplicationAgentContext = {
- application: FlatApplication;
- authContext: ApplicationWorkspaceAuthContext;
- agentRoleId: string | undefined;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/sum-agent-run-summaries.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/sum-agent-run-summaries.util.spec.ts
index abf25c3c42c..12024cffe85 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/sum-agent-run-summaries.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/sum-agent-run-summaries.util.spec.ts
@@ -1,4 +1,5 @@
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
+import { type AgentRunSummary } from 'twenty-shared/ai';
+
import { sumAgentRunSummaries } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util';
const buildSummary = ({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts
index 921943fae5a..914ffb6c340 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts
@@ -1,5 +1,6 @@
+import { type AgentRunSummary } from 'twenty-shared/ai';
+
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { mapAgentStepsToToolCallLogs } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util';
export const buildAgentRunSummary = ({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
index 695fcb1ae7d..0041fd01ae1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
@@ -1,7 +1,7 @@
import { type StepResult, type ToolSet } from 'ai';
+import { type AgentRunToolCallLog } from 'twenty-shared/ai';
import { isFailedToolOutput } from 'src/engine/core-modules/tool-provider/utils/is-failed-tool-output.util';
-import { type AgentRunToolCallLog } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type';
import {
TRUNCATION_SENTINEL,
truncateStringToUtf8ByteBudget,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util.ts
index 2bc895f693a..e24c3a49046 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util.ts
@@ -1,7 +1,6 @@
+import { type AgentRunSummary } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
-
// a count no segment reported stays out
const sumCounts = <TCounts extends Record<string, number | undefined>>(
previousCounts: TCounts,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
index 08f73c84640..de5e0f2a4c0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
@@ -6,6 +6,7 @@ import { isDefined } from 'twenty-shared/utils';
import { v4 } from 'uuid';
import { buildCreatedByFromAgent } from 'src/engine/core-modules/actor/utils/build-created-by-from-agent.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
@@ -42,8 +43,6 @@ type TriggeredRun = {
export class AgentTriggerRunnerService
implements AgentRunCallerHandler<AgentTriggerCaller>, OnModuleInit
{
- readonly callerType = 'AGENT_TRIGGER';
-
private readonly logger = new Logger(AgentTriggerRunnerService.name);
constructor(
@@ -55,7 +54,7 @@ export class AgentTriggerRunnerService
) {}
onModuleInit(): void {
- this.callerHandlerRegistry.register(this);
+ this.callerHandlerRegistry.register('AGENT_TRIGGER', this);
}
async run({
@@ -185,6 +184,7 @@ export class AgentTriggerRunnerService
actorContext: createdBy,
userWorkspaceId: null,
rolePermissionConfig: buildAgentRolePermissionConfig({ agentRoleId }),
+ usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
},
};
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
index cfb4ddb384a..f82ae102f0a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
@@ -294,7 +294,7 @@ describe('AgentChatStreamingService claim & reap', () => {
});
await expect(send()).rejects.toMatchObject({
- code: AiExceptionCode.THREAD_AWAITING_CALLER_INPUT,
+ code: AiExceptionCode.THREAD_AWAITING_ANSWER,
});
expect(agentChatService.closePendingToolCalls).not.toHaveBeenCalled();
expect(agentChatService.addMessage).not.toHaveBeenCalled();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 7660036e040..d85bc92b9fc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -648,7 +648,7 @@ export class AgentChatStreamingService {
) {
throw new AiException(
'This conversation is waiting on an answer to the run that asked',
- AiExceptionCode.THREAD_AWAITING_CALLER_INPUT,
+ AiExceptionCode.THREAD_AWAITING_ANSWER,
);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
index c0487d41707..89a910ea71d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
@@ -32,7 +32,6 @@ export enum AiExceptionCode {
EVALUATION_QUESTION_UNSUPPORTED = 'EVALUATION_QUESTION_UNSUPPORTED',
INVALID_EVALUATION_REQUEST = 'INVALID_EVALUATION_REQUEST',
TOOL_CALL_RESOLUTION_FORBIDDEN = 'TOOL_CALL_RESOLUTION_FORBIDDEN',
- THREAD_AWAITING_CALLER_INPUT = 'THREAD_AWAITING_CALLER_INPUT',
THREAD_AWAITING_ANSWER = 'THREAD_AWAITING_ANSWER',
}
@@ -92,10 +91,8 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
return msg`Invalid classification request.`;
case AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN:
return msg`You are not allowed to answer this request.`;
- case AiExceptionCode.THREAD_AWAITING_CALLER_INPUT:
- return msg`This conversation is waiting for an answer. Answer it before sending a message.`;
case AiExceptionCode.THREAD_AWAITING_ANSWER:
- return msg`This conversation is waiting for an answer to an earlier request.`;
+ return msg`This conversation is waiting on an earlier request. Send your message once it is answered or done.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
index 6fa49188e9c..203ee14080e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
@@ -35,7 +35,6 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {
throw new UserInputError(error);
case AiExceptionCode.AGENT_ALREADY_EXISTS:
case AiExceptionCode.NO_FAILED_TURN_TO_RETRY:
- case AiExceptionCode.THREAD_AWAITING_CALLER_INPUT:
case AiExceptionCode.CHAT_THREAD_INBOX_STATE_UNAVAILABLE:
case AiExceptionCode.THREAD_AWAITING_ANSWER:
throw new ConflictError(error);
diff --git a/packages/twenty-server/src/engine/utils/handler-registry.ts b/packages/twenty-server/src/engine/utils/handler-registry.ts
new file mode 100644
index 00000000000..1b8c718add7
--- /dev/null
+++ b/packages/twenty-server/src/engine/utils/handler-registry.ts
@@ -0,0 +1,20 @@
+import { isDefined } from 'twenty-shared/utils';
+
+// lets the engine call back code it must not import, such as workflow handlers, which register themselves here
+export class HandlerRegistry<TKey extends string, THandler> {
+ private readonly handlers = new Map<TKey, THandler>();
+
+ register(key: TKey, handler: THandler): void {
+ this.handlers.set(key, handler);
+ }
+
+ getHandlerOrThrow(key: TKey): THandler {
+ const handler = this.handlers.get(key);
+
+ if (!isDefined(handler)) {
+ throw new Error(`No handler is registered for ${key}`);
+ }
+
+ return handler;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-base-system-prompt.constant.ts
similarity index 100%
rename from packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const.ts
rename to packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-base-system-prompt.constant.ts
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
index 82d7d898c10..f3f09dfe92c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
@@ -57,7 +57,7 @@ describe('WorkflowAgentConversationWorkspaceService', () => {
...OPEN_ARGS,
recipientWorkspaceMemberId: 'recipient-id',
}),
- ).resolves.toEqual({ threadId: 'thread-id', isCreated: true });
+ ).resolves.toMatchObject({ threadId: 'thread-id', isCreated: true });
expect(
agentCallerConversationService.openConversation,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index 78a1bd8db2a..f2a7e80232e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -68,10 +68,7 @@ export class WorkflowAgentConversationWorkspaceService {
);
}
- return {
- threadId: openedConversation.threadId,
- isCreated: openedConversation.isCreated,
- };
+ return openedConversation;
}
async findTurnCreatedBy(runInfo: WorkflowRunInfo): Promise<ActorMetadata> {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
index 24385f8ee9d..64b0eb9cfbb 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
@@ -1,4 +1,5 @@
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
+import { type AgentRunSummary } from 'twenty-shared/ai';
+
import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';
const SUMMARY: AgentRunSummary = {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
index 792128f482d..11dc6af998a 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
@@ -1,7 +1,6 @@
+import { type AgentRunSummary } from 'twenty-shared/ai';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
-
export const buildAiAgentStepLog = ({
summary,
threadId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
index e110da9ca22..f2e6704affe 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
@@ -1,5 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
import { type WorkflowExecutionContext } from 'src/modules/workflow/workflow-executor/types/workflow-execution-context.type';
@@ -17,6 +18,7 @@ export const buildWorkflowAgentRunExecutionContext = (
? executionContext.authContext.userWorkspaceId
: null,
rolePermissionConfig: executionContext.rolePermissionConfig,
+ usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
...(isDefined(executionContext.application)
? {
application: executionContext.application,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
index 37737e5a86f..9bc3327bce1 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
@@ -1,7 +1,7 @@
import { isNonEmptyString } from '@sniptt/guards';
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
-import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const';
+import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-base-system-prompt.constant';
import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant';
import { WORKFLOW_AGENT_HUMAN_INPUT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant';
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
index f5816014157..fa3a41c2ca9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
@@ -24,7 +24,8 @@ import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner
import { isWorkflowRunNotFoundError } from 'src/modules/workflow/workflow-runner/utils/is-workflow-run-not-found-error.util';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-// Drains delays queued before delays became time waits; new ones resume through ResumeWaitingWorkflowStepJob
+// Drains delays 2.45 and earlier queued as delayed jobs; new ones are TIME waits resumed through
+// ResumePendingWakeUpJob. Remove once upgrades no longer start from 2.45
@Processor({
queueName: MessageQueue.delayedJobsQueue,
scope: Scope.REQUEST,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
index edab6dc0210..c222968f684 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
@@ -1,7 +1,7 @@
import { WorkflowActionType } from 'twenty-shared/workflow';
import { type WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
-import { type AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service';
+import { type AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { WorkflowStepExecutorExceptionCode } from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
@@ -60,7 +60,7 @@ describe('SendChatMessageWorkflowAction', () => {
});
action = new SendChatMessageWorkflowAction(
- { sendMessage } as unknown as AgentCallerInboxService,
+ { sendMessage } as unknown as AgentCallerConversationService,
new WorkflowRunInboxSenderWorkspaceService(
{
executeInWorkspaceContext: jest.fn((callback) => callback()),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
index 69be3abb0b5..e4dfa8e3ca3 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
@@ -5,7 +5,7 @@ import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
-import { AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service';
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -23,7 +23,7 @@ import { type WorkflowSendChatMessageActionInput } from 'src/modules/workflow/wo
@Injectable()
export class SendChatMessageWorkflowAction implements WorkflowAction {
constructor(
- private readonly agentCallerInboxService: AgentCallerInboxService,
+ private readonly agentCallerConversationService: AgentCallerConversationService,
private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,
) {}
@@ -76,7 +76,7 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
stepExecutionKey: executionKey,
});
- const delivery = await this.agentCallerInboxService.sendMessage({
+ const delivery = await this.agentCallerConversationService.sendMessage({
workspaceId: runInfo.workspaceId,
sender,
message: {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
index 3fde690772c..cfc40b9b0a8 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
@@ -1,10 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
+import { type AgentRunSummary } from 'twenty-shared/ai';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
import { DataSource } from 'typeorm';
-import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-agent-run-caller-handler.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-agent-run-caller-handler.workspace-service.ts
index 740f4a2a9d9..987071113d3 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-agent-run-caller-handler.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-agent-run-caller-handler.workspace-service.ts
@@ -31,8 +31,6 @@ type WorkflowStepCaller = Extract<AgentRunCaller, { type: 'WORKFLOW_STEP' }>;
export class WorkflowAgentRunCallerHandlerWorkspaceService
implements AgentRunCallerHandler<WorkflowStepCaller>, OnModuleInit
{
- readonly callerType = 'WORKFLOW_STEP';
-
constructor(
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
@@ -44,7 +42,7 @@ export class WorkflowAgentRunCallerHandlerWorkspaceService
) {}
onModuleInit(): void {
- this.callerHandlerRegistry.register(this);
+ this.callerHandlerRegistry.register('WORKFLOW_STEP', this);
}
async buildExecutionContext({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-pending-wake-up-handler.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-pending-wake-up-handler.workspace-service.spec.ts
index cbd49ac511b..4030c2894b5 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-pending-wake-up-handler.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-pending-wake-up-handler.workspace-service.spec.ts
@@ -1,6 +1,5 @@
import { StepStatus } from 'twenty-shared/workflow';
-import { PendingWakeUpEventRecordService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
import { PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
@@ -86,13 +85,13 @@ const buildService = ({
registry,
workflowRunWorkspaceService as never,
workflowExecutionContextService as never,
- new PendingWakeUpEventRecordService(findRecordsService as never),
messageQueueService as never,
).onModuleInit();
const service = new PendingWakeUpResolverService(
pendingWakeUpService as never,
registry,
+ findRecordsService as never,
);
return {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-pending-wake-up-handler.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-pending-wake-up-handler.workspace-service.ts
index 8cf5086a9ad..dd5f94ad3ac 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-pending-wake-up-handler.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-pending-wake-up-handler.workspace-service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
+import { Injectable, type OnModuleInit } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { StepStatus } from 'twenty-shared/workflow';
@@ -8,15 +8,10 @@ import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decora
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 { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
-import { PendingWakeUpEventRecordService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-event-record.service';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
-import { type PendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-event.type';
import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-outcome.type';
-import {
- type PendingWakeUpBeforeClaimDecision,
- type PendingWakeUpOwnerHandler,
-} from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
-import { computePendingWakeUpRetryDelayMs } from 'src/engine/core-modules/pending-wake-up/utils/compute-pending-wake-up-retry-delay-ms.util';
+import { type PendingWakeUpOwnerHandler } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
+import { type PendingWakeUpOwnerState } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type';
import {
WorkflowRunStatus,
type WorkflowRunWorkspaceEntity,
@@ -29,100 +24,76 @@ import { isWorkflowRunNotFoundError } from 'src/modules/workflow/workflow-runner
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { buildDefaultWaitResult } from 'src/modules/workflow/workflow-wait/utils/build-default-wait-result.util';
-type WorkflowStepResolveContext = {
- workflowRun: WorkflowRunWorkspaceEntity | null;
-};
-
// A WORKFLOW_STEP wake-up is owned by a workflow run and keyed by the step that waits
@Injectable()
export class WorkflowStepPendingWakeUpHandlerWorkspaceService
implements
- PendingWakeUpOwnerHandler<WorkflowStepResolveContext>,
+ PendingWakeUpOwnerHandler<WorkflowRunWorkspaceEntity>,
OnModuleInit
{
- readonly ownerType = 'WORKFLOW_STEP';
-
- private readonly logger = new Logger(
- WorkflowStepPendingWakeUpHandlerWorkspaceService.name,
- );
-
constructor(
private readonly pendingWakeUpOwnerHandlerRegistryService: PendingWakeUpOwnerHandlerRegistryService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly workflowExecutionContextService: WorkflowExecutionContextService,
- private readonly pendingWakeUpEventRecordService: PendingWakeUpEventRecordService,
@InjectMessageQueue(MessageQueue.workflowQueue)
private readonly messageQueueService: MessageQueueService,
) {}
onModuleInit(): void {
- this.pendingWakeUpOwnerHandlerRegistryService.register(this);
+ this.pendingWakeUpOwnerHandlerRegistryService.register(
+ 'WORKFLOW_STEP',
+ this,
+ );
}
buildResumeJobOptions(workflowRunId: string): QueueJobOptions {
return buildRunWorkflowJobOptions(workflowRunId);
}
- async beforeClaim({
- wakeUp,
- event,
- attempt,
- recordReadAttempt,
- }: {
- wakeUp: PendingWakeUpEntity;
- event?: PendingWakeUpEvent;
- attempt: number;
- recordReadAttempt: number;
- }): Promise<PendingWakeUpBeforeClaimDecision<WorkflowStepResolveContext>> {
- const { workspaceId, ownerId: workflowRunId, ownerKey: stepId } = wakeUp;
-
+ async getOwnerState({
+ workspaceId,
+ ownerId: workflowRunId,
+ ownerKey: stepId,
+ }: PendingWakeUpEntity): Promise<
+ PendingWakeUpOwnerState<WorkflowRunWorkspaceEntity>
+ > {
const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({
workflowRunId,
workspaceId,
});
const stepStatus = workflowRun?.state?.stepInfos?.[stepId]?.status;
- const isRunRunning = workflowRun?.status === WorkflowRunStatus.RUNNING;
-
- // the wait is armed before its step reads as pending, so the event is held until it does or the run ends
- if (isRunRunning && stepStatus === StepStatus.RUNNING) {
- return {
- type: 'RETRY_LATER',
- attempt: attempt + 1,
- delayMs: computePendingWakeUpRetryDelayMs(attempt),
- };
- }
- if (isRunRunning && stepStatus === StepStatus.PENDING && isDefined(event)) {
- const { authContext, rolePermissionConfig } =
- await this.workflowExecutionContextService.getExecutionContext({
- workflowRunId,
- workspaceId,
- });
+ if (workflowRun?.status !== WorkflowRunStatus.RUNNING) {
+ return { status: 'GONE', owner: workflowRun };
+ }
- return this.pendingWakeUpEventRecordService.decideOnEventRecord({
- event,
- authContext,
- rolePermissionConfig,
- recordReadAttempt,
- context: { workflowRun },
- onRecordReadGivenUp: (error) =>
- this.logger.warn(
- `Wait ${wakeUp.id} of workflow run ${workflowRunId} kept waiting after its ${event.eventName} record could not be read: ${error}`,
- ),
- });
+ // the wait is armed before its step reads as pending
+ if (stepStatus === StepStatus.RUNNING) {
+ return { status: 'NOT_READY' };
}
- return { type: 'RESOLVE', context: { workflowRun } };
+ return {
+ status: stepStatus === StepStatus.PENDING ? 'WAITING' : 'GONE',
+ owner: workflowRun,
+ };
+ }
+
+ async getReadPermissions({ wakeUp }: { wakeUp: PendingWakeUpEntity }) {
+ return this.workflowExecutionContextService.getExecutionContext({
+ workflowRunId: wakeUp.ownerId,
+ workspaceId: wakeUp.workspaceId,
+ });
}
async resolve({
claimedWakeUp,
outcome,
- context: { workflowRun },
+ owner: workflowRun,
}: {
claimedWakeUp: PendingWakeUpEntity;
outcome: PendingWakeUpOutcome;
- context: WorkflowStepResolveContext;
+ owner: WorkflowRunWorkspaceEntity | null;
+ isOwnerGone: boolean;
}): Promise<void> {
if (!isDefined(workflowRun)) {
return;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts
index 752ac3e36b7..15c5553ac30 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts
@@ -53,10 +53,9 @@ export class WorkflowStepWaitWorkspaceService {
workspaceId: string;
workflowRunId: string;
}): Promise<void> {
- await this.pendingWakeUpService.cancelAllForOwner({
+ await this.pendingWakeUpService.cancel({
workspaceId,
- ownerType: 'WORKFLOW_STEP',
- ownerId: workflowRunId,
+ owner: { type: 'WORKFLOW_STEP', id: workflowRunId },
});
}
}
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
index 7587c37b7aa..681376d7f50 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
@@ -13,7 +13,7 @@ import { getAppProviderByClassName } from 'test/integration/utils/get-app-provid
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-import { type AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service';
+import { type AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { type WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
@@ -234,7 +234,7 @@ describe('Send chat message workflow step', () => {
arguments: { id: companyId, employees: 25 },
};
let postAgain: () => ReturnType<
- AgentCallerInboxService['sendMessage']
+ AgentCallerConversationService['sendMessage']
> = () => Promise.reject(new Error('The step has not posted yet'));
const { status, stepResult } = await runWorkflowActionStep({
@@ -267,8 +267,8 @@ describe('Send chat message workflow step', () => {
});
postAgain = () =>
- getAppProviderByClassName<AgentCallerInboxService>(
- 'AgentCallerInboxService',
+ getAppProviderByClassName<AgentCallerConversationService>(
+ 'AgentCallerConversationService',
).sendMessage({
workspaceId: SEED_APPLE_WORKSPACE_ID,
sender,
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index ba024aefdb4..a9c29b20062 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -36,6 +36,7 @@ export { PROPOSE_TOOL_CALL_TOOL_STATUSES } from './constants/propose-tool-call-t
export { PROPOSED_TOOL_CALL_TEMPLATES } from './constants/proposed-tool-call-templates.const';
export { REQUEST_FORM_TOOL_NAME } from './constants/request-form-tool-name.const';
export { ToolCategory } from './constants/tool-category.const';
+export { agentRunSummarySchema } from './schemas/agent-run-summary-schema';
export type { AgentChatSubscriptionEvent } from './types/AgentChatSubscriptionEvent';
export type {
AgentResponseFormatType,
@@ -47,6 +48,8 @@ export type {
AgentResponseFieldType,
AgentResponseSchema,
} from './types/AgentResponseSchema';
+export type { AgentRunSummary } from './types/AgentRunSummary';
+export type { AgentRunToolCallLog } from './types/AgentRunToolCallLog';
export type { AskQuestionAnswer } from './types/AskQuestionAnswer';
export type { AskQuestionItem } from './types/AskQuestionItem';
export type { AskQuestionOption } from './types/AskQuestionOption';
diff --git a/packages/twenty-shared/src/ai/schemas/agent-run-summary-schema.ts b/packages/twenty-shared/src/ai/schemas/agent-run-summary-schema.ts
new file mode 100644
index 00000000000..9c2f92293fb
--- /dev/null
+++ b/packages/twenty-shared/src/ai/schemas/agent-run-summary-schema.ts
@@ -0,0 +1,30 @@
+import { z } from 'zod';
+
+const agentRunToolCallLogSchema = z.object({
+ toolName: z.string(),
+ toolCallId: z.string(),
+ providerExecuted: z.boolean().optional(),
+ input: z.unknown().optional(),
+ output: z.unknown().optional(),
+ errorMessage: z.string().optional(),
+ state: z.enum(['started', 'success', 'error', 'awaiting-approval']),
+});
+
+export const agentRunSummarySchema = z.object({
+ modelId: z.string(),
+ usage: z.object({
+ inputTokens: z.number(),
+ outputTokens: z.number(),
+ reasoningTokens: z.number().optional(),
+ cacheReadTokens: z.number().optional(),
+ cacheCreationTokens: z.number().optional(),
+ totalTokens: z.number(),
+ }),
+ cost: z.object({
+ totalCostInDollars: z.number(),
+ creditsUsedMicro: z.number(),
+ }),
+ nativeWebSearchCallCount: z.number(),
+ toolCalls: z.array(agentRunToolCallLogSchema),
+ durationMs: z.number(),
+});
diff --git a/packages/twenty-shared/src/ai/types/AgentRunSummary.ts b/packages/twenty-shared/src/ai/types/AgentRunSummary.ts
new file mode 100644
index 00000000000..c15f360d0c6
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AgentRunSummary.ts
@@ -0,0 +1,5 @@
+import type z from 'zod';
+
+import { type agentRunSummarySchema } from '@/ai/schemas/agent-run-summary-schema';
+
+export type AgentRunSummary = z.infer<typeof agentRunSummarySchema>;
diff --git a/packages/twenty-shared/src/ai/types/AgentRunToolCallLog.ts b/packages/twenty-shared/src/ai/types/AgentRunToolCallLog.ts
new file mode 100644
index 00000000000..f4fb43c242a
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AgentRunToolCallLog.ts
@@ -0,0 +1,3 @@
+import { type AgentRunSummary } from '@/ai/types/AgentRunSummary';
+
+export type AgentRunToolCallLog = AgentRunSummary['toolCalls'][number];
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index 40af1c37535..167be7edda1 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -152,7 +152,6 @@ export type {
WorkflowRunStepLog,
WorkflowRunStepLogs,
AiAgentStepLogDetails,
- AiToolCallLog,
} from './types/WorkflowRunStepLog';
export type { WorkflowStepWait } from './types/WorkflowStepWait';
export { canObjectBeManagedByAutomation } from './utils/canObjectBeManagedByAutomation';
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
index f414aad193f..3ea2cd5025f 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
@@ -1,39 +1,15 @@
import { z } from 'zod';
+import { agentRunSummarySchema } from '@/ai/schemas/agent-run-summary-schema';
+
const stepLogEntrySchema = z.object({
timestamp: z.string(),
level: z.enum(['debug', 'info', 'warn', 'error']),
message: z.string(),
});
-const aiToolCallLogSchema = z.object({
- toolName: z.string(),
- toolCallId: z.string(),
- providerExecuted: z.boolean().optional(),
- input: z.unknown().optional(),
- output: z.unknown().optional(),
- errorMessage: z.string().optional(),
- state: z.enum(['started', 'success', 'error', 'awaiting-approval']),
-});
-
-const aiAgentStepLogDetailsSchema = z.object({
+const aiAgentStepLogDetailsSchema = agentRunSummarySchema.extend({
type: z.literal('AI_AGENT'),
- modelId: z.string(),
- usage: z.object({
- inputTokens: z.number(),
- outputTokens: z.number(),
- reasoningTokens: z.number().optional(),
- cacheReadTokens: z.number().optional(),
- cacheCreationTokens: z.number().optional(),
- totalTokens: z.number(),
- }),
- cost: z.object({
- totalCostInDollars: z.number(),
- creditsUsedMicro: z.number(),
- }),
- nativeWebSearchCallCount: z.number(),
- toolCalls: z.array(aiToolCallLogSchema),
- durationMs: z.number(),
// the conversation the agent ran in
threadId: z.string().optional(),
});
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowRunStepLog.ts b/packages/twenty-shared/src/workflow/types/WorkflowRunStepLog.ts
index 371509e8463..834dfe3fe0b 100644
--- a/packages/twenty-shared/src/workflow/types/WorkflowRunStepLog.ts
+++ b/packages/twenty-shared/src/workflow/types/WorkflowRunStepLog.ts
@@ -9,5 +9,3 @@ export type AiAgentStepLogDetails = Extract<
WorkflowRunStepLog['details'],
{ type: 'AI_AGENT' }
>;
-
-export type AiToolCallLog = AiAgentStepLogDetails['toolCalls'][number];