The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Let agent triggers and runAgent calls wait on events and durations (#27403)
Félix Malfait470ffdc680d4
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex c93351063e9..d11b476f704 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4126,6 +4126,7 @@ enum RunAgentMessageRole {type RunAgentResult {error: String+ isWaiting: Boolean!result: JSONsuccess: Boolean!threadId: UUIDdiff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex a0e7f926745..8fd1132a219 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -2993,6 +2993,7 @@ export type RunAgentMessageRole = 'assistant' | 'user'export interface RunAgentResult {error?: Scalars['String']+ isWaiting: Scalars['Boolean']result?: Scalars['JSON']success: Scalars['Boolean']threadId?: Scalars['UUID']@@ -7164,6 +7165,7 @@ export interface RunAgentMessageInput {attachments?: (RunAgentMessageAttachmentIexport interface RunAgentResultGenqlSelection{error?: boolean | number+ isWaiting?: boolean | numberresult?: boolean | numbersuccess?: boolean | numberthreadId?: boolean | numberdiff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex d5980bdb9f6..b24490e1de8 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -11084,6 +11084,9 @@ export default {"error": [1],+ "isWaiting": [+ 4+ ],"result": [285],diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdxindex f1cdd367eb9..78a81ee5bf5 100644--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx@@ -108,7 +108,7 @@ to `defineAgent()`, and pass what you want it to work on as `input`:```ts src/logic-functions/run-enricher.tsimport { runAgent } from 'twenty-sdk/logic-function';-const { result, error, success } = await runAgent({+const { result, error, success, isWaiting } = await runAgent({agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',input: 'Enrich House Ad <recordId>: fill empty fields from its listing URL.',});@@ -121,6 +121,11 @@ Key points:`thread` rather than replaying earlier turns yourself.- The agent runs **synchronously** and can read/update records itself via itsown tools — `runAgent()` resolves once the run completes.+- The agent can also pause until a record changes or some time has passed.+ `runAgent()` then resolves with `success: true`, `isWaiting: true` and+ `result: null`; the agent goes on by itself later, and its reply lands in the+ `threadId` conversation. A call to a `thread` whose agent is still waiting+ fails until it finishes.- Every call is stored with its input and status, plus its reply and usagewhen it completes, so it shows up in the agent's runs. Without a `thread`, a call gets a conversation of itsown: `threadId` names it, and a later call never sees it.@@ -131,9 +136,10 @@ Key points:Without it, `runAgent()` fails with a permission error.- Set a generous `timeoutSeconds` on the logic function — agent runs can takeseveral seconds.-- `success` is `true` and `result` is non-null when the run completes; on- failure `success` is `false`, `result` is `null`, and `error` holds the- reason (for example, when the workspace ran out of AI credits mid-run).+- `success` is `true` and `result` is non-null when the run completes without+ waiting; while it waits, `success` and `isWaiting` are `true` and `result` is+ `null`; on failure `success` is `false`, `result` is `null`, and `error` holds+ the reason (for example, when the workspace ran out of AI credits mid-run).```ts src/roles/default-role.tsimport { defineApplicationRole, SystemPermissionFlag } from 'twenty-sdk/define';diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 09d46474d90..556359f6609 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -6160,6 +6160,7 @@ export enum RunAgentMessageRole {export type RunAgentResult = {__typename?: 'RunAgentResult';error?: Maybe<Scalars['String']['output']>;+ isWaiting: Scalars['Boolean']['output'];result?: Maybe<Scalars['JSON']['output']>;success: Scalars['Boolean']['output'];threadId?: Maybe<Scalars['UUID']['output']>;diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.tsindex 3f5253b1b28..8989e58ca80 100644--- a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts@@ -30,6 +30,7 @@ describe('runAgent', () => {result: { response: 'done' },error: null,success: true,+ isWaiting: false,threadId: null,};@@ -78,6 +79,7 @@ describe('runAgent', () => {result: { response: 'done' },error: null,success: true,+ isWaiting: false,threadId: 'thread-id',},},@@ -112,6 +114,7 @@ describe('runAgent', () => {result: { response: 'done' },error: null,success: true,+ isWaiting: false,};fetchSpy.mockResolvedValue(diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.tsindex fbf86ae8d42..0dbe0a37fae 100644--- a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts@@ -12,6 +12,7 @@ const RUN_AGENT_MUTATION = `resulterrorsuccess+ isWaitingthreadId}}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 8cf6ab1cb24..c5301d06dbc 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@@ -25,6 +25,7 @@ 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 { 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';@@ -33,7 +34,6 @@ import { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-biimport { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';-import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';@@ -44,6 +44,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacAgentHistoryModule,AiBillingModule,AiAgentModule,+ AiAgentRoleModule,ApplicationLookupModule,CacheLockModule,FileUrlModule,@@ -57,7 +58,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacAgentEntity,AgentRunSuspensionEntity,FileEntity,- RoleTargetEntity,WorkspaceEntity,]),],@@ -78,7 +78,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacAgentRunPendingWakeUpHandlerService,ContinueAgentRunJob,RunAgentAttachmentService,- provideWorkspaceScopedRepository(RoleTargetEntity),provideWorkspaceScopedRepository(AgentEntity),provideWorkspaceScopedRepository(AgentRunSuspensionEntity),provideWorkspaceScopedRepository(FileEntity),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.tsnew file mode 100644index 00000000000..766d68e821b--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-max-continuations.const.ts@@ -0,0 +1,2 @@+// 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/dtos/run-agent-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.tsindex 52721db4c9b..d6557399602 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts@@ -16,6 +16,9 @@ export class RunAgentResultDTO implements RunAgentResult {@Field()success: boolean;+ @Field()+ isWaiting: boolean;+@Field(() => UUIDScalarType, { nullable: true })threadId: string | null;}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.tsindex 9cfd839cef9..f645e6cb295 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts@@ -5,7 +5,7 @@ import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-h// not the SDK's hasToolCall, whose stop condition may be async: this is also read synchronously after the run// a pausing call refused or failing when made has no awaiting result, so the model reads its error and goes on-// an offered pausing tool may be resolved by something other than an answer, such as a workflow wait+// an offered pausing tool may be resolved by something other than an answer, such as a waitexport const endsOnPausingToolCall = ({steps,offeredToolNames,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.spec.tsindex e62c5852e4a..2bf9903129d 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.spec.ts@@ -170,22 +170,4 @@ describe('AgentRunConversationService', () => {error: expect.objectContaining({ code: expect.any(String) }),});});-- it('marks the calls it leaves pending as awaited by a caller', async () => {- const { service, conversationWriterService, threadService } =- buildService();-- await service.closeTurn({- ...turn,- title: 'Draft the quote',- agentId: null,- execution,- isAwaitedByCaller: true,- });-- expect(conversationWriterService.insertExecutionReply).toHaveBeenCalledWith(- expect.objectContaining({ isAwaitedByCaller: true }),- );- expect(threadService.recordThreadActivity).not.toHaveBeenCalled();- });});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.tsindex 773d40b3cee..3fcfe8b8a61 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts@@ -35,11 +35,17 @@ const buildService = () => {authContext: { userWorkspaceId: RUN_AS_USER_WORKSPACE_ID },roleId: 'role-id',}),+ buildApplicationAgentContext: jest.fn().mockResolvedValue({+ application: APPLICATION,+ authContext: { type: 'application' },+ agentRoleId: 'agent-role-id',+ }),};const service = new AgentRunService(agentActorContextService as never,agentRunnerService as never,+ {} as never,{ findById: jest.fn().mockResolvedValue(APPLICATION) } as never,{ findOne: jest.fn().mockResolvedValue(AGENT) } as never,);@@ -88,26 +94,38 @@ describe('AgentRunService', () => {result: { response: 'Acme is your biggest customer' },error: null,success: true,+ isWaiting: false,threadId: expect.any(String),});expect(secondResult.threadId).not.toBe(result.threadId);- const { conversation, turn, execution } = runInput(agentRunnerService);+ const { conversation, spec, prompt, executionContext, resolveCreatedBy } =+ runInput(agentRunnerService);expect(conversation).toEqual({threadId: result.threadId,isCreated: true,});- expect(turn).toMatchObject({+ expect(spec).toMatchObject({title: AGENT.label,+ toolLoadingStrategy: 'lazy',+ capabilities: {+ canAskHumans: false,+ canProposeToolCalls: false,+ },+ });+ expect(prompt).toEqual({senderUserWorkspaceId: null,senderApplicationId: APPLICATION.id,messages: userInput('Who is our biggest customer?'),});- await expect(turn.resolveCreatedBy()).resolves.toMatchObject({+ expect(executionContext).toMatchObject({+ rolePermissionConfig: { intersectionOf: ['agent-role-id'] },+ conversationActor: { type: 'application', applicationId: APPLICATION.id },+ });+ await expect(resolveCreatedBy()).resolves.toMatchObject({source: 'APPLICATION',});- expect(execution).toMatchObject({ toolLoadingStrategy: 'lazy' });});it('keeps the replies a run without a thread hands over as its input', async () => {@@ -120,7 +138,7 @@ describe('AgentRunService', () => {await run(service, { input: history });- expect(runInput(agentRunnerService).turn.messages).toEqual(history);+ expect(runInput(agentRunnerService).prompt.messages).toEqual(history);});it('keeps accepting a prompt', async () => {@@ -128,7 +146,7 @@ describe('AgentRunService', () => {await run(service, { prompt: 'Who is our biggest customer?' });- expect(runInput(agentRunnerService).execution.messages).toEqual(+ expect(runInput(agentRunnerService).prompt.messages).toEqual(userInput('Who is our biggest customer?'),);});@@ -147,28 +165,37 @@ describe('AgentRunService', () => {runAsWorkspaceMemberId: 'workspace-member-id',});- const { conversation, conversationActor, turn, execution } =+ const { conversation, caller, prompt, executionContext, resolveCreatedBy } =runInput(agentRunnerService);expect(result.threadId).toBe(threadId);expect(conversation).toEqual({ threadId, isCreated: false });- expect(conversationActor).toEqual({- type: 'user',- userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,+ expect(caller).toEqual({+ type: 'AGENT_API_RUN',+ ref: {+ agentId: AGENT.id,+ runAsWorkspaceMemberId: 'workspace-member-id',+ requestUserWorkspaceId: null,+ createdBy: RUN_AS_ACTOR,+ },});- expect(turn).toMatchObject({- title: AGENT.label,+ expect(prompt).toMatchObject({senderUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,});- await expect(turn.resolveCreatedBy()).resolves.toEqual(RUN_AS_ACTOR);- expect(execution).toMatchObject({+ await expect(resolveCreatedBy()).resolves.toEqual(RUN_AS_ACTOR);+ expect(executionContext).toMatchObject({actorContext: RUN_AS_ACTOR,userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,runAsRoleId: 'role-id',+ rolePermissionConfig: { intersectionOf: ['role-id'] },+ conversationActor: {+ type: 'user',+ userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,+ },});});- it('gives the additional instructions to the model without recording them', async () => {+ it('keeps the additional instructions with the run rather than in its messages', async () => {const { service, agentRunnerService } = buildService();await run(service, {@@ -177,13 +204,13 @@ describe('AgentRunService', () => {additionalInstructions: 'Answer in Slack markdown',});- const { turn, execution } = runInput(agentRunnerService);+ const { spec, prompt } = runInput(agentRunnerService);- expect(execution.messages).toEqual(- userInput('Answer in Slack markdown\n\nAnd the second one?'),- );- expect(turn).toMatchObject({+ expect(spec).toMatchObject({title: 'Acme renewal',+ instructions: 'Answer in Slack markdown',+ });+ expect(prompt).toMatchObject({messages: userInput('And the second one?'),senderUserWorkspaceId: null,});@@ -201,7 +228,7 @@ describe('AgentRunService', () => {},);- expect(runInput(agentRunnerService).turn).toMatchObject({+ expect(runInput(agentRunnerService).prompt).toMatchObject({senderUserWorkspaceId: 'caller-user-workspace-id',senderApplicationId: null,});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 dcf68a6c9f3..5ca2533ae7e 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@@ -4,14 +4,12 @@ import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execimport { 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';-type RunInput = Extract<AgentRunnerRunInput, { turn: unknown }>;-const CREATED_BY = {source: 'WORKFLOW',name: 'New deals',workspaceMemberId: null,context: {},-} as Awaited<ReturnType<RunInput['turn']['resolveCreatedBy']>>;+} as Awaited<ReturnType<AgentRunnerRunInput['resolveCreatedBy']>>;const PRIOR_MESSAGES = [{ id: 'message-id', role: 'assistant', parts: [] }];@@ -45,22 +43,36 @@ const buildExecution = (...overrides,});-const RUN_INPUT: RunInput = {+const RUN_INPUT: AgentRunnerRunInput = {workspaceId: 'workspace-id',conversation: { threadId: 'thread-id', isCreated: false },- turn: {+ caller: {+ type: 'WORKFLOW_STEP',+ ref: { workflowRunId: 'run', stepId: 'step' },+ },+ spec: {+ agentId: null,title: 'Draft the quote',+ baseSystemPrompt: 'base prompt',+ instructions: null,+ capabilities: {+ canAskHumans: false,+ canProposeToolCalls: false,+ },+ },+ agent: null,+ prompt: {+ messages: MESSAGES,senderUserWorkspaceId: 'user-workspace-id',senderApplicationId: null,- messages: MESSAGES,- resolveCreatedBy: async () => CREATED_BY,},- execution: {- agent: null,- messages: MESSAGES,- baseSystemPrompt: 'base prompt',- workspaceId: 'workspace-id',+ executionContext: {+ authContext: {} as never,+ userWorkspaceId: 'user-workspace-id',+ rolePermissionConfig: { intersectionOf: [] },+ conversationActor: { type: 'application', applicationId: 'app-id' },},+ resolveCreatedBy: async () => CREATED_BY,};const buildService = (execution = buildExecution()) => {@@ -83,7 +95,10 @@ const buildService = (execution = buildExecution()) => {agentAsyncExecutorService as never,agentRunConversationService as never,conversationReaderService as never,- {} as never,+ {+ findOne: jest.fn().mockResolvedValue(null),+ closeAwaitedCalls: jest.fn().mockResolvedValue(undefined),+ } as never,{} as never,{} as never,{} as never,@@ -106,10 +121,7 @@ describe('AgentRunnerService', () => {conversationReaderService,} = buildService();- const { threadId, outcome, summary } = await service.run({- ...RUN_INPUT,- conversationActor: { type: 'application', applicationId: 'app-id' },- });+ const { threadId, outcome, summary } = await service.run(RUN_INPUT);expect(threadId).toBe('thread-id');expect(outcome).toEqual({@@ -138,15 +150,19 @@ describe('AgentRunnerService', () => {createdBy: CREATED_BY,messages: MESSAGES,});- expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith({- ...RUN_INPUT.execution,- priorMessages: PRIOR_MESSAGES,- });+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: MESSAGES,+ baseSystemPrompt: expect.stringMatching(+ /^base prompt\n\n.*wait_for_event/,+ ),+ priorMessages: PRIOR_MESSAGES,+ }),+ );expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(expect.objectContaining({turnId: 'turn-id',title: 'Draft the quote',- isAwaitedByCaller: false,}),);});@@ -184,7 +200,7 @@ describe('AgentRunnerService', () => {],])('still runs the agent when %s',- async (_, turnOverrides, conversationOverrides) => {+ async (_, inputOverrides, conversationOverrides) => {const {service,agentAsyncExecutorService,@@ -195,7 +211,7 @@ describe('AgentRunnerService', () => {const { outcome } = await service.run({...RUN_INPUT,- turn: { ...RUN_INPUT.turn, ...turnOverrides },+ ...inputOverrides,});expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalled();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.tsindex eacc859cc8c..42d2b1084a0 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@@ -1,18 +1,26 @@import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';+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 { 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';import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.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 { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';+import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';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,@@ -45,8 +53,46 @@ export class AgentActorContextService {private readonly userWorkspaceService: UserWorkspaceService,private readonly userRoleService: UserRoleService,private readonly workspaceOrmManager: WorkspaceOrmManager,+ private readonly applicationLookupService: ApplicationLookupService,+ private readonly aiAgentRoleService: AiAgentRoleService,+ @InjectRepository(WorkspaceEntity)+ private readonly workspaceRepository: Repository<WorkspaceEntity>,) {}+ // An agent acting through its own application, as a trigger or API run does; null once the application is gone+ async buildApplicationAgentContext({+ workspaceId,+ agent,+ }: {+ workspaceId: string;+ agent: Pick<AgentEntity, 'id' | 'applicationId'>;+ }): Promise<ApplicationAgentContext | null> {+ const [workspace, application, agentRoleId] = await Promise.all([+ this.workspaceRepository.findOneOrFail({ where: { id: workspaceId } }),+ this.applicationLookupService.findById({+ id: agent.applicationId,+ workspaceId,+ }),+ this.aiAgentRoleService.findAgentRoleId({+ workspaceId,+ agentId: agent.id,+ }),+ ]);++ if (!isDefined(application)) {+ return null;+ }++ return {+ application,+ authContext: buildApplicationAuthContext({+ workspace: fromWorkspaceEntityToFlat(workspace),+ application,+ }),+ agentRoleId,+ };+ }+async buildUserAndAgentActorContext(userWorkspaceId: string,workspaceId: string,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.tsindex 3c9665a6485..4c6838edbb0 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@@ -66,6 +66,7 @@ import { STRUCTURED_OUTPUT_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { repairToolCall } from 'src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util';import { NATIVE_WEB_SEARCH_COST_PER_CALL_DOLLARS } from 'src/engine/metadata-modules/ai/ai-billing/constants/native-web-search-cost-per-call-dollars';+import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';import { countNativeWebSearchCallsFromSteps } from 'src/engine/metadata-modules/ai/ai-billing/utils/count-native-web-search-calls-from-steps.util';@@ -85,9 +86,6 @@ import {AiException,AiExceptionCode,} from 'src/engine/metadata-modules/ai/ai.exception';-import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';-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 buildUnavailableToolOutput = (toolName: string): ToolOutput => ({success: false,@@ -138,26 +136,11 @@ export class AgentAsyncExecutorService {private readonly aiBillingService: AiBillingService,private readonly metricsService: MetricsService,private readonly runAgentAttachmentService: RunAgentAttachmentService,- @InjectWorkspaceScopedRepository(RoleTargetEntity)- private readonly roleTargetRepository: WorkspaceScopedRepository<RoleTargetEntity>,+ private readonly aiAgentRoleService: AiAgentRoleService,@InjectRepository(WorkspaceEntity)private readonly workspaceRepository: Repository<WorkspaceEntity>,) {}- private async getAgentRoleId(- agentId: string,- workspaceId: string,- ): Promise<string | undefined> {- const roleTarget = await this.roleTargetRepository.findOne(workspaceId, {- where: {- agentId,- },- select: ['roleId'],- });-- return roleTarget?.roleId;- }-private resolveUserIdentity(authContext?: WorkspaceAuthContext): {userId?: string;userWorkspaceId?: string;@@ -416,10 +399,10 @@ export class AgentAsyncExecutorService {});if (agent) {- const agentRoleId = await this.getAgentRoleId(- agent.id,- agent.workspaceId,- );+ const agentRoleId = await this.aiAgentRoleService.findAgentRoleId({+ workspaceId: agent.workspaceId,+ agentId: agent.id,+ });const nativeModelToolOptions: NativeModelToolOptions = {webSearch: agent.modelConfiguration?.webSearch?.enabled === 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 e4e91a47b7f..a4b9de96b2b 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@@ -136,7 +136,6 @@ export class AgentRunConversationService {title,agentId,execution,- isAwaitedByCaller,}: {workspaceId: string;threadId: string;@@ -144,8 +143,6 @@ export class AgentRunConversationService {title: string;agentId: string | null;execution: RecordableAgentExecution;- // a caller such as a workflow step waits on the calls the run pauses on- isAwaitedByCaller?: boolean;}): Promise<{ isAwaitingAnswer: boolean }> {const turn = { workspaceId, threadId, turnId, execution };@@ -157,7 +154,6 @@ export class AgentRunConversationService {turnId,agentId,execution,- isAwaitedByCaller,}).catch(async (error: unknown) => {await this.turnRecorderService.finishExecutedTurn({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 9deb453ba92..b36656102d8 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@@ -239,7 +239,7 @@ export class AgentRunSuspensionService {await this.callerHandlerRegistry.getHandlerOrThrow(suspension.caller.type)- .onOutcome({+ .onOutcome?.({workspaceId,caller: suspension.caller,threadId: suspension.threadId,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.tsindex 799211d662a..5aef55e91a2 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@@ -1,4 +1,9 @@-import { Injectable, Logger, NotFoundException } from '@nestjs/common';+import {+ Injectable,+ Logger,+ NotFoundException,+ type OnModuleInit,+} from '@nestjs/common';import { randomUUID } from 'node:crypto';@@ -16,12 +21,17 @@ import { buildCreatedByFromApplication } from 'src/engine/core-modules/actor/utiimport { 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 { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';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';import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';+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 AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.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 RunAsWorkspaceMemberContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/run-as-workspace-member-context.type';-import { addAdditionalInstructionsToLastRunAgentMessage } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util';+import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';import { resolveRunAgentMessagesOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util';import { AGENT_RUN_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/agent-run-base-system-prompt.const';@@ -43,18 +53,31 @@ type RunAgentServiceInput = {runAsWorkspaceMemberId?: string;};+type AgentApiRunCaller = Extract<AgentRunCaller, { type: 'AGENT_API_RUN' }>;++// Runs an agent for the runAgent API. A run that waits goes on later with the API call as its+// caller, and its reply lands in its conversation@Injectable()-export class AgentRunService {+export class AgentRunService+ implements AgentRunCallerHandler<AgentApiRunCaller>, OnModuleInit+{+ readonly callerType = 'AGENT_API_RUN';+private readonly logger = new Logger(AgentRunService.name);constructor(private readonly agentActorContextService: AgentActorContextService,private readonly agentRunnerService: AgentRunnerService,+ private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,private readonly applicationLookupService: ApplicationLookupService,@InjectWorkspaceScopedRepository(AgentEntity)private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,) {}+ onModuleInit(): void {+ this.callerHandlerRegistry.register(this);+ }+async run({workspace,requestUserWorkspaceId,@@ -129,22 +152,6 @@ export class AgentRunService {application,});- const authContext: WorkspaceAuthContext = runAsContext?.authContext ?? {- type: 'application',- workspace,- application,- };-- const senderUserWorkspaceId = this.resolveRunSender({- runAsContext,- callerApplication,- requestUserWorkspaceId,- });-- const threadTitle = isNonEmptyString(thread?.title)- ? thread.title- : agent.label;-const threadId = isDefined(thread)? buildAgentRunThreadId({applicationId: application.id,@@ -153,62 +160,65 @@ export class AgentRunService {}): randomUUID();- const createdBy =- runAsContext?.actorContext ??- this.buildRunCreator({ callerApplication, application });-- const executionMessages = isNonEmptyString(input.additionalInstructions)- ? addAdditionalInstructionsToLastRunAgentMessage({- messages,- additionalInstructions: input.additionalInstructions,- })- : messages;+ const caller: AgentApiRunCaller = {+ type: 'AGENT_API_RUN',+ ref: {+ agentId: agent.id,+ runAsWorkspaceMemberId: input.runAsWorkspaceMemberId ?? null,+ requestUserWorkspaceId,+ createdBy:+ runAsContext?.actorContext ??+ this.buildRunCreator({ callerApplication, application }),+ },+ };try {const { outcome } = await this.agentRunnerService.run({workspaceId: workspace.id,conversation: { threadId, isCreated: !isDefined(thread) },- conversationActor: isDefined(runAsContext)- ? {- type: 'user',- userWorkspaceId: runAsContext.authContext.userWorkspaceId,- }- : { type: 'application', applicationId: application.id },- turn: {- title: threadTitle,- senderUserWorkspaceId,- senderApplicationId: callerApplication?.id ?? null,- messages,- resolveCreatedBy: async () => createdBy,- },- execution: {- agent,- messages: executionMessages,+ caller,+ spec: {+ agentId: agent.id,+ title: isNonEmptyString(thread?.title) ? thread.title : agent.label,baseSystemPrompt: AGENT_RUN_BASE_SYSTEM_PROMPT,- actorContext: runAsContext?.actorContext,- authContext,- workspaceId: workspace.id,- userWorkspaceId:- runAsContext?.authContext.userWorkspaceId ?? requestUserWorkspaceId,- runAsRoleId: runAsContext?.roleId,+ // kept with the run rather than in its messages, so a run that waits still has them when it goes on+ instructions: input.additionalInstructions ?? null,+ // the call returns before anyone could answer, so the run can wait but not ask+ capabilities: {+ canAskHumans: false,+ canProposeToolCalls: false,+ },toolLoadingStrategy: 'lazy',},+ agent,+ prompt: {+ messages,+ senderUserWorkspaceId: this.resolveRunSender({+ runAsContext,+ callerApplication,+ requestUserWorkspaceId,+ }),+ senderApplicationId: callerApplication?.id ?? null,+ },+ executionContext: await this.buildExecutionContext({+ workspaceId: workspace.id,+ caller,+ }),+ resolveCreatedBy: async () => caller.ref.createdBy,});- if (outcome.status === 'FAILED') {- return { result: null, error: outcome.error, success: false, threadId };- }-return {result: outcome.status === 'COMPLETED' ? outcome.result : null,- error: null,- success: true,+ error: outcome.status === 'FAILED' ? outcome.error : null,+ success: outcome.status !== 'FAILED',+ isWaiting: outcome.status === 'SUSPENDED',threadId,};} catch (error) {if (error instanceof AiException &&- error.code === AiExceptionCode.INVALID_AGENT_INPUT+ (error.code === AiExceptionCode.INVALID_AGENT_INPUT ||+ error.code === AiExceptionCode.THREAD_AWAITING_ANSWER)) {throw error;}@@ -222,11 +232,104 @@ export class AgentRunService {result: null,error: 'Agent execution failed.',success: false,+ isWaiting: false,threadId,};}}+ // The member a run acts as is looked up again, so a waiting run goes on with their current role+ async buildExecutionContext({+ workspaceId,+ caller: { ref },+ }: AgentRunCallerInput<AgentApiRunCaller>): Promise<AgentRunExecutionContext> {+ const agent = await this.agentRepository.findOne(workspaceId, {+ where: { id: ref.agentId },+ });+ const agentContext = isDefined(agent)+ ? await this.agentActorContextService.buildApplicationAgentContext({+ workspaceId,+ agent,+ })+ : null;++ if (!isDefined(agentContext)) {+ throw new AiException(+ `Agent ${ref.agentId} or its application no longer exists`,+ AiExceptionCode.AGENT_NOT_FOUND,+ );+ }++ const runAsContext = isDefined(ref.runAsWorkspaceMemberId)+ ? await this.agentActorContextService.buildRunAsWorkspaceMemberContext({+ workspaceMemberId: ref.runAsWorkspaceMemberId,+ workspaceId,+ viaApplication: agentContext.application,+ })+ : undefined;++ return {+ authContext: runAsContext?.authContext ?? agentContext.authContext,+ actorContext: runAsContext?.actorContext,+ userWorkspaceId:+ runAsContext?.authContext.userWorkspaceId ?? ref.requestUserWorkspaceId,+ rolePermissionConfig: buildAgentRolePermissionConfig({+ agentRoleId: agentContext.agentRoleId,+ runAsRoleId: runAsContext?.roleId,+ }),+ runAsRoleId: runAsContext?.roleId,+ conversationActor: isDefined(runAsContext)+ ? {+ type: 'user',+ userWorkspaceId: runAsContext.authContext.userWorkspaceId,+ }+ : { type: 'application', applicationId: agentContext.application.id },+ };+ }++ async resolveTurnAuthor({+ caller,+ }: AgentRunCallerInput<AgentApiRunCaller>): Promise<ActorMetadata> {+ return caller.ref.createdBy;+ }++ async getWaitingState({+ workspaceId,+ caller,+ }: AgentRunCallerInput<AgentApiRunCaller>): Promise<AgentRunCallerWaitingState> {+ const agent = await this.agentRepository.findOne(workspaceId, {+ where: { id: caller.ref.agentId },+ select: ['id'],+ });++ if (!isDefined(agent)) {+ return 'GONE';+ }++ if (!isDefined(caller.ref.runAsWorkspaceMemberId)) {+ return 'WAITING';+ }++ // a run acting as a member who left can never continue, so it must release its thread+ try {+ await this.agentActorContextService.buildRunAsWorkspaceMemberContext({+ workspaceMemberId: caller.ref.runAsWorkspaceMemberId,+ workspaceId,+ });++ return 'WAITING';+ } catch (error) {+ if (+ error instanceof AiException &&+ error.code === AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_FOUND+ ) {+ return 'GONE';+ }++ throw error;+ }+ }+// a member calling without runAs still sent the input, while an app's call has no member behind itprivate resolveRunSender({runAsContext,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 db4e8ab45ac..ea508cc4e90 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@@ -8,6 +8,7 @@ import {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 { 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';@@ -38,13 +39,9 @@ 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';-type AgentRunnerTurnInput = Extract<AgentRunnerRunInput, { turn: unknown }>;--type AgentRunnerCallerInput = Extract<AgentRunnerRunInput, { caller: unknown }>;--// Runs an agent turn and records it in its conversation. A run a caller waits on 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 the caller's handler+// 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@Injectable()export class AgentRunnerService {private readonly logger = new Logger(AgentRunnerService.name);@@ -188,32 +185,37 @@ export class AgentRunnerService {const {workspaceId,conversation: { threadId, isCreated },- conversationActor,+ caller,+ spec,+ agent,+ prompt,+ executionContext,+ resolveCreatedBy,} = input;- const { turn, execution } =- 'caller' in input ? this.buildCallerTurn(input) : input;- const callerRun =- 'caller' in input ? { caller: input.caller, spec: input.spec } : null;++ if (!isCreated && !isDefined(suspension)) {+ await this.assertConversationNotSuspended({ workspaceId, threadId });+ }const priorMessages = isCreated? []: await this.conversationReaderService.loadMessages({workspaceId,threadId,- actor: conversationActor,+ actor: executionContext.conversationActor,});- const agentId = execution.agent?.id ?? null;+ const agentId = agent?.id ?? null;const turnId = await this.recordConversation(threadId, async () =>this.agentRunConversationService.openTurn({workspaceId,threadId,- title: turn.title,+ title: spec.title,agentId,- senderUserWorkspaceId: turn.senderUserWorkspaceId,- senderApplicationId: turn.senderApplicationId,- createdBy: await turn.resolveCreatedBy(),- messages: turn.messages,+ senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,+ senderApplicationId: prompt?.senderApplicationId ?? null,+ createdBy: await resolveCreatedBy(),+ messages: prompt?.messages ?? [],}),);@@ -224,7 +226,7 @@ export class AgentRunnerService {try {executionResult = await withDedicatedAiTrace(() =>this.agentAsyncExecutorService.executeAgent({- ...execution,+ ...this.buildExecution(input),priorMessages,}),);@@ -250,10 +252,9 @@ export class AgentRunnerService {workspaceId,threadId,turnId,- title: turn.title,+ title: spec.title,agentId,execution: executionResult,- isAwaitedByCaller: isDefined(callerRun),}),): null;@@ -272,7 +273,8 @@ export class AgentRunnerService {outcome: await this.settleTurn({workspaceId,threadId,- callerRun,+ caller,+ spec,execution: executionResult,isRecorded: isDefined(closedTurn),isAwaitingAnswer: closedTurn?.isAwaitingAnswer ?? false,@@ -282,10 +284,32 @@ 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,- callerRun,+ caller,+ spec,execution,isRecorded,isAwaitingAnswer,@@ -294,7 +318,8 @@ export class AgentRunnerService {}: {workspaceId: string;threadId: string;- callerRun: { caller: AgentRunCaller; spec: AgentRunSpec } | null;+ caller: AgentRunCaller;+ spec: AgentRunSpec;execution: AgentExecutionResult;isRecorded: boolean;isAwaitingAnswer: boolean;@@ -308,17 +333,21 @@ export class AgentRunnerService {const wait = findAgentRunWait(execution.steps[execution.steps.length - 1]?.toolResults ?? [],);+ const hasPausedTooOften =+ isDefined(suspension) &&+ suspension.resumeCount + 1 >= AGENT_RUN_MAX_CONTINUATIONS;// continuing reads the conversation, so a pause it does not hold could never be continuedconst suspensionId =!execution.hasNoMoreAvailableCredits &&- isDefined(callerRun) &&+ !hasPausedTooOften &&isRecorded &&(isAwaitingAnswer || isDefined(wait))? await this.keepSuspended({workspaceId,threadId,- callerRun,+ caller,+ spec,summary,suspension,})@@ -326,7 +355,7 @@ export class AgentRunnerService {if (!isDefined(suspensionId)) {// a pause the run could not keep leaves nothing to answer- if (isDefined(callerRun) && !isDefined(suspension)) {+ if (!isDefined(suspension)) {await this.agentRunSuspensionService.closeAwaitedCalls({workspaceId,threadId,@@ -340,6 +369,13 @@ export class AgentRunnerService {};}+ if (hasPausedTooOften) {+ return {+ status: 'FAILED',+ error: `Agent stopped: it paused more than ${AGENT_RUN_MAX_CONTINUATIONS} times in one run.`,+ };+ }+if (isDefined(wait)) {return {status: 'FAILED',@@ -369,13 +405,15 @@ export class AgentRunnerService {private async keepSuspended({workspaceId,threadId,- callerRun: { caller, spec },+ caller,+ spec,summary,suspension,}: {workspaceId: string;threadId: string;- callerRun: { caller: AgentRunCaller; spec: AgentRunSpec };+ caller: AgentRunCaller;+ spec: AgentRunSpec;summary: AgentRunSummary;suspension: AgentRunSuspensionEntity | null;}): Promise<string | null> {@@ -411,56 +449,49 @@ export class AgentRunnerService {}// The toolset and prompt come from the spec alone, so a continued run gets those it paused with- private buildCallerTurn({+ private buildExecution({workspaceId,spec,agent,prompt,executionContext,- resolveCreatedBy,- }: AgentRunnerCallerInput): Pick<AgentRunnerTurnInput, 'turn' | 'execution'> {- const messages = isDefined(prompt)- ? [{ role: 'user' as const, content: prompt }]- : [];- const { canAskHumans, canProposeToolCalls, canWait } = spec.capabilities;+ }: AgentRunnerRunInput): Omit<+ Parameters<AgentAsyncExecutorService['executeAgent']>[0],+ 'priorMessages'+ > {+ const { canAskHumans, canProposeToolCalls } = spec.capabilities;return {- turn: {- title: spec.title,- senderUserWorkspaceId: executionContext.userWorkspaceId,- senderApplicationId: null,- messages,- resolveCreatedBy,- },- execution: {- agent,- messages,- // the wait tools are the engine's, so it explains them; the caller's own instructions come last- baseSystemPrompt: [- spec.baseSystemPrompt,- ...(canWait ? [AGENT_WAIT_PROMPT] : []),- ...(isNonEmptyString(spec.instructions) ? [spec.instructions] : []),- ].join('\n\n'),- pausingTools: {- ...(canWait ? 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,- additionalRoleRestrictionIds:- executionContext.additionalRoleRestrictionIds,- additionalExcludedToolNames: spec.additionalExcludedToolNames,+ 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,};}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 a04da2bc5ae..ed98158192c 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,31 +1,32 @@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 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';-type AgentRunCallerInput = {- workspaceId: string;- caller: AgentRunCaller;-};--export type AgentRunCallerHandler = {- callerType: AgentRunCaller['type'];+export type AgentRunCallerHandler<+ TCaller extends AgentRunCaller = AgentRunCaller,+> = {+ callerType: TCaller['type'];buildExecutionContext(- input: AgentRunCallerInput,+ input: AgentRunCallerInput<TCaller>,): Promise<AgentRunExecutionContext>;- resolveTurnAuthor(input: AgentRunCallerInput): Promise<ActorMetadata>;+ resolveTurnAuthor(+ input: AgentRunCallerInput<TCaller>,+ ): Promise<ActorMetadata>;getWaitingState(- input: AgentRunCallerInput,+ input: AgentRunCallerInput<TCaller>,): Promise<AgentRunCallerWaitingState>;- onOutcome(- input: AgentRunCallerInput & {+ // absent for a caller that only records the run, whose outcome is already in its conversation+ onOutcome?(+ input: AgentRunCallerInput<TCaller> & {threadId: string;outcome: Exclude<AgentRunnerOutcome, { status: 'SUSPENDED' }>;// null for a call the caller posted itself, which no agent randiff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type.tsnew file mode 100644index 00000000000..c9f031c8792--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type.ts@@ -0,0 +1,8 @@+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';++export type AgentRunCallerInput<+ TCaller extends AgentRunCaller = AgentRunCaller,+> = {+ workspaceId: string;+ caller: TCaller;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type.tsindex da2d8dd1bb5..cee16756289 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type.ts@@ -1,6 +1,23 @@+import { type ActorMetadata } from 'twenty-shared/types';+// who started a run and waits on its outcome; stored with a suspended run, so the engine// can call it back without knowing what the ref means-export type AgentRunCaller = {- type: 'WORKFLOW_STEP';- ref: { workflowRunId: string; stepId: string };-};+export type AgentRunCaller =+ | {+ type: 'WORKFLOW_STEP';+ ref: { workflowRunId: string; stepId: string };+ }+ | {+ type: 'AGENT_TRIGGER';+ ref: { agentId: string; triggerId: string; dispatchedRoleId?: string };+ }+ | {+ type: 'AGENT_API_RUN';+ ref: {+ agentId: string;+ runAsWorkspaceMemberId: string | null;+ requestUserWorkspaceId: string | null;+ // the request's own actor cannot be read back once it is over+ createdBy: ActorMetadata;+ };+ };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 55edf0f2816..17254ee8b71 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,6 +1,7 @@import { type ActorMetadata } from 'twenty-shared/types';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';// The permissions a run acts with, which its caller derives on each segment instead of the engine storing them@@ -10,6 +11,10 @@ export type AgentRunExecutionContext = {userWorkspaceId: string | null;// what the run itself can read, such as the record an awaited event is aboutrolePermissionConfig: RolePermissionConfig;+ // replaces the agent's own role, for a run acting as a member+ runAsRoleId?: string;// narrows the agent's own role, such as to the application a run belongs toadditionalRoleRestrictionIds?: string[];+ // who the continued conversation is read for, so turns others acted on read as theirs+ conversationActor?: AgentConversationActor;};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.tsnew file mode 100644index 00000000000..d9fa8a94b9e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-prompt.type.ts@@ -0,0 +1,8 @@+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-spec.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.tsindex 8ea7123081d..55b2ca9cc86 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts@@ -1,3 +1,5 @@+import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-tool-loading-strategy.type';+// What a suspended run needs to continue without its caller building it again.// Permissions are left out: the caller derives them anew on each continuationexport type AgentRunSpec = {@@ -12,8 +14,7 @@ export type AgentRunSpec = {canAskHumans: boolean;// propose_tool_call, for an action a person approves firstcanProposeToolCalls: boolean;- // wait_for_event and wait_for_duration, resolved by a wake-up- canWait: boolean;};additionalExcludedToolNames?: string[];+ toolLoadingStrategy?: AgentToolLoadingStrategy;};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.tsindex c992dd783f0..bc893bce0a2 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,44 +1,23 @@-import { type RunAgentMessage } from 'twenty-shared/application';import { type ActorMetadata } from 'twenty-shared/types';-import { type AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';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';-import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';+// A run that pauses is suspended with its spec, and the engine continues it on its own and hands+// the outcome to its caller's handlerexport type AgentRunnerRunInput = {workspaceId: string;conversation: AgentRunConversation;- // who the continued conversation is read for, so turns others acted on read as theirs- conversationActor?: AgentConversationActor;-} & (- | {- turn: {- // names the thread when the turn creates it- title: string;- senderUserWorkspaceId: string | null;- senderApplicationId: string | null;- messages: RunAgentMessage[];- // resolved while recording the turn, so a failed lookup does not stop the run- resolveCreatedBy: () => Promise<ActorMetadata>;- };- execution: Omit<- Parameters<AgentAsyncExecutorService['executeAgent']>[0],- 'priorMessages'- >;- }- // A caller such as a workflow step waits on the outcome: a run that pauses is suspended with its- // spec, and the engine continues it on its own and hands the outcome to the caller's handler- | {- caller: AgentRunCaller;- spec: AgentRunSpec;- agent: AgentEntity | null;- // absent when the run continues its conversation without a new message- prompt: string | null;- executionContext: AgentRunExecutionContext;- resolveCreatedBy: () => Promise<ActorMetadata>;- }-);+ caller: AgentRunCaller;+ spec: AgentRunSpec;+ agent: AgentEntity | null;+ // absent when the run continues its conversation without a new message+ prompt: AgentRunPrompt | 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.tsnew file mode 100644index 00000000000..8f0042e357f--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/application-agent-context.type.ts@@ -0,0 +1,8 @@+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__/add-additional-instructions-to-last-run-agent-message.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/add-additional-instructions-to-last-run-agent-message.util.spec.tsdeleted file mode 100644index 67af6304d28..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/add-additional-instructions-to-last-run-agent-message.util.spec.ts+++ /dev/null@@ -1,34 +0,0 @@-import { addAdditionalInstructionsToLastRunAgentMessage } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util';--describe('addAdditionalInstructionsToLastRunAgentMessage', () => {- it('should put the instructions before the content of the last message only', () => {- expect(- addAdditionalInstructionsToLastRunAgentMessage({- messages: [- { role: 'user', content: 'Who owns Acme?' },- { role: 'user', content: 'And the last touchpoint?' },- ],- additionalInstructions: 'Answer in Slack markdown.',- }),- ).toEqual([- { role: 'user', content: 'Who owns Acme?' },- {- role: 'user',- content: 'Answer in Slack markdown.\n\nAnd the last touchpoint?',- },- ]);- });-- it('should use the instructions as the content of a message that only carries files', () => {- const attachments = [{ fileId: 'file-id', filename: 'deck.pdf' }];-- expect(- addAdditionalInstructionsToLastRunAgentMessage({- messages: [{ role: 'user', content: '', attachments }],- additionalInstructions: 'Answer in Slack markdown.',- }),- ).toEqual([- { role: 'user', content: 'Answer in Slack markdown.', attachments },- ]);- });-});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.tsindex 826c7ba9670..f3c7aae351c 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts@@ -58,4 +58,13 @@ describe('buildAgentRolePermissionConfig', () => {}),).toEqual({ intersectionOf: ['application-role-id'] });});++ it('reads nothing for an agent without a role, whatever restricts it', () => {+ expect(+ buildAgentRolePermissionConfig({+ agentRoleId: undefined,+ additionalRoleRestrictionIds: ['application-role-id'],+ }),+ ).toEqual({ intersectionOf: [] });+ });});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.tsdeleted file mode 100644index f5607698322..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.ts+++ /dev/null@@ -1,20 +0,0 @@-import { isNonEmptyString } from '@sniptt/guards';-import { type RunAgentMessage } from 'twenty-shared/application';--export const addAdditionalInstructionsToLastRunAgentMessage = ({- messages,- additionalInstructions,-}: {- messages: RunAgentMessage[];- additionalInstructions: string;-}): RunAgentMessage[] =>- messages.map((message, index) =>- index === messages.length - 1- ? {- ...message,- content: isNonEmptyString(message.content)- ? `${additionalInstructions}\n\n${message.content}`- : additionalInstructions,- }- : message,- );diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.tsindex 4ad40a03afb..a36d07b2627 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts@@ -7,12 +7,17 @@ export const buildAgentRolePermissionConfig = ({runAsRoleId,additionalRoleRestrictionIds = [],}: {- agentRoleId: string;+ agentRoleId: string | undefined;runAsRoleId?: string;additionalRoleRestrictionIds?: string[];}): RolePermissionConfig => {const baseRoleId = isDefined(runAsRoleId) ? runAsRoleId : agentRoleId;+ // without a role the agent reads nothing, however its restrictions narrow it+ if (!isDefined(baseRoleId)) {+ return { intersectionOf: [] };+ }+return {intersectionOf: [...new Set([baseRoleId, ...additionalRoleRestrictionIds])],};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service.tsindex 37210218e85..0b423a3c670 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service.ts@@ -27,6 +27,21 @@ export class AiAgentRoleService {private readonly workspaceCacheService: WorkspaceCacheService,) {}+ public async findAgentRoleId({+ workspaceId,+ agentId,+ }: {+ workspaceId: string;+ agentId: string;+ }): Promise<string | undefined> {+ const { flatRoleTargetByAgentIdMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatRoleTargetByAgentIdMaps',+ ]);++ return flatRoleTargetByAgentIdMaps[agentId]?.roleId;+ }+public async assignRoleToAgent({workspaceId,agentId,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/ai-agent-trigger.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/ai-agent-trigger.module.tsindex 8a375de3fd8..42bc6ae5c1e 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/ai-agent-trigger.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/ai-agent-trigger.module.ts@@ -1,7 +1,6 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';-import { ApplicationLookupModule } from 'src/engine/core-modules/application/application-lookup/application-lookup.module';import { CronModule } from 'src/engine/core-modules/cron/cron.module';import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';@@ -21,7 +20,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheimports: [TypeOrmModule.forFeature([AgentEntity, WorkspaceEntity]),AiAgentExecutionModule,- ApplicationLookupModule,CronModule,RecordShareModule,ThrottlerModule,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.tsindex 9d7acd1078c..404802fe2e2 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts@@ -1,14 +1,12 @@import { Test, type TestingModule } from '@nestjs/testing';-import { getRepositoryToken } from '@nestjs/typeorm';-import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+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';import { AgentTriggerRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service';import { type RunAgentTriggerJobData } from 'src/engine/metadata-modules/ai/ai-agent-trigger/types/run-agent-trigger-job-data.type';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';const WORKSPACE_ID = 'workspace-id';const AGENT_ID = 'agent-id';@@ -66,33 +64,28 @@ describe('AgentTriggerRunnerService', () => {useValue: { run: runAgent },},{- provide: ApplicationLookupService,- useValue: { findById: findApplication },+ provide: AgentRunCallerHandlerRegistryService,+ useValue: { register: jest.fn() },},{- provide: getWorkspaceScopedRepositoryToken(AgentEntity),- useValue: { findOne: findAgent },- },- {- provide: getRepositoryToken(WorkspaceEntity),+ provide: AgentActorContextService,useValue: {- findOneOrFail: jest.fn().mockResolvedValue({- id: WORKSPACE_ID,- createdAt: new Date(),- updatedAt: new Date(),- deletedAt: null,+ buildApplicationAgentContext: jest.fn(async () => {+ const application = await findApplication();++ return application+ ? {+ application,+ authContext: { type: 'application', application },+ agentRoleId: currentRoleId,+ }+ : null;}),},},{- provide: WorkspaceCacheService,- useValue: {- getOrRecompute: jest.fn().mockImplementation(async () => ({- flatRoleTargetByAgentIdMaps: {- [AGENT_ID]: { agentId: AGENT_ID, roleId: currentRoleId },- },- })),- },+ provide: getWorkspaceScopedRepositoryToken(AgentEntity),+ useValue: { findOne: findAgent },},],}).compile();@@ -100,24 +93,39 @@ describe('AgentTriggerRunnerService', () => {service = module.get(AgentTriggerRunnerService);});- it('should run the agent as itself in a new conversation', async () => {+ it('should run the agent as itself in a new conversation, able to wait', async () => {await service.run(JOB_DATA);expect(runAgent).toHaveBeenCalledWith(expect.objectContaining({conversation: { threadId: expect.any(String), isCreated: true },- turn: expect.objectContaining({+ caller: {+ type: 'AGENT_TRIGGER',+ ref: {+ agentId: AGENT_ID,+ triggerId: TRIGGER_ID,+ dispatchedRoleId: AGENT_ROLE_ID,+ },+ },+ spec: expect.objectContaining({title: 'Enricher',+ toolLoadingStrategy: 'lazy',+ capabilities: {+ canAskHumans: false,+ canProposeToolCalls: false,+ },+ }),+ prompt: expect.objectContaining({senderUserWorkspaceId: null,senderApplicationId: 'application-id',}),- execution: expect.objectContaining({+ executionContext: expect.objectContaining({actorContext: expect.objectContaining({ name: 'Enricher' }),authContext: expect.objectContaining({type: 'application',actingAgent: { id: AGENT_ID, label: 'Enricher' },}),- toolLoadingStrategy: 'lazy',+ rolePermissionConfig: { intersectionOf: [AGENT_ROLE_ID] },}),}),);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.tsindex a1220fd5adb..08f73c84640 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@@ -1,46 +1,139 @@-import { Injectable, Logger } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';+import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';+import { type AgentTrigger } from 'twenty-shared/application';+import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { Repository } from 'typeorm';import { v4 } from 'uuid';-import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';import { buildCreatedByFromAgent } from 'src/engine/core-modules/actor/utils/build-created-by-from-agent.util';-import { buildApplicationAuthContext } from 'src/engine/core-modules/auth/utils/build-application-auth-context.util';-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 { 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';+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 AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.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 { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';import { AGENT_TRIGGER_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent-trigger/constants/agent-trigger-base-system-prompt.const';import { type RunAgentTriggerJobData } from 'src/engine/metadata-modules/ai/ai-agent-trigger/types/run-agent-trigger-job-data.type';import { buildAgentTriggerMessages } from 'src/engine/metadata-modules/ai/ai-agent-trigger/utils/build-agent-trigger-messages.util';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';+import {+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+type AgentTriggerCaller = Extract<AgentRunCaller, { type: 'AGENT_TRIGGER' }>;++type TriggeredRun = {+ agent: AgentEntity;+ trigger: AgentTrigger;+ createdBy: ActorMetadata;+ executionContext: AgentRunExecutionContext;+};++// Runs an agent on its triggers. A run that waits goes on later with the trigger as its caller,+// as long as the trigger could still start it@Injectable()-export class AgentTriggerRunnerService {+export class AgentTriggerRunnerService+ implements AgentRunCallerHandler<AgentTriggerCaller>, OnModuleInit+{+ readonly callerType = 'AGENT_TRIGGER';+private readonly logger = new Logger(AgentTriggerRunnerService.name);constructor(private readonly agentRunnerService: AgentRunnerService,- private readonly applicationLookupService: ApplicationLookupService,+ private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,+ private readonly agentActorContextService: AgentActorContextService,@InjectWorkspaceScopedRepository(AgentEntity)private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,- @InjectRepository(WorkspaceEntity)- private readonly workspaceRepository: Repository<WorkspaceEntity>,- private readonly workspaceCacheService: WorkspaceCacheService,) {}+ onModuleInit(): void {+ this.callerHandlerRegistry.register(this);+ }+async run({workspaceId,- agentId,- triggerId,- dispatchedRoleId,payload,+ ...ref}: RunAgentTriggerJobData): Promise<void> {+ const caller: AgentTriggerCaller = { type: 'AGENT_TRIGGER', ref };+ const triggeredRun = await this.findTriggeredRun({ workspaceId, caller });++ if (!isDefined(triggeredRun)) {+ return;+ }++ const { agent, trigger, createdBy, executionContext } = triggeredRun;++ await this.agentRunnerService.run({+ workspaceId,+ conversation: {+ threadId: buildAgentRunThreadId({+ applicationId: agent.applicationId,+ agentId: agent.id,+ threadKey: `trigger:${trigger.id}:${v4()}`,+ }),+ isCreated: true,+ },+ caller,+ spec: {+ agentId: agent.id,+ title: agent.label,+ baseSystemPrompt: AGENT_TRIGGER_BASE_SYSTEM_PROMPT,+ instructions: null,+ // nobody is there to answer, so the run can wait but not ask+ capabilities: {+ canAskHumans: false,+ canProposeToolCalls: false,+ },+ toolLoadingStrategy: 'lazy',+ },+ agent,+ prompt: {+ messages: buildAgentTriggerMessages({+ instructions: trigger.instructions,+ payload,+ }),+ senderUserWorkspaceId: null,+ senderApplicationId: agent.applicationId,+ },+ executionContext,+ resolveCreatedBy: async () => createdBy,+ });+ }++ async buildExecutionContext(+ input: AgentRunCallerInput<AgentTriggerCaller>,+ ): Promise<AgentRunExecutionContext> {+ return (await this.findTriggeredRunOrThrow(input)).executionContext;+ }++ async resolveTurnAuthor(+ input: AgentRunCallerInput<AgentTriggerCaller>,+ ): Promise<ActorMetadata> {+ return (await this.findTriggeredRunOrThrow(input)).createdBy;+ }++ async getWaitingState(+ input: AgentRunCallerInput<AgentTriggerCaller>,+ ): Promise<AgentRunCallerWaitingState> {+ return isDefined(await this.findTriggeredRun(input)) ? 'WAITING' : 'GONE';+ }++ // The trigger may have been turned off or removed, or the agent's role changed, since the run was queued+ private async findTriggeredRun({+ workspaceId,+ caller: {+ ref: { agentId, triggerId, dispatchedRoleId },+ },+ }: AgentRunCallerInput<AgentTriggerCaller>): Promise<TriggeredRun | null> {const agent = await this.agentRepository.findOne(workspaceId, {where: { id: agentId },});@@ -49,86 +142,65 @@ export class AgentTriggerRunnerService {(agentTrigger) => agentTrigger.id === triggerId,);- // The trigger may have been turned off or removed while the run was queuedif (!isDefined(agent) || !isDefined(trigger) || !trigger.isActive) {- return;+ return null;}- if (isDefined(dispatchedRoleId)) {- const { flatRoleTargetByAgentIdMaps } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatRoleTargetByAgentIdMaps',- ]);+ const agentContext =+ await this.agentActorContextService.buildApplicationAgentContext({+ workspaceId,+ agent,+ });- if (flatRoleTargetByAgentIdMaps[agentId]?.roleId !== dispatchedRoleId) {- this.logger.warn(- `Skipping trigger ${triggerId} of agent ${agentId}: its role changed since the run was queued`,- );+ if (!isDefined(agentContext)) {+ this.logger.warn(+ `Skipping trigger ${triggerId} of agent ${agentId}: application ${agent.applicationId} not found`,+ );- return;- }+ return null;}- const [workspace, application] = await Promise.all([- this.workspaceRepository.findOneOrFail({ where: { id: workspaceId } }),- this.applicationLookupService.findById({- id: agent.applicationId,- workspaceId,- }),- ]);+ const { application, authContext, agentRoleId } = agentContext;- if (!isDefined(application)) {+ if (isDefined(dispatchedRoleId) && agentRoleId !== dispatchedRoleId) {this.logger.warn(- `Skipping trigger ${triggerId} of agent ${agentId}: application ${agent.applicationId} not found`,+ `Skipping trigger ${triggerId} of agent ${agentId}: its role changed since the run was queued`,);- return;+ return null;}const actingAgent = { id: agent.id, label: agent.label };- const authContext = {- ...buildApplicationAuthContext({- workspace: fromWorkspaceEntityToFlat(workspace),- application,- }),- actingAgent,- };- const messages = buildAgentTriggerMessages({- instructions: trigger.instructions,- payload,- });const createdBy = buildCreatedByFromAgent({agent: actingAgent,applicationId: application.id,});- await this.agentRunnerService.run({- workspaceId,- conversation: {- threadId: buildAgentRunThreadId({- applicationId: application.id,- agentId: agent.id,- threadKey: `trigger:${trigger.id}:${v4()}`,- }),- isCreated: true,- },- turn: {- title: agent.label,- senderUserWorkspaceId: null,- senderApplicationId: application.id,- messages,- resolveCreatedBy: async () => createdBy,- },- execution: {- agent,- messages,- baseSystemPrompt: AGENT_TRIGGER_BASE_SYSTEM_PROMPT,+ return {+ agent,+ trigger,+ createdBy,+ executionContext: {+ authContext: { ...authContext, actingAgent },actorContext: createdBy,- authContext,- workspaceId,userWorkspaceId: null,- toolLoadingStrategy: 'lazy',+ rolePermissionConfig: buildAgentRolePermissionConfig({ agentRoleId }),},- });+ };+ }++ private async findTriggeredRunOrThrow(+ input: AgentRunCallerInput<AgentTriggerCaller>,+ ): Promise<TriggeredRun> {+ const triggeredRun = await this.findTriggeredRun(input);++ if (!isDefined(triggeredRun)) {+ throw new AiException(+ `Trigger ${input.caller.ref.triggerId} of agent ${input.caller.ref.agentId} can no longer run`,+ AiExceptionCode.AGENT_EXECUTION_FAILED,+ );+ }++ return triggeredRun;}}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.tsindex cd19bca4eaf..55437d94f92 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts@@ -215,7 +215,6 @@ export class AgentConversationWriterService {turnId,agentId,execution,- isAwaitedByCaller = false,scope,}: {workspaceId: string;@@ -223,17 +222,15 @@ export class AgentConversationWriterService {turnId: string;agentId: string | null;execution: RecordableAgentExecution;- // a caller such as a workflow step waits on the calls the run pauses on- isAwaitedByCaller?: boolean;scope?: AgentHistoryTransactionScope;}): Promise<{isAwaitingAnswer: boolean;replyParts: ExtendedUIMessagePart[];}> {- const mappedReplyParts = mapAiStepsToUIMessageParts(execution.steps ?? []);- const replyParts = isAwaitedByCaller- ? stampPendingToolPartsAwaitedByCaller(mappedReplyParts)- : mappedReplyParts;+ // every executed run has a caller waiting on the calls it pauses on+ const replyParts = stampPendingToolPartsAwaitedByCaller(+ mapAiStepsToUIMessageParts(execution.steps ?? []),+ );if (replyParts.length === 0) {return { isAwaitingAnswer: false, replyParts };diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.tsindex d8f9f2ebe03..594be959c34 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts@@ -311,7 +311,6 @@ export class DevSeederWorkflowPendingInputWorkspaceService {turnId,title: workflow.step.name,agentId: null,- isAwaitedByCaller: true,execution: {isPaused: true,steps: [{ content }],diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util.tsindex 1f9de883d50..672a09410eb 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util.ts@@ -1,5 +1,7 @@import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';+type WorkflowStepCaller = Extract<AgentRunCaller, { type: 'WORKFLOW_STEP' }>;+export const buildWorkflowStepCaller = (- ref: AgentRunCaller['ref'],-): AgentRunCaller => ({ type: 'WORKFLOW_STEP', ref });+ ref: WorkflowStepCaller['ref'],+): WorkflowStepCaller => ({ type: 'WORKFLOW_STEP', ref });diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.tsindex 5d2c25ce697..699f0b38423 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts@@ -138,6 +138,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {}),});+ const agentExecutionContext =+ buildWorkflowAgentRunExecutionContext(executionContext);+ const resolvedPrompt = resolveInput(prompt, context) as string | undefined;+const { threadId, outcome, summary } = await this.agentRunnerService.run({workspaceId,conversation,@@ -150,8 +154,14 @@ export class AiAgentWorkflowAction implements WorkflowAction {isApplicationBound: isDefined(application),}),agent,- prompt: (resolveInput(prompt, context) as string | undefined) ?? null,- executionContext: buildWorkflowAgentRunExecutionContext(executionContext),+ prompt: isDefined(resolvedPrompt)+ ? {+ messages: [{ role: 'user', content: resolvedPrompt }],+ senderUserWorkspaceId: agentExecutionContext.userWorkspaceId,+ senderApplicationId: null,+ }+ : null,+ executionContext: agentExecutionContext,resolveCreatedBy: () =>this.workflowAgentConversationService.findTurnCreatedBy(runInfo),});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.tsindex 80c5816e7da..594ac06decd 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts@@ -23,7 +23,7 @@ const buildStep = (}) as WorkflowAiAgentAction;describe('buildWorkflowAgentRunSpec', () => {- it('lets the agent wait but not ask without human input instructions', () => {+ it('keeps the agent from asking without human input instructions', () => {const spec = buildWorkflowAgentRunSpec({step: buildStep({prompt: 'Draft the quote',@@ -39,7 +39,6 @@ describe('buildWorkflowAgentRunSpec', () => {capabilities: {canAskHumans: false,canProposeToolCalls: false,- canWait: true,},});expect(spec).not.toHaveProperty('additionalExcludedToolNames');@@ -58,7 +57,6 @@ describe('buildWorkflowAgentRunSpec', () => {expect(spec.capabilities).toEqual({canAskHumans: true,canProposeToolCalls: true,- canWait: true,});expect(spec.instructions).toMatch(/Ask before choosing a plan\.$/);});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.tsindex 136ba69e7f4..37737e5a86f 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@@ -28,7 +28,6 @@ export const buildWorkflowAgentRunSpec = ({capabilities: {canAskHumans,canProposeToolCalls: canAskHumans,- canWait: true,},...(isApplicationBound? {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 42d8c525119..727d54b9fd9 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@@ -8,6 +8,8 @@ import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decoraimport { 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 { 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 AgentRunCallerInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type';import { type AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.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';@@ -23,15 +25,13 @@ import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runnerimport { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';-type WorkflowStepCallerInput = Parameters<- AgentRunCallerHandler['getWaitingState']->[0];+type WorkflowStepCaller = Extract<AgentRunCaller, { type: 'WORKFLOW_STEP' }>;// A step waiting on a CALLBACK takes the outcome of what it handed its work to: the agent run the// engine continued, or the answer to a call the step posted itself@Injectable()export class WorkflowAgentRunCallerHandlerWorkspaceService- implements AgentRunCallerHandler, OnModuleInit+ implements AgentRunCallerHandler<WorkflowStepCaller>, OnModuleInit{readonly callerType = 'WORKFLOW_STEP';@@ -52,7 +52,7 @@ export class WorkflowAgentRunCallerHandlerWorkspaceServiceasync buildExecutionContext({workspaceId,caller,- }: WorkflowStepCallerInput): Promise<AgentRunExecutionContext> {+ }: AgentRunCallerInput<WorkflowStepCaller>): Promise<AgentRunExecutionContext> {return buildWorkflowAgentRunExecutionContext(await this.workflowExecutionContextService.getExecutionContext({workflowRunId: caller.ref.workflowRunId,@@ -64,7 +64,7 @@ export class WorkflowAgentRunCallerHandlerWorkspaceServiceasync resolveTurnAuthor({workspaceId,caller,- }: WorkflowStepCallerInput): Promise<ActorMetadata> {+ }: AgentRunCallerInput<WorkflowStepCaller>): Promise<ActorMetadata> {return this.workflowAgentConversationService.findTurnCreatedBy({workflowRunId: caller.ref.workflowRunId,workspaceId,@@ -75,7 +75,7 @@ export class WorkflowAgentRunCallerHandlerWorkspaceServiceasync getWaitingState({workspaceId,caller,- }: WorkflowStepCallerInput): Promise<AgentRunCallerWaitingState> {+ }: AgentRunCallerInput<WorkflowStepCaller>): Promise<AgentRunCallerWaitingState> {const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({workflowRunId: caller.ref.workflowRunId,workspaceId,@@ -105,7 +105,9 @@ export class WorkflowAgentRunCallerHandlerWorkspaceServicethreadId,outcome,summary,- }: Parameters<AgentRunCallerHandler['onOutcome']>[0]): Promise<void> {+ }: Parameters<+ NonNullable<AgentRunCallerHandler<WorkflowStepCaller>['onOutcome']>+ >[0]): Promise<void> {if (isDefined(summary)) {await this.workflowRunStepLogService.setAiAgentStepLog({workflowRunId,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.tsnew file mode 100644index 00000000000..d50f4eb989f--- /dev/null+++ b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts@@ -0,0 +1,311 @@+import { randomUUID } from 'node:crypto';++import gql from 'graphql-tag';+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';+import { updateOneAgent } from 'test/integration/metadata/suites/agent/utils/update-one-agent.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { expectEventually } from 'test/integration/utils/expect-eventually.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';+import { type AgentTrigger } from 'twenty-shared/application';++import { type ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.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 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';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';++const workspaceId = SEED_APPLE_WORKSPACE_ID;+const schema = getWorkspaceSchemaName(workspaceId);++const agentResult = (+ overrides: Partial<AgentExecutionResult>,+): AgentExecutionResult =>+ ({+ result: { response: '' },+ usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },+ cacheCreationTokens: 0,+ nativeWebSearchCallCount: 0,+ hasNoMoreAvailableCredits: false,+ modelId: 'test-model',+ ...overrides,+ }) as AgentExecutionResult;++const waitingResult = () => {+ const resumeAt = new Date(Date.now() + 1_000).toISOString();+ const output = {+ success: true,+ message: `Waiting until ${resumeAt}.`,+ result: { status: 'pending', wait: { type: 'TIME', resumeAt } },+ };++ return agentResult({+ isPaused: true,+ steps: [+ {+ content: [+ {+ type: 'tool-call',+ toolCallId: 'wait-1',+ toolName: 'wait_for_duration',+ input: { durationInMinutes: 1 },+ },+ {+ type: 'tool-result',+ toolCallId: 'wait-1',+ toolName: 'wait_for_duration',+ input: { durationInMinutes: 1 },+ output,+ },+ ],+ toolResults: [+ { toolCallId: 'wait-1', toolName: 'wait_for_duration', output },+ ],+ },+ ] as unknown as AgentExecutionResult['steps'],+ });+};++const replyingResult = agentResult({+ result: { response: 'Followed up' },+ steps: [+ { content: [{ type: 'text', text: 'Followed up' }] },+ ] as AgentExecutionResult['steps'],+});++const mockAgent = (...results: AgentExecutionResult[]) =>+ results.reduce(+ (spy, result) => spy.mockResolvedValueOnce(result),+ jest.spyOn(+ getAppProviderByClassName<AgentAsyncExecutorService>(+ 'AgentAsyncExecutorService',+ ),+ 'executeAgent',+ ),+ );++const findSuspensions = (callerType: string, agentId: string) =>+ global.testDataSource.query(+ `SELECT suspension.id, suspension."threadId", wake_up."ownerType" FROM core."agentRunSuspension" suspension+ LEFT JOIN core."pendingWakeUp" wake_up ON wake_up."ownerId" = suspension.id+ WHERE suspension.caller->>'type' = $1 AND suspension.caller->'ref'->>'agentId' = $2`,+ [callerType, agentId],+ );++const findTurnStatuses = async (threadId: string) =>+ (+ await global.testDataSource.query(+ `SELECT status FROM "${schema}"."agentTurn" WHERE "threadId" = $1 ORDER BY "createdAt"`,+ [threadId],+ )+ ).map(({ status }: { status: string }) => status);++describe('agent runs that wait (integration)', () => {+ const triggerId = randomUUID();+ const trigger: AgentTrigger = {+ id: triggerId,+ type: 'CRON',+ isActive: true,+ instructions: 'Follow up with new leads',+ settings: { pattern: '0 9 * * *' },+ };+ let agentId: string;+ let agentUniversalIdentifier: string;+ let agentApplicationId: string;++ beforeAll(async () => {+ const { data } = await createOneAgent({+ expectToFail: false,+ input: {+ label: 'Waiting Agent',+ prompt: 'Follow up with leads',+ modelId: TEST_AI_MODEL_ID,+ triggers: [trigger],+ },+ });++ agentId = data.createOneAgent.id;++ const [agent] = await global.testDataSource.query(+ `SELECT "universalIdentifier", "applicationId" FROM core.agent WHERE id = $1`,+ [agentId],+ );++ agentUniversalIdentifier = agent.universalIdentifier;+ agentApplicationId = agent.applicationId;+ });++ afterEach(() => jest.restoreAllMocks());++ afterAll(async () => {+ await deleteOneAgent({ expectToFail: false, input: { id: agentId } });+ });++ const runTrigger = () =>+ getAppProviderByClassName<AgentTriggerRunnerService>(+ 'AgentTriggerRunnerService',+ ).run({+ workspaceId,+ agentId,+ triggerId,+ payload: { type: 'CRON', firedAt: new Date().toISOString() },+ });++ it('lets a triggered agent wait for a duration and go on once the wake-up resolves', async () => {+ const executeAgent = mockAgent(waitingResult(), replyingResult);++ await runTrigger();++ const [suspension] = await findSuspensions('AGENT_TRIGGER', agentId);++ expect(suspension).toMatchObject({ ownerType: 'AGENT_RUN' });+ expect(executeAgent.mock.calls[0][0].baseSystemPrompt).toContain(+ 'wait_for_duration',+ );+ expect(+ Object.keys(executeAgent.mock.calls[0][0].pausingTools ?? {}),+ ).toEqual(['wait_for_event', 'wait_for_duration']);++ await expectEventually(async () => {+ expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);+ });++ expect(executeAgent).toHaveBeenCalledTimes(2);+ expect(executeAgent.mock.calls[1][0].messages).toEqual([]);+ expect(+ JSON.stringify(executeAgent.mock.calls[1][0].priorMessages),+ ).toContain('The wait is over.');+ expect(await findTurnStatuses(suspension.threadId)).toEqual([+ 'completed',+ 'completed',+ ]);+ });++ it('drops a waiting triggered run once its trigger is turned off', async () => {+ const executeAgent = mockAgent(waitingResult(), replyingResult);++ await runTrigger();++ expect(await findSuspensions('AGENT_TRIGGER', agentId)).toHaveLength(1);++ await updateOneAgent({+ expectToFail: false,+ input: {+ id: agentId,+ triggers: [{ ...trigger, isActive: false }],+ },+ });++ await expectEventually(async () => {+ expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);+ });++ expect(executeAgent).toHaveBeenCalledTimes(1);++ await updateOneAgent({+ expectToFail: false,+ input: { id: agentId, triggers: [trigger] },+ });+ });++ it('answers a runAgent call whose agent waits as waiting, with its thread', async () => {+ const executeAgent = mockAgent(waitingResult(), replyingResult);++ const response = await makeMetadataApiRequest({+ query: gql`+ mutation RunAgent($input: RunAgentInput!) {+ runAgent(input: $input) {+ result+ error+ success+ isWaiting+ threadId+ }+ }+ `,+ variables: {+ input: {+ agentUniversalIdentifier,+ input: [{ role: 'user', content: 'Follow up tomorrow' }],+ },+ },+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.runAgent).toEqual({+ result: null,+ error: null,+ success: true,+ isWaiting: true,+ threadId: expect.any(String),+ });++ await expectEventually(async () => {+ expect(await findSuspensions('AGENT_API_RUN', agentId)).toEqual([]);+ });++ expect(executeAgent).toHaveBeenCalledTimes(2);+ expect(+ await findTurnStatuses(response.body.data.runAgent.threadId),+ ).toEqual(['completed', 'completed']);+ });++ it('refuses a message to a thread whose run waits, and takes it once the run finished', async () => {+ const executeAgent = mockAgent(+ waitingResult(),+ replyingResult,+ replyingResult,+ );+ const agentRunService =+ getAppProviderByClassName<AgentRunService>('AgentRunService');+ const workspace = fromWorkspaceEntityToFlat(+ await getCoreRepository<WorkspaceEntity>(WorkspaceEntity).findOneByOrFail(+ { id: workspaceId },+ ),+ );+ const callerApplication =+ await getAppProviderByClassName<ApplicationLookupService>(+ 'ApplicationLookupService',+ ).findById({ id: agentApplicationId, workspaceId });+ const thread = { key: `lead:${randomUUID()}` };+ const runOnSameThread = (content: string) =>+ agentRunService.run({+ workspace,+ requestUserWorkspaceId: null,+ requestWorkspaceMemberId: null,+ callerApplication: callerApplication ?? undefined,+ input: {+ agentUniversalIdentifier,+ input: [{ role: 'user', content }],+ thread,+ },+ });++ const waiting = await runOnSameThread('Follow up tomorrow');++ expect(waiting).toMatchObject({ success: true, isWaiting: true });++ await expect(runOnSameThread('Any news?')).rejects.toMatchObject({+ code: AiExceptionCode.THREAD_AWAITING_ANSWER,+ });++ await expectEventually(async () => {+ expect(await findSuspensions('AGENT_API_RUN', agentId)).toEqual([]);+ });++ await expect(runOnSameThread('Any news?')).resolves.toMatchObject({+ success: true,+ isWaiting: false,+ result: { response: 'Followed up' },+ threadId: waiting.threadId,+ });+ expect(executeAgent).toHaveBeenCalledTimes(3);+ });+});diff --git a/packages/twenty-shared/src/application/runAgentType.ts b/packages/twenty-shared/src/application/runAgentType.tsindex 8187b1bcc9e..f57444b1558 100644--- a/packages/twenty-shared/src/application/runAgentType.ts+++ b/packages/twenty-shared/src/application/runAgentType.ts@@ -42,5 +42,7 @@ export type RunAgentResult = {result: object | null;error: string | null;success: boolean;+ // the agent paused on a wait and goes on by itself; its reply lands in the thread+ isWaiting: boolean;threadId: string | null;};