The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Send workflow chat messages through an engine inbox API (#27405)
Félix Malfait8212c4605054
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.tsindex 1c194b273dd..9fa53822c89 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,6 +16,7 @@ import { AgentMessagePartResolver } from 'src/engine/metadata-modules/ai/ai-agenimport { 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';@@ -25,11 +26,11 @@ import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-executiimport { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';import { RunAgentAttachmentService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service';+import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';import { AiAgentRoleModule } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.module';import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';-import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';import { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-billing.module';import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';@@ -62,6 +63,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac],providers: [AgentAsyncExecutorService,+ AgentCallerInboxService,AgentActorContextService,AgentCallerConversationService,AgentRunCallerHandlerRegistryService,@@ -82,6 +84,7 @@ 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.tsnew file mode 100644index 00000000000..393ac2ecebf--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-message-thread-lock-max-retries.const.ts@@ -0,0 +1,2 @@+// 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/pausing-tools/types/proposed-tool-call-answer.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type.tsnew file mode 100644index 00000000000..a3b9b5fe461--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type.ts@@ -0,0 +1,11 @@+// The member's decision on a proposed call, read from its tool output once it ran or was refused+export type ProposedToolCallAnswer = {+ outcome: 'executed' | 'rejected' | 'failed' | 'conflict';+ // the member may approve an alternative, such as saving an email as a draft instead of sending it+ toolName: string;+ arguments: Record<string, unknown>;+ // a conflict carries the record's latest values+ output: unknown;+ feedback: string | null;+ error: string | null;+};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-missing-required-tool-arguments.util.spec.tssimilarity index 87%rename from packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-missing-required-tool-arguments.util.spec.tsindex f500c5cd25a..7f5e33b4965 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/find-missing-required-tool-arguments.util.spec.ts@@ -1,4 +1,4 @@-import { findMissingRequiredToolArguments } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util';+import { findMissingRequiredToolArguments } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util';const CALENDAR_EVENT_SCHEMA = {type: 'object',diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/read-proposed-tool-call-answer.util.spec.tssimilarity index 74%rename from packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/read-proposed-tool-call-answer.util.spec.tsindex da14e8d654d..6b308df31eb 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/read-proposed-tool-call-answer.util.spec.ts@@ -1,4 +1,4 @@-import { buildSendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util';+import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';const EMAIL_ARGUMENTS = {recipients: { to: '[email protected]' },@@ -6,24 +6,20 @@ const EMAIL_ARGUMENTS = {body: '<p>Recap</p>',};-const buildResult = (result: Record<string, unknown>) =>- buildSendChatMessageAnswerResult({- threadId: 'thread-id',- toolResult: { success: true, result },- });+const readAnswer = (result: Record<string, unknown>) =>+ readProposedToolCallAnswer({ success: true, result });-describe('buildSendChatMessageAnswerResult', () => {+describe('readProposedToolCallAnswer', () => {it.each(['send_email', 'draft_email'])('reports %s as executed once approved',(toolName) => {expect(- buildResult({+ readAnswer({status: 'approved',proposal: { toolName, arguments: EMAIL_ARGUMENTS },output: { messageId: 'message-id' },}),).toEqual({- threadId: 'thread-id',outcome: 'executed',toolName,arguments: EMAIL_ARGUMENTS,@@ -36,7 +32,7 @@ describe('buildSendChatMessageAnswerResult', () => {it('keeps the error of an approved call that failed', () => {expect(- buildResult({+ readAnswer({status: 'failed',proposal: { toolName: 'send_email', arguments: EMAIL_ARGUMENTS },error: 'No connected account',@@ -51,7 +47,7 @@ describe('buildSendChatMessageAnswerResult', () => {it('keeps the latest values of a record that changed before approval', () => {expect(- buildResult({+ readAnswer({status: 'conflict',proposal: { toolName: 'update_one_company', arguments: {} },output: { latestValues: { employees: 12 } },@@ -64,7 +60,7 @@ describe('buildSendChatMessageAnswerResult', () => {it('keeps the feedback of a rejected call', () => {expect(- buildResult({+ readAnswer({status: 'rejected',proposal: { toolName: 'send_email', arguments: EMAIL_ARGUMENTS },feedback: 'Not yet',@@ -77,14 +73,14 @@ describe('buildSendChatMessageAnswerResult', () => {});it.each(['pending', 'running', 'skipped', undefined])(- 'refuses to report a %s call',+ 'reads no answer from a %s call',(status) => {- expect(() =>- buildResult({+ expect(+ readAnswer({status,proposal: { toolName: 'send_email', arguments: EMAIL_ARGUMENTS },}),- ).toThrow('The answer to the action could not be read');+ ).toBeUndefined();},);});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util.tssimilarity index 100%rename from packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util.tsdiff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util.tsnew file mode 100644index 00000000000..166e083fc75--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util.ts@@ -0,0 +1,41 @@+import { isString } from '@sniptt/guards';+import { isDefined, isPlainObject } from 'twenty-shared/utils';++import { type ProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type';++const OUTCOME_BY_STATUS: ReadonlyMap<+ string,+ ProposedToolCallAnswer['outcome']+> = new Map([+ ['approved', 'executed'],+ ['rejected', 'rejected'],+ ['failed', 'failed'],+ ['conflict', 'conflict'],+]);++// undefined while the call waits on the member, or once it closed without an answer+export const readProposedToolCallAnswer = (+ toolOutput: unknown,+): ProposedToolCallAnswer | undefined => {+ const result =+ isPlainObject(toolOutput) && isPlainObject(toolOutput.result)+ ? toolOutput.result+ : {};+ const proposal = isPlainObject(result.proposal) ? result.proposal : {};+ const outcome = isString(result.status)+ ? OUTCOME_BY_STATUS.get(result.status)+ : undefined;++ if (!isDefined(outcome) || !isString(proposal.toolName)) {+ return undefined;+ }++ return {+ outcome,+ toolName: proposal.toolName,+ arguments: isPlainObject(proposal.arguments) ? proposal.arguments : {},+ output: result.output ?? null,+ feedback: isString(result.feedback) ? result.feedback : null,+ error: isString(result.error) ? result.error : null,+ };+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util.tsindex a1ce6d2b8df..a5356cfa9c6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util.ts@@ -1,7 +1,8 @@import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-outcome.type';export const buildWaitOutcomeToolOutput = (- outcome: PendingWakeUpOutcome,+ // a run dropped while it waits cancels its wait+ outcome: PendingWakeUpOutcome | { type: 'CANCELLED' },): Record<string, unknown> => {switch (outcome.type) {case 'TIME_ELAPSED':@@ -30,5 +31,12 @@ export const buildWaitOutcomeToolOutput = ('Stopped waiting: the event did not happen before the timeout.',result: { status: 'expired' },};+ case 'CANCELLED':+ return {+ success: true,+ message:+ 'Stopped waiting: the run was stopped before the wait was over.',+ result: { status: 'cancelled' },+ };}};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.tsindex 5ca2533ae7e..9638ec52cac 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@@ -96,7 +96,7 @@ const buildService = (execution = buildExecution()) => {agentRunConversationService as never,conversationReaderService as never,{- findOne: jest.fn().mockResolvedValue(null),+ assertConversationNotSuspended: jest.fn().mockResolvedValue(undefined),closeAwaitedCalls: jest.fn().mockResolvedValue(undefined),} as never,{} as never,@@ -167,7 +167,7 @@ describe('AgentRunnerService', () => {);});- it('neither reads nor locks a conversation it just created', async () => {+ it('locks a conversation it just created without reading it', async () => {const {service,agentRunConversationService,@@ -180,7 +180,9 @@ describe('AgentRunnerService', () => {conversation: { threadId: 'thread-id', isCreated: true },});- expect(agentRunConversationService.withThreadLock).not.toHaveBeenCalled();+ expect(agentRunConversationService.withThreadLock).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'thread-id' }),+ );expect(conversationReaderService.loadMessages).not.toHaveBeenCalled();expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(expect.objectContaining({ priorMessages: [] }),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.tsnew file mode 100644index 00000000000..9b15550e0c4--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service.ts@@ -0,0 +1,206 @@+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-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.tsindex a4b9de96b2b..2f576b85389 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@@ -10,11 +10,13 @@ import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { CacheLockException } from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.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,@@ -25,6 +27,10 @@ import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';+import {+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';@Injectable()export class AgentRunConversationService {@@ -43,10 +49,13 @@ export class AgentRunConversationService {workspaceId,threadId,work,+ maxRetries = AGENT_RUN_THREAD_LOCK_TTL_MS /+ AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,}: {workspaceId: string;threadId: string;work: () => Promise<TResult>;+ maxRetries?: number;}): Promise<TResult> {return this.cacheLockService.withLock(work,@@ -54,13 +63,47 @@ export class AgentRunConversationService {{ttl: AGENT_RUN_THREAD_LOCK_TTL_MS,ms: AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,- maxRetries:- AGENT_RUN_THREAD_LOCK_TTL_MS /- AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,+ maxRetries,},);}+ // A member's message waits a moment for a run going on in the conversation, then is refused like+ // one sent while the run waits+ async withThreadLockForMessage<TResult>({+ workspaceId,+ threadId,+ work,+ }: {+ workspaceId: string;+ threadId: string;+ work: () => Promise<TResult>;+ }): Promise<TResult> {+ let isLocked = false;++ try {+ return await this.withThreadLock({+ workspaceId,+ threadId,+ maxRetries: AGENT_MESSAGE_THREAD_LOCK_MAX_RETRIES,+ work: () => {+ isLocked = true;++ return work();+ },+ });+ } catch (error) {+ if (!isLocked && error instanceof CacheLockException) {+ throw new AiException(+ 'A run is going on in the conversation; send the next message once it has finished',+ AiExceptionCode.THREAD_AWAITING_ANSWER,+ );+ }++ throw error;+ }+ }+// The turn is written before the agent runs, so a run in progress or one that fails is on recordasync openTurn({workspaceId,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.tsindex b36656102d8..0fa748d2b5b 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@@ -11,13 +11,16 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/serviimport { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';import { CONTINUE_AGENT_RUN_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/continue-agent-run-job-name.constant';import { AgentRunSuspensionEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-run-suspension.entity';+import { AGENT_WAIT_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-tool-names.constant';import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';+import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';+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';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 AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.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';@@ -87,6 +90,24 @@ export class AgentRunSuspensionService {} as QueryDeepPartialEntity<AgentRunSuspensionEntity>);}+ // a new message must not slip in while a run waits in the conversation: the run would read it on continuing+ async assertConversationNotSuspended({+ workspaceId,+ threadId,+ }: {+ workspaceId: string;+ threadId: string;+ }): Promise<void> {+ const suspension = await this.findOne({ workspaceId, where: { threadId } });++ if (isDefined(suspension)) {+ throw new AiException(+ 'The conversation is waiting on an earlier run; send the next message once it has finished',+ AiExceptionCode.THREAD_AWAITING_ANSWER,+ );+ }+ }+// A call the caller posted itself, such as a workflow step asking for approval: there is no// agent to continue, so the answer goes straight back to the caller. Posting again is a no-opasync awaitCallerCall({@@ -200,7 +221,7 @@ export class AgentRunSuspensionService {return status === 'NOT_READY' ? { status } : { status, suspension };}- // The last answer continues the agent, or is itself the outcome of a call the caller posted+ // The last answer continues the agent, or is itself the outcome of the call the caller proposedasync deliverAnswer({workspaceId,suspension,@@ -216,10 +237,17 @@ export class AgentRunSuspensionService {return;}+ const answer = readProposedToolCallAnswer(toolResult);+await this.settle({workspaceId,suspension,- outcome: { status: 'COMPLETED', result: toolResult },+ outcome: isDefined(answer)+ ? { status: 'ANSWERED', answer }+ : {+ status: 'FAILED',+ error: 'The answer to the proposed call could not be read',+ },});}@@ -232,7 +260,7 @@ export class AgentRunSuspensionService {}: {workspaceId: string;suspension: AgentRunSuspensionEntity;- outcome: Exclude<AgentRunnerOutcome, { status: 'SUSPENDED' }>;+ outcome: AgentRunCallerOutcome;summary?: AgentRunSummary | null;}): Promise<void> {await this.release({ workspaceId, suspension });@@ -301,6 +329,8 @@ export class AgentRunSuspensionService {workspaceId: string;threadId: string;}): Promise<void> {+ await this.closeWaitCalls({ workspaceId, threadId });+const thread = await this.threadRepository.findOne(workspaceId, {where: {id: threadId,@@ -355,4 +385,27 @@ 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-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.tsindex ea508cc4e90..7b6c64786b8 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@@ -162,17 +162,13 @@ export class AgentRunnerService {// the suspension a continued run resumes fromsuspension: AgentRunSuspensionEntity | null;}): Promise<AgentRunnerResult> {- const { workspaceId, conversation } = input;- const work = () => this.runTurn({ input, suspension });-- // a continued conversation is read before the run, so two runs on it must not interleave- return conversation.isCreated- ? work()- : this.agentRunConversationService.withThreadLock({- workspaceId,- threadId: conversation.threadId,- work,- });+ // 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,+ work: () => this.runTurn({ input, suspension }),+ });}private async runTurn({@@ -194,7 +190,10 @@ export class AgentRunnerService {} = input;if (!isCreated && !isDefined(suspension)) {- await this.assertConversationNotSuspended({ workspaceId, threadId });+ await this.agentRunSuspensionService.assertConversationNotSuspended({+ workspaceId,+ threadId,+ });}const priorMessages = isCreated@@ -284,27 +283,6 @@ export class AgentRunnerService {};}- // a new message must not slip in while a run waits in the conversation: the run would read it on continuing- private async assertConversationNotSuspended({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): Promise<void> {- const suspension = await this.agentRunSuspensionService.findOne({- workspaceId,- where: { threadId },- });-- if (isDefined(suspension)) {- throw new AiException(- 'The conversation is waiting on an earlier run; send the next message once it has finished',- AiExceptionCode.THREAD_AWAITING_ANSWER,- );- }- }-private async settleTurn({workspaceId,threadId,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.tsnew file mode 100644index 00000000000..a064540da42--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-caller-inbox-delivery.type.ts@@ -0,0 +1,10 @@+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.tsindex ed98158192c..704e5da4668 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@@ -2,10 +2,10 @@ 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 AgentRunCallerInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.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 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';-import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';export type AgentRunCallerHandler<TCaller extends AgentRunCaller = AgentRunCaller,@@ -28,7 +28,7 @@ export type AgentRunCallerHandler<onOutcome?(input: AgentRunCallerInput<TCaller> & {threadId: string;- outcome: Exclude<AgentRunnerOutcome, { status: 'SUSPENDED' }>;+ outcome: AgentRunCallerOutcome;// null for a call the caller posted itself, which no agent ransummary: AgentRunSummary | null;},diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type.tsnew file mode 100644index 00000000000..93cc1b99a9e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type.ts@@ -0,0 +1,7 @@+import { type ProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-answer.type';+import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';++// what a caller gets once it stops waiting: how its run ended, or the answer to a call it posted itself+export type AgentRunCallerOutcome =+ | Exclude<AgentRunnerOutcome, { status: 'SUSPENDED' }>+ | { status: 'ANSWERED'; answer: ProposedToolCallAnswer };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.tsindex 17254ee8b71..0236276060d 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@@ -1,5 +1,6 @@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 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';@@ -17,4 +18,6 @@ export type AgentRunExecutionContext = {additionalRoleRestrictionIds?: string[];// who the continued conversation is read for, so turns others acted on read as theirsconversationActor?: AgentConversationActor;+ // the application the caller is bound to, whose tools are the only ones a call it posts can propose+ application?: FlatApplication;};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.tsindex 5e7f75d79ad..cfb4ddb384a 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@@ -152,6 +152,10 @@ describe('AgentChatStreamingService claim & reap', () => {findLatestTurn: jest.fn().mockResolvedValue(null),markRunning: jest.fn().mockResolvedValue(true),} as never,+ {+ assertConversationNotSuspended: jest.fn().mockResolvedValue(undefined),+ } as never,+ { withThreadLockForMessage: jest.fn(({ work }) => work()) } as never,);return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.tsindex f2b9785bb87..ef5aa348dfb 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.opening-turn.spec.ts@@ -68,6 +68,8 @@ describe('AgentChatStreamingService.startOpeningTurn', () => {{} as never,{} as never,{} as never,+ {} as never,+ {} as never,);return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.tsindex e21ea7c0ce2..aa035d6d723 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts@@ -110,6 +110,8 @@ describe('AgentChatStreamingService.retryLastFailedTurn', () => {cancel: jest.fn().mockResolvedValue(false),} as never,turnRecorderService as never,+ {} as never,+ {} as never,);return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.tsindex 1b6757c256c..428c44236c6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts@@ -63,6 +63,8 @@ const build = () => {hasPendingForThread: jest.fn().mockResolvedValue(false),} as never,{} as never,+ {} as never,+ {} as never,);return { service, threads, queue, chat, actors, heartbeat };};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.tsindex f47e07b72a4..7660036e040 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@@ -31,6 +31,8 @@ import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';import { AgentMessageStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-status.enum';+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 { isToolOutputAwaitedByCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util';import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util';import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';@@ -93,6 +95,8 @@ export class AgentChatStreamingService {@InjectAgentHistoryRepository('agentMessagePart')private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,private readonly turnRecorderService: AgentTurnRecorderService,+ private readonly agentRunSuspensionService: AgentRunSuspensionService,+ private readonly agentRunConversationService: AgentRunConversationService,) {}async tryClaimStream({@@ -120,7 +124,17 @@ export class AgentChatStreamingService {return true;}- async streamAgentChat({+ // a message that lands while a run goes on in the conversation would be read by that run once it+ // goes on after a wait, so it is let in only between runs+ streamAgentChat(options: StreamAgentChatOptions) {+ return this.agentRunConversationService.withThreadLockForMessage({+ workspaceId: options.workspace.id,+ threadId: options.thread.id,+ work: () => this.startOrQueueMessage(options),+ });+ }++ private async startOrQueueMessage({thread,userWorkspaceId,workspaceMemberId,@@ -628,17 +642,26 @@ export class AgentChatStreamingService {}): Promise<void> {const messageId = thread.pendingQuestionMessageId;- if (!isDefined(messageId)) {- return;- }-- if (await this.isAwaitingCaller({ messageId, workspaceId })) {+ if (+ isDefined(messageId) &&+ (await this.isAwaitingCaller({ messageId, workspaceId }))+ ) {throw new AiException('This conversation is waiting on an answer to the run that asked',AiExceptionCode.THREAD_AWAITING_CALLER_INPUT,);}+ // a run waiting on an event or a duration asks nothing, yet reads the conversation when it goes on+ await this.agentRunSuspensionService.assertConversationNotSuspended({+ workspaceId,+ threadId: thread.id,+ });++ if (!isDefined(messageId)) {+ return;+ }+await this.agentChatService.closePendingToolCalls({threadId: thread.id,messageId,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.tsindex 5fb877a6547..1254bbd7443 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts@@ -70,6 +70,7 @@ describe('isUserFacingWorkflowExecutorError', () => {it.each([AiExceptionCode.API_KEY_NOT_CONFIGURED,+ AiExceptionCode.INVALID_AGENT_INPUT,AiExceptionCode.EVALUATION_MODEL_NOT_FOUND,AiExceptionCode.EVALUATION_QUESTION_UNSUPPORTED,AiExceptionCode.INVALID_EVALUATION_REQUEST,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.tsindex b5f8bc67a4d..86d4b8d549c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts@@ -20,9 +20,11 @@ const USER_FACING_STEP_EXECUTOR_EXCEPTION_CODES = [];// Author misconfigurations: no retry produces a model, and reporting them as system errors buries real ones.-// API_KEY_NOT_CONFIGURED is what an instance with no provider raises via getDefaultModelForTier.+// API_KEY_NOT_CONFIGURED is what an instance with no provider raises via getDefaultModelForTier, and+// INVALID_AGENT_INPUT what a malformed agent or inbox input raises, such as a call that cannot be proposed.const USER_FACING_AI_EXCEPTION_CODES = [AiExceptionCode.API_KEY_NOT_CONFIGURED,+ AiExceptionCode.INVALID_AGENT_INPUT,AiExceptionCode.EVALUATION_MODEL_NOT_FOUND,AiExceptionCode.EVALUATION_QUESTION_UNSUPPORTED,AiExceptionCode.INVALID_EVALUATION_REQUEST,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.tsindex 739404eb6b5..e110da9ca22 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@@ -19,6 +19,7 @@ export const buildWorkflowAgentRunExecutionContext = (rolePermissionConfig: executionContext.rolePermissionConfig,...(isDefined(executionContext.application)? {+ application: executionContext.application,additionalRoleRestrictionIds: getRoleIdsFromRolePermissionConfig(executionContext.rolePermissionConfig,),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.tsindex ed9428beef7..edab6dc0210 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,12 +1,9 @@import { WorkflowActionType } from 'twenty-shared/workflow';-import { type ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';import { type WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';-import { type AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';-import { type AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';+import { type AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.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 { type WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';import { createMockIteratorStep } from 'src/modules/workflow/workflow-executor/utils/create-mock-workflow-steps.util';import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';@@ -49,7 +46,10 @@ describe('SendChatMessageWorkflowAction', () => {beforeEach(() => {jest.clearAllMocks();- sendMessage.mockResolvedValue({ threadId: 'thread-id' });+ sendMessage.mockResolvedValue({+ status: 'DELIVERED',+ threadId: 'thread-id',+ });findWorkflowRun.mockResolvedValue({id: WORKFLOW_RUN_ID,coreWorkflowId: WORKFLOW_ID,@@ -60,7 +60,7 @@ describe('SendChatMessageWorkflowAction', () => {});action = new SendChatMessageWorkflowAction(- { sendMessage } as unknown as AgentInboxService,+ { sendMessage } as unknown as AgentCallerInboxService,new WorkflowRunInboxSenderWorkspaceService({executeInWorkspaceContext: jest.fn((callback) => callback()),@@ -70,9 +70,6 @@ describe('SendChatMessageWorkflowAction', () => {} as unknown as WorkspaceOrmManager,{ findCoreWorkflowById } as unknown as WorkflowCoreSyncService,),- {} as WorkflowExecutionContextService,- {} as AgentRunSuspensionService,- {} as ToolRegistryService,);});@@ -91,13 +88,14 @@ describe('SendChatMessageWorkflowAction', () => {workflowId: WORKFLOW_ID,workflowName: 'New deals',},- input: {+ message: {workspaceMemberId: WORKSPACE_MEMBER_ID,threadKey: WORKFLOW_RUN_ID,idempotencyKey: 'step-1',title: 'New deal: Acme',text: '**Acme** just signed.',},+ awaitedToolCall: undefined,});});@@ -126,7 +124,7 @@ describe('SendChatMessageWorkflowAction', () => {await runIteration(1);const idempotencyKeys = sendMessage.mock.calls.map(- ([{ input: sentInput }]) => sentInput.idempotencyKey,+ ([{ message }]) => message.idempotencyKey,);expect(idempotencyKeys).toEqual([@@ -144,7 +142,7 @@ describe('SendChatMessageWorkflowAction', () => {conversation: { scope: 'STEP' },});- expect(sendMessage.mock.calls[0][0].input).toMatchObject({+ expect(sendMessage.mock.calls[0][0].message).toMatchObject({threadKey: `${WORKFLOW_RUN_ID}:step-1`,idempotencyKey: 'step-1',});@@ -158,7 +156,7 @@ describe('SendChatMessageWorkflowAction', () => {conversation: { scope: 'KEY', key: 'deal-{{trigger.name}}' },});- expect(sendMessage.mock.calls[0][0].input).toMatchObject({+ expect(sendMessage.mock.calls[0][0].message).toMatchObject({threadKey: 'key:deal-Acme',idempotencyKey: `${WORKFLOW_RUN_ID}:step-1`,});@@ -187,7 +185,7 @@ describe('SendChatMessageWorkflowAction', () => {expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({- input: expect.objectContaining({ title: 'Send to Inbox' }),+ message: expect.objectContaining({ title: 'Send to Inbox' }),}),);});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.tsindex 96f415a809f..5dc6aec8db6 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts@@ -1,20 +1,11 @@import { Module } from '@nestjs/common';-import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';-import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';-import { WorkflowExecutionContextModule } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.module';import { WorkflowRunInboxSenderModule } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module';import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';@Module({- imports: [- AgentChatThreadModule,- AiAgentExecutionModule,- WorkflowExecutionContextModule,- WorkflowRunInboxSenderModule,- ToolProviderModule,- ],+ imports: [AiAgentExecutionModule, WorkflowRunInboxSenderModule],providers: [SendChatMessageWorkflowAction],exports: [SendChatMessageWorkflowAction],})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.tsindex c49a90208eb..69be3abb0b5 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@@ -1,51 +1,30 @@import { Injectable } from '@nestjs/common';import { isNonEmptyString } from '@sniptt/guards';-import { PROPOSE_TOOL_CALL_TOOL_NAME } from 'twenty-shared/ai';-import {- isDefined,- isPlainObject,- isValidUuid,- resolveInput,-} from 'twenty-shared/utils';+import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';-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 { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-status.util';-import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';-import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';-import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';-import { buildProposeToolCallPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';-import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';+import { AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.service';import {WorkflowStepExecutorException,WorkflowStepExecutorExceptionCode,} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';-import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';-import { buildWorkflowStepCaller } from 'src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util';import { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';+import { buildWorkflowStepCaller } from 'src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';import { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util';import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';-import { findMissingRequiredToolArguments } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util';-import { buildSendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util';import { type WorkflowSendChatMessageActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type';-const MAX_SEND_ATTEMPTS = 10;-@Injectable()export class SendChatMessageWorkflowAction implements WorkflowAction {constructor(- private readonly agentInboxService: AgentInboxService,+ private readonly agentCallerInboxService: AgentCallerInboxService,private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,- private readonly workflowExecutionContextService: WorkflowExecutionContextService,- private readonly agentRunSuspensionService: AgentRunSuspensionService,- private readonly toolRegistryService: ToolRegistryService,) {}async execute({@@ -96,158 +75,45 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {workflowRunId: runInfo.workflowRunId,stepExecutionKey: executionKey,});- // a conversation shared by key holds every run's messages, so each run keys its own- const messageKey =- conversation?.scope === 'KEY'- ? `${runInfo.workflowRunId}:${executionKey}`- : executionKey;- let awaitingToolCall:- | ReturnType<SendChatMessageWorkflowAction['resolveAwaitingToolCall']>- | undefined;- const buildAwaitingToolCall = isDefined(toolCall)- ? () => {- awaitingToolCall ??= this.resolveAwaitingToolCall({- toolCall,- summary: text,- runInfo,- });-- return awaitingToolCall;- }- : undefined;- const sendMessage = (idempotencyKey: string) =>- this.agentInboxService.sendMessage({- workspaceId: runInfo.workspaceId,- sender,- input: {- workspaceMemberId,- threadKey,- idempotencyKey,- title: isNonEmptyString(title) ? title : step.name,- text,- },- buildAwaitingToolCall,- });- // a step run again finds the call it posted before: it keeps waiting on a pending one, reuses- // an answered one so nothing runs twice, and asks again once an earlier call closed unanswered- for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt++) {- const { threadId, isDismissed, awaitedToolOutput } = await sendMessage(- attempt === 0 ? messageKey : `${messageKey}:${attempt}`,- );-- if (!isDefined(buildAwaitingToolCall)) {- return { result: { threadId } };- }+ const delivery = await this.agentCallerInboxService.sendMessage({+ workspaceId: runInfo.workspaceId,+ sender,+ message: {+ workspaceMemberId,+ threadKey,+ // a conversation shared by key holds every run's messages, so each run keys its own+ idempotencyKey:+ conversation?.scope === 'KEY'+ ? `${runInfo.workflowRunId}:${executionKey}`+ : executionKey,+ title: isNonEmptyString(title) ? title : step.name,+ text,+ },+ awaitedToolCall: isDefined(toolCall)+ ? {+ ...toolCall,+ caller: buildWorkflowStepCaller({+ workflowRunId: runInfo.workflowRunId,+ stepId: currentStepId,+ }),+ }+ : undefined,+ });- if (isDismissed) {+ switch (delivery.status) {+ case 'DELIVERED':+ return { result: { threadId: delivery.threadId } };+ case 'DISMISSED':throw new WorkflowStepExecutorException('The recipient deleted this conversation, so the action cannot be approved',WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,);- }-- const status = readToolCallStatus(awaitedToolOutput);-- if (status === 'skipped') {- continue;- }-- if (status === 'pending' || status === 'running') {- // the step waits for the member, and the engine hands it their answer- await this.agentRunSuspensionService.awaitCallerCall({- workspaceId: runInfo.workspaceId,- threadId,- caller: buildWorkflowStepCaller({- workflowRunId: runInfo.workflowRunId,- stepId: currentStepId,- }),- });-+ // the step waits for the member, and the engine hands it their answer+ case 'AWAITING':return { wait: { type: 'CALLBACK' } };- }-- return {- result: buildSendChatMessageAnswerResult({- threadId,- toolResult: isPlainObject(awaitedToolOutput) ? awaitedToolOutput : {},- }),- };+ case 'ANSWERED':+ return { result: { threadId: delivery.threadId, ...delivery.answer } };}-- throw new WorkflowStepExecutorException(- `The action was asked ${MAX_SEND_ATTEMPTS} times without an answer`,- WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,- );- }-- // resolved with the run's permissions, the ones the step itself acts with- private async resolveAwaitingToolCall({- toolCall,- summary,- runInfo,- }: {- toolCall: NonNullable<WorkflowSendChatMessageActionInput['toolCall']>;- summary: string;- runInfo: WorkflowActionInput['runInfo'];- }) {- const { authContext, rolePermissionConfig, application } =- await this.workflowExecutionContextService.getExecutionContext(runInfo);-- const toolContext = {- workspaceId: runInfo.workspaceId,- roleId: getRoleIdsFromRolePermissionConfig(rolePermissionConfig)[0] ?? '',- rolePermissionConfig,- authContext,- application: application ?? undefined,- } satisfies ToolContext;-- const catalog = await this.toolRegistryService.getCatalog(toolContext);- const inputSchemas = await this.toolRegistryService.resolveSchemas({- toolNames: [toolCall.toolName],- context: toolContext,- precomputedCatalog: catalog,- });- const missingArgumentNames = findMissingRequiredToolArguments({- inputSchema: inputSchemas.get(toolCall.toolName),- toolArguments: toolCall.arguments,- });-- if (missingArgumentNames.length > 0) {- throw new WorkflowStepExecutorException(- `The action is missing required arguments: ${missingArgumentNames.join(', ')}`,- WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,- );- }-- const input = {- toolName: toolCall.toolName,- arguments: toolCall.arguments,- summary,- };-- const resolution = await resolveProposedToolCall({- input,- findTool: async (toolName) =>- catalog.find((catalogEntry) => catalogEntry.name === toolName),- executeTool: ({ toolName, args }) =>- this.toolRegistryService.resolveAndExecute(toolName, args, toolContext),- });-- if ('error' in resolution) {- throw new WorkflowStepExecutorException(- `The tool call cannot be proposed: ${resolution.error}`,- WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,- );- }-- return {- toolName: PROPOSE_TOOL_CALL_TOOL_NAME,- input,- output: {- ...buildProposeToolCallPendingOutput(resolution.proposal),- awaitedByCaller: true,- },- };}}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.tsdeleted file mode 100644index 27ebd521cb5..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.ts+++ /dev/null@@ -1,5 +0,0 @@-export type SendChatMessageAnswerOutcome =- | 'executed'- | 'rejected'- | 'failed'- | 'conflict';diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.tsdeleted file mode 100644index e499336a404..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.ts+++ /dev/null@@ -1,11 +0,0 @@-import { type SendChatMessageAnswerOutcome } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type';--export type SendChatMessageAnswerResult = {- threadId: string;- outcome: SendChatMessageAnswerOutcome;- toolName: string;- arguments: Record<string, unknown>;- output: unknown;- feedback: string | null;- error: string | null;-};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.tsdeleted file mode 100644index 00ba186b75c..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.ts+++ /dev/null@@ -1,50 +0,0 @@-import { isString } from '@sniptt/guards';-import { isDefined, isPlainObject } from 'twenty-shared/utils';--import {- WorkflowStepExecutorException,- WorkflowStepExecutorExceptionCode,-} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';-import { type SendChatMessageAnswerOutcome } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type';-import { type SendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type';--const OUTCOME_BY_STATUS: ReadonlyMap<string, SendChatMessageAnswerOutcome> =- new Map([- ['approved', 'executed'],- ['rejected', 'rejected'],- ['failed', 'failed'],- ['conflict', 'conflict'],- ]);--export const buildSendChatMessageAnswerResult = ({- threadId,- toolResult,-}: {- threadId: string;- toolResult: Record<string, unknown>;-}): SendChatMessageAnswerResult => {- const result = isPlainObject(toolResult.result) ? toolResult.result : {};- const proposal = isPlainObject(result.proposal) ? result.proposal : {};- const outcome = isString(result.status)- ? OUTCOME_BY_STATUS.get(result.status)- : undefined;-- if (!isDefined(outcome) || !isString(proposal.toolName)) {- throw new WorkflowStepExecutorException(- 'The answer to the action could not be read',- WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,- );- }-- return {- threadId,- outcome,- // the member may approve an alternative, such as saving an email as a draft instead of sending it- toolName: proposal.toolName,- arguments: isPlainObject(proposal.arguments) ? proposal.arguments : {},- // a conflict carries the record's latest values- output: result.output ?? null,- feedback: isString(result.feedback) ? result.feedback : null,- error: isString(result.error) ? result.error : null,- };-};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.tsindex 727d54b9fd9..740f4a2a9d9 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@@ -17,8 +17,6 @@ import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';import { buildWorkflowAgentRunExecutionContext } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util';-import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';-import { buildSendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util';import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';import { type RunWorkflowJobData } from 'src/modules/workflow/workflow-runner/types/run-workflow-job-data.type';import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';@@ -118,21 +116,19 @@ export class WorkflowAgentRunCallerHandlerWorkspaceService});}+ // the member's answer already ran the call, so a Send Message step only reports it+ const actionOutput =+ outcome.status === 'FAILED'+ ? { error: outcome.error }+ : {+ result:+ outcome.status === 'ANSWERED'+ ? { threadId, ...outcome.answer }+ : outcome.result,+ };+// the step stays pending until the job claims it, so the run must not stay running without onetry {- const actionOutput =- outcome.status === 'FAILED'- ? { error: outcome.error }- : {- result: await this.buildStepResult({- workspaceId,- workflowRunId,- stepId,- threadId,- result: outcome.result,- }),- };-await this.messageQueueService.add<RunWorkflowJobData>(RUN_WORKFLOW_JOB_NAME,{@@ -153,34 +149,4 @@ export class WorkflowAgentRunCallerHandlerWorkspaceServicethrow error;}}-- // the member's answer already ran the call, so a Send Message step only reports it- private async buildStepResult({- workspaceId,- workflowRunId,- stepId,- threadId,- result,- }: {- workspaceId: string;- workflowRunId: string;- stepId: string;- threadId: string;- result: object;- }): Promise<object> {- const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({- workflowRunId,- workspaceId,- });- const step = workflowRun?.state?.flow?.steps?.find(- (candidateStep) => candidateStep.id === stepId,- );-- return isDefined(step) && isWorkflowSendChatMessageAction(step)- ? buildSendChatMessageAnswerResult({- threadId,- toolResult: result as Record<string, unknown>,- })- : result;- }}diff --git a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.tsindex d50f4eb989f..1a8ff3def48 100644--- a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts+++ b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts@@ -12,11 +12,13 @@ import { getCoreRepository } from 'test/integration/utils/get-core-repository.utimport { type AgentTrigger } from 'twenty-shared/application';import { type ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';+import { type PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';import { fromWorkspaceEntityToFlat } from 'src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { type AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';import { type AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';+import { type AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';import { type AgentTriggerRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service';import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';@@ -38,12 +40,20 @@ const agentResult = (...overrides,}) as AgentExecutionResult;-const waitingResult = () => {- const resumeAt = new Date(Date.now() + 1_000).toISOString();+const waitingResult = ({+ toolName = 'wait_for_duration',+ wait = {+ type: 'TIME',+ resumeAt: new Date(Date.now() + 1_000).toISOString(),+ },+}: {+ toolName?: string;+ wait?: Record<string, unknown>;+} = {}) => {const output = {success: true,- message: `Waiting until ${resumeAt}.`,- result: { status: 'pending', wait: { type: 'TIME', resumeAt } },+ message: 'Waiting.',+ result: { status: 'pending', wait },};return agentResult({@@ -54,20 +64,18 @@ const waitingResult = () => {{type: 'tool-call',toolCallId: 'wait-1',- toolName: 'wait_for_duration',- input: { durationInMinutes: 1 },+ toolName,+ input: {},},{type: 'tool-result',toolCallId: 'wait-1',- toolName: 'wait_for_duration',- input: { durationInMinutes: 1 },+ toolName,+ input: {},output,},],- toolResults: [- { toolCallId: 'wait-1', toolName: 'wait_for_duration', output },- ],+ toolResults: [{ toolCallId: 'wait-1', toolName, output }],},] as unknown as AgentExecutionResult['steps'],});@@ -99,6 +107,17 @@ const findSuspensions = (callerType: string, agentId: string) =>[callerType, agentId],);+const findWaitCallStatus = async (threadId: string) => {+ const [part] = await global.testDataSource.query(+ `SELECT part."toolOutput"->'result'->>'status' AS status FROM "${schema}"."agentMessagePart" part+ JOIN "${schema}"."agentMessage" message ON message.id = part."messageId"+ WHERE message."threadId" = $1 AND part."toolName" IN ('wait_for_duration', 'wait_for_event')`,+ [threadId],+ );++ return part?.status;+};+const findTurnStatuses = async (threadId: string) =>(await global.testDataSource.query(@@ -166,6 +185,17 @@ describe('agent runs that wait (integration)', () => {const [suspension] = await findSuspensions('AGENT_TRIGGER', agentId);expect(suspension).toMatchObject({ ownerType: 'AGENT_RUN' });++ // the run reads its conversation when it goes on, so a chat message cannot slip in while it waits+ await expect(+ getAppProviderByClassName<AgentChatStreamingService>(+ 'AgentChatStreamingService',+ ).streamAgentChat({+ thread: { id: suspension.threadId, pendingQuestionMessageId: null },+ workspace: { id: workspaceId },+ text: 'Any news?',+ } as Parameters<AgentChatStreamingService['streamAgentChat']>[0]),+ ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_AWAITING_ANSWER });expect(executeAgent.mock.calls[0][0].baseSystemPrompt).toContain('wait_for_duration',);@@ -188,12 +218,68 @@ describe('agent runs that wait (integration)', () => {]);});+ it('refuses a chat message while a run goes on in its conversation', async () => {+ let chatAttempt: Promise<unknown> | undefined;++ jest+ .spyOn(+ getAppProviderByClassName<AgentAsyncExecutorService>(+ 'AgentAsyncExecutorService',+ ),+ 'executeAgent',+ )+ .mockImplementationOnce(async () => {+ const [{ threadId }] = await global.testDataSource.query(+ `SELECT "threadId" FROM "${schema}"."agentTurn" WHERE "agentId" = $1 AND status = 'running'+ ORDER BY "createdAt" DESC LIMIT 1`,+ [agentId],+ );++ // the run is not suspended yet, so only its lock on the conversation keeps the message out+ chatAttempt = getAppProviderByClassName<AgentChatStreamingService>(+ 'AgentChatStreamingService',+ )+ .streamAgentChat({+ thread: { id: threadId, pendingQuestionMessageId: null },+ workspace: { id: workspaceId },+ text: 'Any news?',+ } as Parameters<AgentChatStreamingService['streamAgentChat']>[0])+ .catch((error: unknown) => error);++ await chatAttempt;++ return replyingResult;+ });++ await runTrigger();++ expect(await chatAttempt).toMatchObject({+ code: AiExceptionCode.THREAD_AWAITING_ANSWER,+ });+ });+it('drops a waiting triggered run once its trigger is turned off', async () => {- const executeAgent = mockAgent(waitingResult(), replyingResult);+ // an event that never happens, so only the explicit resolution below wakes the run up+ const executeAgent = mockAgent(+ waitingResult({+ toolName: 'wait_for_event',+ wait: {+ type: 'EVENT',+ eventName: 'opportunity.deleted',+ recordId: randomUUID(),+ },+ }),+ replyingResult,+ );await runTrigger();- expect(await findSuspensions('AGENT_TRIGGER', agentId)).toHaveLength(1);+ const [{ id: suspensionId, threadId }] = await findSuspensions(+ 'AGENT_TRIGGER',+ agentId,+ );++ expect(await findWaitCallStatus(threadId)).toBe('pending');await updateOneAgent({expectToFail: false,@@ -203,11 +289,19 @@ describe('agent runs that wait (integration)', () => {},});- await expectEventually(async () => {- expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);- });+ const [{ id: wakeUpId }] = await global.testDataSource.query(+ `SELECT id FROM core."pendingWakeUp" WHERE "ownerId" = $1`,+ [suspensionId],+ );++ await getAppProviderByClassName<PendingWakeUpResolverService>(+ 'PendingWakeUpResolverService',+ ).resolve({ workspaceId, wakeUpId });++ expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);expect(executeAgent).toHaveBeenCalledTimes(1);+ expect(await findWaitCallStatus(threadId)).toBe('cancelled');await updateOneAgent({expectToFail: false,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.tsindex 03c8f45848a..7587c37b7aa 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,8 +13,9 @@ import { getAppProviderByClassName } from 'test/integration/utils/get-app-providimport { 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 AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';+import { type AgentCallerInboxService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-inbox.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';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';@@ -227,7 +228,15 @@ describe('Send chat message workflow step', () => {expect(await readEmployees()).toBe(30);}, 120000);- it('keeps waiting when the step posts its call again', async () => {+ it('keeps waiting when the step posts its call again, then reads the answer', async () => {+ const toolCall = {+ toolName: 'update_one_company',+ arguments: { id: companyId, employees: 25 },+ };+ let postAgain: () => ReturnType<+ AgentCallerInboxService['sendMessage']+ > = () => Promise.reject(new Error('The step has not posted yet'));+const { status, stepResult } = await runWorkflowActionStep({name: 'Post a headcount check twice',stepType: 'SEND_CHAT_MESSAGE',@@ -235,10 +244,7 @@ describe('Send chat message workflow step', () => {workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,title: 'Headcount check',text: 'Raise the headcount to 25?',- toolCall: {- toolName: 'update_one_company',- arguments: { id: companyId, employees: 25 },- },+ toolCall,},whileRunning: async ({ workflowRunId, stepId }) => {await waitForWorkflowRunStepStatus(workflowRunId, stepId, 'PENDING');@@ -250,18 +256,42 @@ describe('Send chat message workflow step', () => {postedThreadId = threadId;- await expect(- getAppProviderByClassName<AgentRunSuspensionService>(- 'AgentRunSuspensionService',- ).awaitCallerCall({+ // the step posts again as a retry of it would, with the same keys; the sender is read while+ // the run exists, since the run is removed once it completes+ const sender =+ await getAppProviderByClassName<WorkflowRunInboxSenderWorkspaceService>(+ 'WorkflowRunInboxSenderWorkspaceService',+ ).findRunSenderOrThrow({+ workflowRunId,workspaceId: SEED_APPLE_WORKSPACE_ID,- threadId,- caller: {- type: 'WORKFLOW_STEP',- ref: { workflowRunId, stepId },+ });++ postAgain = () =>+ getAppProviderByClassName<AgentCallerInboxService>(+ 'AgentCallerInboxService',+ ).sendMessage({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ sender,+ message: {+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadKey: workflowRunId,+ idempotencyKey: stepId,+ title: 'Headcount check',+ text: 'Raise the headcount to 25?',+ },+ awaitedToolCall: {+ ...toolCall,+ caller: {+ type: 'WORKFLOW_STEP',+ ref: { workflowRunId, stepId },+ },},- }),- ).resolves.toBeUndefined();+ });++ expect(await postAgain()).toEqual({+ status: 'AWAITING',+ threadId,+ });await answerPostedCall({workflowRunId,@@ -274,6 +304,18 @@ describe('Send chat message workflow step', () => {expect(status).toBe('COMPLETED');expect(stepResult).toMatchObject({ outcome: 'executed' });expect(await readEmployees()).toBe(25);+ expect(await postAgain()).toEqual({+ status: 'ANSWERED',+ threadId: postedThreadId,+ answer: {+ outcome: 'executed',+ toolName: 'update_one_company',+ arguments: { id: companyId, employees: 25 },+ output: expect.anything(),+ feedback: null,+ error: null,+ },+ });}, 120000);it('runs nothing when the recipient rejects the action', async () => {