Skip to content

The open alternative to Salesforce, designed for AI.

Run workflow, API and trigger agent turns through one engine runner (#27385)

Félix Malfait7cd16733030c
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index dea86ec62ac..82c1ab6beb6 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3975,28 +3975,18 @@ type Query {
): Object!
objectRecordCounts: [ObjectRecordCount!]!
mostlyEmptyFieldMetadataIds(objectMetadataId: UUID!): [UUID!]!
+ getToolIndex: [ToolIndexEntry!]!
+ getToolInputSchema(toolName: String!): JSON
+ previewMessageCampaignAudience(input: PreviewMessageCampaignAudienceInput!): CampaignAudiencePreviewDTO!
+ messageSuppressions(input: FindMessageSuppressionsInput!): MessageSuppressionList!
+ unsubscribeTopics: [UnsubscribeTopic!]!
+ myMessageChannels(connectedAccountId: UUID): [MessageChannel!]!
+ appMessageChannels(filter: ListAppMessageChannelsInput): [MessageChannel!]!
+ getEmailingDomains: [EmailingDomain!]!
getRoles: [Role!]!
getRole(id: UUID!): Role!
- currentWorkspace: Workspace!
- getPublicWorkspaceDataByDomain(origin: String): PublicWorkspaceData!
- getPublicWorkspaceDataById(id: UUID!): PublicWorkspaceDataSummary!
- findApplicationRegistrationByClientId(clientId: String!): PublicApplicationRegistration
- findApplicationRegistrationByUniversalIdentifier(universalIdentifier: String!): ApplicationRegistration
- findManyApplicationRegistrations: [ApplicationRegistration!]!
- findOneApplicationRegistration(id: String!): ApplicationRegistration!
- findApplicationRegistrationStats(id: String!): ApplicationRegistrationStats!
- findApplicationRegistrationVariables(applicationRegistrationId: String!): [ApplicationRegistrationVariable!]!
- applicationRegistrationTarballUrl(id: String!): String
- findClaimableApplicationRegistration(sourcePackage: String, universalIdentifier: String): ClaimableApplicationRegistration
- githubClaimAuthorizationUrl(applicationRegistrationId: String!): String!
- findManyApplications: [Application!]!
- findOneApplication(id: UUID, universalIdentifier: UUID): Application!
- findInstallApplicationJobStatus(universalIdentifier: String!): JobStatus
- findUninstallApplicationJobStatus(universalIdentifier: String!): JobStatus
- findManyMarketplaceApps(universalIdentifiers: [String!]): [MarketplaceApp!]!
- findMarketplaceAppDetail(universalIdentifier: String!): MarketplaceAppDetail!
- publicMarketplaceApps(isVetted: Boolean! = true): [MarketplaceApp!]!
- publicMarketplaceAppDetail(universalIdentifier: String!): MarketplaceAppDetail!
+ webhooks: [Webhook!]!
+ webhook(id: UUID!): Webhook
fields(
"""Limit or page results."""
paging: CursorPaging! = {first: 10}
@@ -4010,16 +4000,6 @@ type Query {
): Field!
getViewGroups(viewId: String): [ViewGroup!]!
getViewGroup(id: String!): ViewGroup
- previewMessageCampaignAudience(input: PreviewMessageCampaignAudienceInput!): CampaignAudiencePreviewDTO!
- messageSuppressions(input: FindMessageSuppressionsInput!): MessageSuppressionList!
- unsubscribeTopics: [UnsubscribeTopic!]!
- myMessageChannels(connectedAccountId: UUID): [MessageChannel!]!
- appMessageChannels(filter: ListAppMessageChannelsInput): [MessageChannel!]!
- getEmailingDomains: [EmailingDomain!]!
- getToolIndex: [ToolIndexEntry!]!
- getToolInputSchema(toolName: String!): JSON
- webhooks: [Webhook!]!
- webhook(id: UUID!): Webhook
myMessageFolders(messageChannelId: UUID): [MessageFolder!]!
myCalendarChannels(connectedAccountId: UUID): [CalendarChannel!]!
getPermissionFlags: [PermissionFlag!]!
@@ -4046,7 +4026,27 @@ type Query {
checkWorkspaceSubdomainAvailability(subdomain: String!): SubdomainAvailabilityDTO!
getWorkspaceCreationDefaults: WorkspaceCreationDefaultsDTO!
validatePasswordResetToken(passwordResetToken: String!): ValidatePasswordResetToken!
+ findApplicationRegistrationByClientId(clientId: String!): PublicApplicationRegistration
+ findApplicationRegistrationByUniversalIdentifier(universalIdentifier: String!): ApplicationRegistration
+ findManyApplicationRegistrations: [ApplicationRegistration!]!
+ findOneApplicationRegistration(id: String!): ApplicationRegistration!
+ findApplicationRegistrationStats(id: String!): ApplicationRegistrationStats!
+ findApplicationRegistrationVariables(applicationRegistrationId: String!): [ApplicationRegistrationVariable!]!
+ applicationRegistrationTarballUrl(id: String!): String
+ findClaimableApplicationRegistration(sourcePackage: String, universalIdentifier: String): ClaimableApplicationRegistration
+ githubClaimAuthorizationUrl(applicationRegistrationId: String!): String!
currentUser: User!
+ currentWorkspace: Workspace!
+ getPublicWorkspaceDataByDomain(origin: String): PublicWorkspaceData!
+ getPublicWorkspaceDataById(id: UUID!): PublicWorkspaceDataSummary!
+ findManyApplications: [Application!]!
+ findOneApplication(id: UUID, universalIdentifier: UUID): Application!
+ findInstallApplicationJobStatus(universalIdentifier: String!): JobStatus
+ findUninstallApplicationJobStatus(universalIdentifier: String!): JobStatus
+ findManyMarketplaceApps(universalIdentifiers: [String!]): [MarketplaceApp!]!
+ findMarketplaceAppDetail(universalIdentifier: String!): MarketplaceAppDetail!
+ publicMarketplaceApps(isVetted: Boolean! = true): [MarketplaceApp!]!
+ publicMarketplaceAppDetail(universalIdentifier: String!): MarketplaceAppDetail!
getSSOIdentityProviders: [FindAvailableSSOIDP!]!
eventLogs(input: EventLogQueryInput!): EventLogQueryResult!
pieChartData(input: PieChartDataInput!): PieChartData!
@@ -4310,50 +4310,7 @@ type Mutation {
updateManyObjects(inputs: [UpdateOneObjectInput!]!): [Object!]!
createOneIndex(input: CreateOneIndexInput!): Index!
deleteOneIndex(input: DeleteOneIndexInput!): Index!
- updateWorkspaceMemberRole(workspaceMemberId: UUID!, roleId: UUID!): WorkspaceMember!
- createOneRole(createRoleInput: CreateRoleInput!): Role!
- updateOneRole(updateRoleInput: UpdateRoleInput!): Role!
- deleteOneRole(roleId: UUID!): String!
- upsertObjectPermissions(upsertObjectPermissionsInput: UpsertObjectPermissionsInput!): [ObjectPermission!]!
- upsertPermissionFlags(upsertPermissionFlagsInput: UpsertPermissionFlagsInput!): [RolePermissionFlag!]!
- upsertFieldPermissions(upsertFieldPermissionsInput: UpsertFieldPermissionsInput!): [FieldPermission!]!
- upsertRowLevelPermissionPredicates(input: UpsertRowLevelPermissionPredicatesInput!): UpsertRowLevelPermissionPredicatesResult!
- assignRoleToAgent(agentId: UUID!, roleId: UUID!): Boolean!
- removeRoleFromAgent(agentId: UUID!): Boolean!
- activateWorkspace(data: ActivateWorkspaceInput!): Workspace!
- updateWorkspace(data: UpdateWorkspaceInput!): Workspace!
- updateWorkspaceAllowedIframeOrigins(data: UpdateWorkspaceAllowedIframeOriginsInput!): Workspace!
- deleteCurrentWorkspace: Workspace!
- checkCustomDomainValidRecords: DomainValidRecords
- enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult!
- upgradeApplication(appRegistrationId: String!, targetVersion: String!): Boolean!
- createApplicationRegistration(input: CreateApplicationRegistrationInput!): CreateApplicationRegistration!
- updateApplicationRegistration(input: UpdateApplicationRegistrationInput!): ApplicationRegistration!
- deleteApplicationRegistration(id: String!): Boolean!
- rotateApplicationRegistrationClientSecret(id: String!): RotateClientSecret!
- updateApplicationRegistrationVariable(input: UpdateApplicationRegistrationVariableInput!): ApplicationRegistrationVariable!
- completeAppTarballUpload(fileId: UUID!): ApplicationRegistration!
- uploadAppTarball(file: Upload!, universalIdentifier: String @deprecated(reason: "Ignored: the application universalIdentifier is read from the tarball manifest.")): ApplicationRegistration! @deprecated(reason: "Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage.")
- claimApplicationRegistrationOwnership(applicationRegistrationId: String!): ApplicationRegistration!
- transferApplicationRegistrationOwnership(applicationRegistrationId: String!, targetWorkspaceSubdomain: String!): ApplicationRegistration!
- grantApplicationCapabilities(input: GrantApplicationCapabilitiesInput!): ApplicationCapabilityGrant!
- installMarketplaceApp(universalIdentifier: String!, version: String): Boolean! @deprecated(reason: "Use installApplication instead")
- installApplication(universalIdentifier: String!, version: String): Application!
- triggerInstallApplicationJob(input: TriggerInstallApplicationJobInput!): TriggerInstallApplicationJobResult!
- triggerUninstallApplicationJob(input: TriggerUninstallApplicationJobInput!): TriggerUninstallApplicationJobResult!
- updateApplication(id: UUID!, input: UpdateApplicationInput!): Application!
- uninstallApplication(universalIdentifier: String!): Boolean!
- syncMarketplaceCatalog: Boolean!
- runApplicationHealthCheck(applicationId: UUID!): ApplicationHealthCheckResult
- createOneField(input: CreateOneFieldMetadataInput!): Field!
- updateOneField(input: UpdateOneFieldMetadataInput!): Field!
- deleteOneField(input: DeleteOneFieldInput!): Field!
- createViewGroup(input: CreateViewGroupInput!): ViewGroup!
- createManyViewGroups(inputs: [CreateViewGroupInput!]!): [ViewGroup!]!
- updateViewGroup(input: UpdateViewGroupInput!): ViewGroup!
- updateManyViewGroups(inputs: [UpdateViewGroupInput!]!): [ViewGroup!]!
- deleteViewGroup(input: DeleteViewGroupInput!): ViewGroup!
- destroyViewGroup(input: DestroyViewGroupInput!): ViewGroup!
+ runAgent(input: RunAgentInput!): RunAgentResult!
sendMessageCampaign(input: SendMessageCampaignInput!): SendMessageCampaignOutputDTO!
cancelMessageCampaign(input: CancelMessageCampaignInput!): CancelMessageCampaignOutputDTO!
sendMessageCampaignTest(input: SendMessageCampaignTestInput!): SendEmailViaDomainOutput!
@@ -4374,10 +4331,28 @@ type Mutation {
createEmailingDomain(input: CreateEmailingDomainInput!): EmailingDomain!
deleteEmailingDomain(id: String!): Boolean!
verifyEmailingDomain(id: String!): EmailingDomain!
+ updateWorkspaceMemberRole(workspaceMemberId: UUID!, roleId: UUID!): WorkspaceMember!
+ createOneRole(createRoleInput: CreateRoleInput!): Role!
+ updateOneRole(updateRoleInput: UpdateRoleInput!): Role!
+ deleteOneRole(roleId: UUID!): String!
+ upsertObjectPermissions(upsertObjectPermissionsInput: UpsertObjectPermissionsInput!): [ObjectPermission!]!
+ upsertPermissionFlags(upsertPermissionFlagsInput: UpsertPermissionFlagsInput!): [RolePermissionFlag!]!
+ upsertFieldPermissions(upsertFieldPermissionsInput: UpsertFieldPermissionsInput!): [FieldPermission!]!
+ upsertRowLevelPermissionPredicates(input: UpsertRowLevelPermissionPredicatesInput!): UpsertRowLevelPermissionPredicatesResult!
+ assignRoleToAgent(agentId: UUID!, roleId: UUID!): Boolean!
+ removeRoleFromAgent(agentId: UUID!): Boolean!
createWebhook(input: CreateWebhookInput!): Webhook!
updateWebhook(input: UpdateWebhookInput!): Webhook!
deleteWebhook(id: UUID!): Webhook!
- runAgent(input: RunAgentInput!): RunAgentResult!
+ createOneField(input: CreateOneFieldMetadataInput!): Field!
+ updateOneField(input: UpdateOneFieldMetadataInput!): Field!
+ deleteOneField(input: DeleteOneFieldInput!): Field!
+ createViewGroup(input: CreateViewGroupInput!): ViewGroup!
+ createManyViewGroups(inputs: [CreateViewGroupInput!]!): [ViewGroup!]!
+ updateViewGroup(input: UpdateViewGroupInput!): ViewGroup!
+ updateManyViewGroups(inputs: [UpdateViewGroupInput!]!): [ViewGroup!]!
+ deleteViewGroup(input: DeleteViewGroupInput!): ViewGroup!
+ destroyViewGroup(input: DestroyViewGroupInput!): ViewGroup!
updateMessageFolder(input: UpdateMessageFolderInput!): MessageFolder!
updateMessageFolders(input: UpdateMessageFoldersInput!): [MessageFolder!]!
updateCalendarChannel(input: UpdateCalendarChannelInput!): CalendarChannel!
@@ -4431,6 +4406,15 @@ type Mutation {
generatePlaygroundToken: AuthToken!
emailPasswordResetLink(email: String!, workspaceId: UUID, captchaToken: String): EmailPasswordResetLink!
updatePasswordViaResetToken(passwordResetToken: String!, newPassword: String!): InvalidatePassword!
+ createApplicationRegistration(input: CreateApplicationRegistrationInput!): CreateApplicationRegistration!
+ updateApplicationRegistration(input: UpdateApplicationRegistrationInput!): ApplicationRegistration!
+ deleteApplicationRegistration(id: String!): Boolean!
+ rotateApplicationRegistrationClientSecret(id: String!): RotateClientSecret!
+ updateApplicationRegistrationVariable(input: UpdateApplicationRegistrationVariableInput!): ApplicationRegistrationVariable!
+ completeAppTarballUpload(fileId: UUID!): ApplicationRegistration!
+ uploadAppTarball(file: Upload!, universalIdentifier: String @deprecated(reason: "Ignored: the application universalIdentifier is read from the tarball manifest.")): ApplicationRegistration! @deprecated(reason: "Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage.")
+ claimApplicationRegistrationOwnership(applicationRegistrationId: String!): ApplicationRegistration!
+ transferApplicationRegistrationOwnership(applicationRegistrationId: String!, targetWorkspaceSubdomain: String!): ApplicationRegistration!
initiateOTPProvisioning(loginToken: String!, origin: String!): InitiateTwoFactorAuthenticationProvisioning!
initiateOTPProvisioningForAuthenticatedUser: InitiateTwoFactorAuthenticationProvisioning!
deleteTwoFactorAuthenticationMethod(twoFactorAuthenticationMethodId: UUID!): DeleteTwoFactorAuthenticationMethod!
@@ -4440,6 +4424,22 @@ type Mutation {
updateWorkspaceMemberSettings(input: UpdateWorkspaceMemberSettingsInput!): Boolean!
updateUserEmail(newEmail: String!, verifyEmailRedirectPath: String): Boolean!
resendEmailVerificationToken(email: String!, origin: String!): ResendEmailVerificationToken!
+ activateWorkspace(data: ActivateWorkspaceInput!): Workspace!
+ updateWorkspace(data: UpdateWorkspaceInput!): Workspace!
+ updateWorkspaceAllowedIframeOrigins(data: UpdateWorkspaceAllowedIframeOriginsInput!): Workspace!
+ deleteCurrentWorkspace: Workspace!
+ checkCustomDomainValidRecords: DomainValidRecords
+ enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult!
+ upgradeApplication(appRegistrationId: String!, targetVersion: String!): Boolean!
+ grantApplicationCapabilities(input: GrantApplicationCapabilitiesInput!): ApplicationCapabilityGrant!
+ installMarketplaceApp(universalIdentifier: String!, version: String): Boolean! @deprecated(reason: "Use installApplication instead")
+ installApplication(universalIdentifier: String!, version: String): Application!
+ triggerInstallApplicationJob(input: TriggerInstallApplicationJobInput!): TriggerInstallApplicationJobResult!
+ triggerUninstallApplicationJob(input: TriggerUninstallApplicationJobInput!): TriggerUninstallApplicationJobResult!
+ updateApplication(id: UUID!, input: UpdateApplicationInput!): Application!
+ uninstallApplication(universalIdentifier: String!): Boolean!
+ syncMarketplaceCatalog: Boolean!
+ runApplicationHealthCheck(applicationId: UUID!): ApplicationHealthCheckResult
createOIDCIdentityProvider(input: SetupOIDCSsoInput!): SetupSso!
createSAMLIdentityProvider(input: SetupSAMLSsoInput!): SetupSso!
deleteSSOIdentityProvider(input: DeleteSsoInput!): DeleteSso!
@@ -5177,187 +5177,261 @@ input DeleteOneIndexInput {
id: UUID!
}
-input CreateRoleInput {
- id: String
- label: String!
- description: String
- icon: String
- canUpdateAllSettings: Boolean
- canAccessAllTools: Boolean
- canReadAllObjectRecords: Boolean
- canUpdateAllObjectRecords: Boolean
- canSoftDeleteAllObjectRecords: Boolean
- canDestroyAllObjectRecords: Boolean
- canBeAssignedToUsers: Boolean
- canBeAssignedToAgents: Boolean
- canBeAssignedToApiKeys: Boolean
+input RunAgentInput {
+ agentUniversalIdentifier: String!
+ prompt: String @deprecated(reason: "Use input instead.")
+ runAsWorkspaceMemberId: UUID
+ messages: [RunAgentMessageInput!] @deprecated(reason: "Use input instead.")
+ input: [RunAgentMessageInput!]
+ additionalInstructions: String
+ thread: RunAgentThreadInput
}
-input UpdateRoleInput {
- update: UpdateRolePayload!
-
- """The id of the role to update"""
- id: UUID!
+input RunAgentMessageInput {
+ role: RunAgentMessageRole!
+ content: String!
+ attachments: [RunAgentMessageAttachmentInput!]
}
-input UpdateRolePayload {
- label: String
- description: String
- icon: String
- canUpdateAllSettings: Boolean
- canAccessAllTools: Boolean
- canReadAllObjectRecords: Boolean
- canUpdateAllObjectRecords: Boolean
- canSoftDeleteAllObjectRecords: Boolean
- canDestroyAllObjectRecords: Boolean
- canBeAssignedToUsers: Boolean
- canBeAssignedToAgents: Boolean
- canBeAssignedToApiKeys: Boolean
+enum RunAgentMessageRole {
+ user
+ assistant
}
-input UpsertObjectPermissionsInput {
- roleId: UUID!
- objectPermissions: [ObjectPermissionInput!]!
+input RunAgentMessageAttachmentInput {
+ fileId: UUID!
+ filename: String
}
-input ObjectPermissionInput {
- objectMetadataId: UUID!
- canReadObjectRecords: Boolean
- canUpdateObjectRecords: Boolean
- canSoftDeleteObjectRecords: Boolean
- canDestroyObjectRecords: Boolean
+input RunAgentThreadInput {
+ key: String!
+ title: String
}
-input UpsertPermissionFlagsInput {
- roleId: UUID!
- permissionFlagKeys: [String!]!
+input SendMessageCampaignInput {
+ campaignId: String!
+ scheduledAt: DateTime
}
-input UpsertFieldPermissionsInput {
- roleId: UUID!
- fieldPermissions: [FieldPermissionInput!]!
+input CancelMessageCampaignInput {
+ campaignId: String!
}
-input FieldPermissionInput {
- objectMetadataId: UUID!
- fieldMetadataId: UUID!
- canReadFieldValue: Boolean
- canUpdateFieldValue: Boolean
+input SendMessageCampaignTestInput {
+ toAddress: String!
+ unsubscribeTopicId: String
+ subject: String!
+ body: String!
+ fromAddress: String!
}
-input UpsertRowLevelPermissionPredicatesInput {
- roleId: UUID!
- objectMetadataId: UUID!
- predicates: [RowLevelPermissionPredicateInput!]!
- predicateGroups: [RowLevelPermissionPredicateGroupInput!]!
+input CreateMessageSuppressionInput {
+ emailAddress: String!
+ unsubscribeTopicId: UUID
}
-input RowLevelPermissionPredicateInput {
- id: UUID
- fieldMetadataId: UUID!
- operand: RowLevelPermissionPredicateOperand!
- value: JSON
- subFieldName: String
- workspaceMemberFieldMetadataId: String
- workspaceMemberSubFieldName: String
- rowLevelPermissionPredicateGroupId: UUID
- positionInRowLevelPermissionPredicateGroup: Float
+input CreateUnsubscribeTopicInput {
+ name: String!
+ description: String
+ visibility: UnsubscribeTopicVisibility
}
-input RowLevelPermissionPredicateGroupInput {
- id: UUID
- objectMetadataId: UUID!
- parentRowLevelPermissionPredicateGroupId: UUID
- logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator!
- positionInRowLevelPermissionPredicateGroup: Float
+input UpdateUnsubscribeTopicInput {
+ id: String!
+ name: String
+ description: String
+ visibility: UnsubscribeTopicVisibility
}
-input ActivateWorkspaceInput {
- """
- Deprecated: the workspace name is set at creation (signUpInNewWorkspace) and this field is ignored during activation. Kept for backward compatibility.
- """
+input UpdateMessageChannelInput {
+ id: UUID!
+ update: UpdateMessageChannelInputUpdates!
+}
+
+input UpdateMessageChannelInputUpdates {
+ visibility: MessageChannelVisibility
+ isContactAutoCreationEnabled: Boolean
+ contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy
+ messageFolderImportPolicy: MessageFolderImportPolicy
+ isSyncEnabled: Boolean
+ excludeNonProfessionalEmails: Boolean
+ excludeGroupEmails: Boolean
+}
+
+input CreateEmailGroupChannelInput {
+ handle: String!
displayName: String
}
-input UpdateWorkspaceInput {
- subdomain: String
- customDomain: String
+input UpdateEmailGroupChannelInput {
+ id: UUID!
displayName: String
- logo: String
- inviteHash: String
- isPublicInviteLinkEnabled: Boolean
- isCampaignClickTrackingEnabled: Boolean
- workspaceDiscoverability: WorkspaceDiscoverability
- allowImpersonation: Boolean
- isGoogleAuthEnabled: Boolean
- isMicrosoftAuthEnabled: Boolean
- isPasswordAuthEnabled: Boolean
- isGoogleAuthBypassEnabled: Boolean
- isMicrosoftAuthBypassEnabled: Boolean
- isPasswordAuthBypassEnabled: Boolean
- defaultRoleId: UUID
- isTwoFactorAuthenticationEnforced: Boolean
- trashRetentionDays: Float
- eventLogRetentionDays: Float
- aiChatModelTier: AiModelTier
- aiAgentModelTier: AiModelTier
- isAutoModelSelectionEnabled: Boolean
- aiModelIdByTier: JSON
- aiEvaluationModelId: String
- aiAdditionalInstructions: String
- editableProfileFields: [String!]
- isInternalMessagesImportEnabled: Boolean
}
-input UpdateWorkspaceAllowedIframeOriginsInput {
- operation: String!
- origin: String!
+input CreateAppMessageChannelInput {
+ connectedAccountId: UUID!
+ handle: String!
+ displayName: String
+ visibility: MessageChannelVisibility!
}
-input CreateApplicationRegistrationInput {
- name: String!
- universalIdentifier: String
- oAuthRedirectUris: [String!]
- oAuthScopes: [String!]
+input UpdateAppMessageChannelInput {
+ id: UUID!
+ displayName: String
+ visibility: MessageChannelVisibility
+ isSyncEnabled: Boolean
}
-input UpdateApplicationRegistrationInput {
- id: String!
- update: UpdateApplicationRegistrationPayload!
+input IngestAppMessagesInput {
+ messageChannelId: UUID!
+ messages: [AppMessageInput!]!
}
-input UpdateApplicationRegistrationPayload {
- name: String
- oAuthRedirectUris: [String!]
- oAuthScopes: [String!]
+input AppMessageInput {
+ externalId: String!
+ threadExternalId: String!
+ subject: String
+ text: String!
+ receivedAt: DateTime!
+ participants: [AppMessageParticipantInput!]!
}
-input UpdateApplicationRegistrationVariableInput {
- id: String!
- update: UpdateApplicationRegistrationVariablePayload!
+input AppMessageParticipantInput {
+ role: MessageParticipantRole!
+ handle: String!
+ displayName: String
+ personId: UUID
+ workspaceMemberId: UUID
}
-input UpdateApplicationRegistrationVariablePayload {
- value: String
- resetValue: Boolean
+enum MessageParticipantRole {
+ FROM
+ TO
+ CC
+ BCC
+ REPLY_TO
+}
+
+input CreateEmailingDomainInput {
+ domain: String!
+}
+
+input CreateRoleInput {
+ id: String
+ label: String!
description: String
+ icon: String
+ canUpdateAllSettings: Boolean
+ canAccessAllTools: Boolean
+ canReadAllObjectRecords: Boolean
+ canUpdateAllObjectRecords: Boolean
+ canSoftDeleteAllObjectRecords: Boolean
+ canDestroyAllObjectRecords: Boolean
+ canBeAssignedToUsers: Boolean
+ canBeAssignedToAgents: Boolean
+ canBeAssignedToApiKeys: Boolean
}
-input GrantApplicationCapabilitiesInput {
- applicationId: UUID!
- capabilities: [String!]!
+input UpdateRoleInput {
+ update: UpdateRolePayload!
+
+ """The id of the role to update"""
+ id: UUID!
}
-input TriggerInstallApplicationJobInput {
- universalIdentifier: String!
+input UpdateRolePayload {
+ label: String
+ description: String
+ icon: String
+ canUpdateAllSettings: Boolean
+ canAccessAllTools: Boolean
+ canReadAllObjectRecords: Boolean
+ canUpdateAllObjectRecords: Boolean
+ canSoftDeleteAllObjectRecords: Boolean
+ canDestroyAllObjectRecords: Boolean
+ canBeAssignedToUsers: Boolean
+ canBeAssignedToAgents: Boolean
+ canBeAssignedToApiKeys: Boolean
}
-input TriggerUninstallApplicationJobInput {
- universalIdentifier: String!
+input UpsertObjectPermissionsInput {
+ roleId: UUID!
+ objectPermissions: [ObjectPermissionInput!]!
}
-input UpdateApplicationInput {
- autoUpgrade: Boolean
+input ObjectPermissionInput {
+ objectMetadataId: UUID!
+ canReadObjectRecords: Boolean
+ canUpdateObjectRecords: Boolean
+ canSoftDeleteObjectRecords: Boolean
+ canDestroyObjectRecords: Boolean
+}
+
+input UpsertPermissionFlagsInput {
+ roleId: UUID!
+ permissionFlagKeys: [String!]!
+}
+
+input UpsertFieldPermissionsInput {
+ roleId: UUID!
+ fieldPermissions: [FieldPermissionInput!]!
+}
+
+input FieldPermissionInput {
+ objectMetadataId: UUID!
+ fieldMetadataId: UUID!
+ canReadFieldValue: Boolean
+ canUpdateFieldValue: Boolean
+}
+
+input UpsertRowLevelPermissionPredicatesInput {
+ roleId: UUID!
+ objectMetadataId: UUID!
+ predicates: [RowLevelPermissionPredicateInput!]!
+ predicateGroups: [RowLevelPermissionPredicateGroupInput!]!
+}
+
+input RowLevelPermissionPredicateInput {
+ id: UUID
+ fieldMetadataId: UUID!
+ operand: RowLevelPermissionPredicateOperand!
+ value: JSON
+ subFieldName: String
+ workspaceMemberFieldMetadataId: String
+ workspaceMemberSubFieldName: String
+ rowLevelPermissionPredicateGroupId: UUID
+ positionInRowLevelPermissionPredicateGroup: Float
+}
+
+input RowLevelPermissionPredicateGroupInput {
+ id: UUID
+ objectMetadataId: UUID!
+ parentRowLevelPermissionPredicateGroupId: UUID
+ logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator!
+ positionInRowLevelPermissionPredicateGroup: Float
+}
+
+input CreateWebhookInput {
+ id: UUID
+ targetUrl: String!
+ operations: [String!]!
+ description: String
+ secret: String
+}
+
+input UpdateWebhookInput {
+ """The id of the webhook to update"""
+ id: UUID!
+
+ """The webhook fields to update"""
+ update: UpdateWebhookInputUpdates!
+}
+
+input UpdateWebhookInputUpdates {
+ targetUrl: String
+ operations: [String!]
+ description: String
+ secret: String
}
input CreateOneFieldMetadataInput {
@@ -5458,168 +5532,6 @@ input DestroyViewGroupInput {
id: UUID!
}
-input SendMessageCampaignInput {
- campaignId: String!
- scheduledAt: DateTime
-}
-
-input CancelMessageCampaignInput {
- campaignId: String!
-}
-
-input SendMessageCampaignTestInput {
- toAddress: String!
- unsubscribeTopicId: String
- subject: String!
- body: String!
- fromAddress: String!
-}
-
-input CreateMessageSuppressionInput {
- emailAddress: String!
- unsubscribeTopicId: UUID
-}
-
-input CreateUnsubscribeTopicInput {
- name: String!
- description: String
- visibility: UnsubscribeTopicVisibility
-}
-
-input UpdateUnsubscribeTopicInput {
- id: String!
- name: String
- description: String
- visibility: UnsubscribeTopicVisibility
-}
-
-input UpdateMessageChannelInput {
- id: UUID!
- update: UpdateMessageChannelInputUpdates!
-}
-
-input UpdateMessageChannelInputUpdates {
- visibility: MessageChannelVisibility
- isContactAutoCreationEnabled: Boolean
- contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy
- messageFolderImportPolicy: MessageFolderImportPolicy
- isSyncEnabled: Boolean
- excludeNonProfessionalEmails: Boolean
- excludeGroupEmails: Boolean
-}
-
-input CreateEmailGroupChannelInput {
- handle: String!
- displayName: String
-}
-
-input UpdateEmailGroupChannelInput {
- id: UUID!
- displayName: String
-}
-
-input CreateAppMessageChannelInput {
- connectedAccountId: UUID!
- handle: String!
- displayName: String
- visibility: MessageChannelVisibility!
-}
-
-input UpdateAppMessageChannelInput {
- id: UUID!
- displayName: String
- visibility: MessageChannelVisibility
- isSyncEnabled: Boolean
-}
-
-input IngestAppMessagesInput {
- messageChannelId: UUID!
- messages: [AppMessageInput!]!
-}
-
-input AppMessageInput {
- externalId: String!
- threadExternalId: String!
- subject: String
- text: String!
- receivedAt: DateTime!
- participants: [AppMessageParticipantInput!]!
-}
-
-input AppMessageParticipantInput {
- role: MessageParticipantRole!
- handle: String!
- displayName: String
- personId: UUID
- workspaceMemberId: UUID
-}
-
-enum MessageParticipantRole {
- FROM
- TO
- CC
- BCC
- REPLY_TO
-}
-
-input CreateEmailingDomainInput {
- domain: String!
-}
-
-input CreateWebhookInput {
- id: UUID
- targetUrl: String!
- operations: [String!]!
- description: String
- secret: String
-}
-
-input UpdateWebhookInput {
- """The id of the webhook to update"""
- id: UUID!
-
- """The webhook fields to update"""
- update: UpdateWebhookInputUpdates!
-}
-
-input UpdateWebhookInputUpdates {
- targetUrl: String
- operations: [String!]
- description: String
- secret: String
-}
-
-input RunAgentInput {
- agentUniversalIdentifier: String!
- prompt: String @deprecated(reason: "Use input instead.")
- runAsWorkspaceMemberId: UUID
- messages: [RunAgentMessageInput!] @deprecated(reason: "Use input instead.")
- input: [RunAgentMessageInput!]
- additionalInstructions: String
- thread: RunAgentThreadInput
-}
-
-input RunAgentMessageInput {
- role: RunAgentMessageRole!
- content: String!
- attachments: [RunAgentMessageAttachmentInput!]
-}
-
-enum RunAgentMessageRole {
- user
- assistant
-}
-
-input RunAgentMessageAttachmentInput {
- fileId: UUID!
- filename: String
-}
-
-input RunAgentThreadInput {
- key: String!
- title: String
-}
-
input UpdateMessageFolderInput {
id: UUID!
update: UpdateMessageFolderInputUpdates!
@@ -5755,11 +5667,99 @@ input SignUpInNewWorkspaceInput {
subdomain: String
}
+input CreateApplicationRegistrationInput {
+ name: String!
+ universalIdentifier: String
+ oAuthRedirectUris: [String!]
+ oAuthScopes: [String!]
+}
+
+input UpdateApplicationRegistrationInput {
+ id: String!
+ update: UpdateApplicationRegistrationPayload!
+}
+
+input UpdateApplicationRegistrationPayload {
+ name: String
+ oAuthRedirectUris: [String!]
+ oAuthScopes: [String!]
+}
+
+input UpdateApplicationRegistrationVariableInput {
+ id: String!
+ update: UpdateApplicationRegistrationVariablePayload!
+}
+
+input UpdateApplicationRegistrationVariablePayload {
+ value: String
+ resetValue: Boolean
+ description: String
+}
+
input UpdateWorkspaceMemberSettingsInput {
workspaceMemberId: UUID!
update: JSON!
}
+input ActivateWorkspaceInput {
+ """
+ Deprecated: the workspace name is set at creation (signUpInNewWorkspace) and this field is ignored during activation. Kept for backward compatibility.
+ """
+ displayName: String
+}
+
+input UpdateWorkspaceInput {
+ subdomain: String
+ customDomain: String
+ displayName: String
+ logo: String
+ inviteHash: String
+ isPublicInviteLinkEnabled: Boolean
+ isCampaignClickTrackingEnabled: Boolean
+ workspaceDiscoverability: WorkspaceDiscoverability
+ allowImpersonation: Boolean
+ isGoogleAuthEnabled: Boolean
+ isMicrosoftAuthEnabled: Boolean
+ isPasswordAuthEnabled: Boolean
+ isGoogleAuthBypassEnabled: Boolean
+ isMicrosoftAuthBypassEnabled: Boolean
+ isPasswordAuthBypassEnabled: Boolean
+ defaultRoleId: UUID
+ isTwoFactorAuthenticationEnforced: Boolean
+ trashRetentionDays: Float
+ eventLogRetentionDays: Float
+ aiChatModelTier: AiModelTier
+ aiAgentModelTier: AiModelTier
+ isAutoModelSelectionEnabled: Boolean
+ aiModelIdByTier: JSON
+ aiEvaluationModelId: String
+ aiAdditionalInstructions: String
+ editableProfileFields: [String!]
+ isInternalMessagesImportEnabled: Boolean
+}
+
+input UpdateWorkspaceAllowedIframeOriginsInput {
+ operation: String!
+ origin: String!
+}
+
+input GrantApplicationCapabilitiesInput {
+ applicationId: UUID!
+ capabilities: [String!]!
+}
+
+input TriggerInstallApplicationJobInput {
+ universalIdentifier: String!
+}
+
+input TriggerUninstallApplicationJobInput {
+ universalIdentifier: String!
+}
+
+input UpdateApplicationInput {
+ autoUpgrade: Boolean
+}
+
input SetupOIDCSsoInput {
name: String!
issuer: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index fb7dcc830e3..70988196560 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -3463,42 +3463,22 @@ export interface Query {
object: Object
objectRecordCounts: ObjectRecordCount[]
mostlyEmptyFieldMetadataIds: Scalars['UUID'][]
- getRoles: Role[]
- getRole: Role
- currentWorkspace: Workspace
- getPublicWorkspaceDataByDomain: PublicWorkspaceData
- getPublicWorkspaceDataById: PublicWorkspaceDataSummary
- findApplicationRegistrationByClientId?: PublicApplicationRegistration
- findApplicationRegistrationByUniversalIdentifier?: ApplicationRegistration
- findManyApplicationRegistrations: ApplicationRegistration[]
- findOneApplicationRegistration: ApplicationRegistration
- findApplicationRegistrationStats: ApplicationRegistrationStats
- findApplicationRegistrationVariables: ApplicationRegistrationVariable[]
- applicationRegistrationTarballUrl?: Scalars['String']
- findClaimableApplicationRegistration?: ClaimableApplicationRegistration
- githubClaimAuthorizationUrl: Scalars['String']
- findManyApplications: Application[]
- findOneApplication: Application
- findInstallApplicationJobStatus?: JobStatus
- findUninstallApplicationJobStatus?: JobStatus
- findManyMarketplaceApps: MarketplaceApp[]
- findMarketplaceAppDetail: MarketplaceAppDetail
- publicMarketplaceApps: MarketplaceApp[]
- publicMarketplaceAppDetail: MarketplaceAppDetail
- fields: FieldConnection
- field: Field
- getViewGroups: ViewGroup[]
- getViewGroup?: ViewGroup
+ getToolIndex: ToolIndexEntry[]
+ getToolInputSchema?: Scalars['JSON']
previewMessageCampaignAudience: CampaignAudiencePreviewDTO
messageSuppressions: MessageSuppressionList
unsubscribeTopics: UnsubscribeTopic[]
myMessageChannels: MessageChannel[]
appMessageChannels: MessageChannel[]
getEmailingDomains: EmailingDomain[]
- getToolIndex: ToolIndexEntry[]
- getToolInputSchema?: Scalars['JSON']
+ getRoles: Role[]
+ getRole: Role
webhooks: Webhook[]
webhook?: Webhook
+ fields: FieldConnection
+ field: Field
+ getViewGroups: ViewGroup[]
+ getViewGroup?: ViewGroup
myMessageFolders: MessageFolder[]
myCalendarChannels: CalendarChannel[]
getPermissionFlags: PermissionFlag[]
@@ -3525,7 +3505,27 @@ export interface Query {
checkWorkspaceSubdomainAvailability: SubdomainAvailabilityDTO
getWorkspaceCreationDefaults: WorkspaceCreationDefaultsDTO
validatePasswordResetToken: ValidatePasswordResetToken
+ findApplicationRegistrationByClientId?: PublicApplicationRegistration
+ findApplicationRegistrationByUniversalIdentifier?: ApplicationRegistration
+ findManyApplicationRegistrations: ApplicationRegistration[]
+ findOneApplicationRegistration: ApplicationRegistration
+ findApplicationRegistrationStats: ApplicationRegistrationStats
+ findApplicationRegistrationVariables: ApplicationRegistrationVariable[]
+ applicationRegistrationTarballUrl?: Scalars['String']
+ findClaimableApplicationRegistration?: ClaimableApplicationRegistration
+ githubClaimAuthorizationUrl: Scalars['String']
currentUser: User
+ currentWorkspace: Workspace
+ getPublicWorkspaceDataByDomain: PublicWorkspaceData
+ getPublicWorkspaceDataById: PublicWorkspaceDataSummary
+ findManyApplications: Application[]
+ findOneApplication: Application
+ findInstallApplicationJobStatus?: JobStatus
+ findUninstallApplicationJobStatus?: JobStatus
+ findManyMarketplaceApps: MarketplaceApp[]
+ findMarketplaceAppDetail: MarketplaceAppDetail
+ publicMarketplaceApps: MarketplaceApp[]
+ publicMarketplaceAppDetail: MarketplaceAppDetail
getSSOIdentityProviders: FindAvailableSSOIDP[]
eventLogs: EventLogQueryResult
pieChartData: PieChartData
@@ -3664,52 +3664,7 @@ export interface Mutation {
updateManyObjects: Object[]
createOneIndex: Index
deleteOneIndex: Index
- updateWorkspaceMemberRole: WorkspaceMember
- createOneRole: Role
- updateOneRole: Role
- deleteOneRole: Scalars['String']
- upsertObjectPermissions: ObjectPermission[]
- upsertPermissionFlags: RolePermissionFlag[]
- upsertFieldPermissions: FieldPermission[]
- upsertRowLevelPermissionPredicates: UpsertRowLevelPermissionPredicatesResult
- assignRoleToAgent: Scalars['Boolean']
- removeRoleFromAgent: Scalars['Boolean']
- activateWorkspace: Workspace
- updateWorkspace: Workspace
- updateWorkspaceAllowedIframeOrigins: Workspace
- deleteCurrentWorkspace: Workspace
- checkCustomDomainValidRecords?: DomainValidRecords
- enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult
- upgradeApplication: Scalars['Boolean']
- createApplicationRegistration: CreateApplicationRegistration
- updateApplicationRegistration: ApplicationRegistration
- deleteApplicationRegistration: Scalars['Boolean']
- rotateApplicationRegistrationClientSecret: RotateClientSecret
- updateApplicationRegistrationVariable: ApplicationRegistrationVariable
- completeAppTarballUpload: ApplicationRegistration
- /** @deprecated Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage. */
- uploadAppTarball: ApplicationRegistration
- claimApplicationRegistrationOwnership: ApplicationRegistration
- transferApplicationRegistrationOwnership: ApplicationRegistration
- grantApplicationCapabilities: ApplicationCapabilityGrant
- /** @deprecated Use installApplication instead */
- installMarketplaceApp: Scalars['Boolean']
- installApplication: Application
- triggerInstallApplicationJob: TriggerInstallApplicationJobResult
- triggerUninstallApplicationJob: TriggerUninstallApplicationJobResult
- updateApplication: Application
- uninstallApplication: Scalars['Boolean']
- syncMarketplaceCatalog: Scalars['Boolean']
- runApplicationHealthCheck?: ApplicationHealthCheckResult
- createOneField: Field
- updateOneField: Field
- deleteOneField: Field
- createViewGroup: ViewGroup
- createManyViewGroups: ViewGroup[]
- updateViewGroup: ViewGroup
- updateManyViewGroups: ViewGroup[]
- deleteViewGroup: ViewGroup
- destroyViewGroup: ViewGroup
+ runAgent: RunAgentResult
sendMessageCampaign: SendMessageCampaignOutputDTO
cancelMessageCampaign: CancelMessageCampaignOutputDTO
sendMessageCampaignTest: SendEmailViaDomainOutput
@@ -3730,10 +3685,28 @@ export interface Mutation {
createEmailingDomain: EmailingDomain
deleteEmailingDomain: Scalars['Boolean']
verifyEmailingDomain: EmailingDomain
+ updateWorkspaceMemberRole: WorkspaceMember
+ createOneRole: Role
+ updateOneRole: Role
+ deleteOneRole: Scalars['String']
+ upsertObjectPermissions: ObjectPermission[]
+ upsertPermissionFlags: RolePermissionFlag[]
+ upsertFieldPermissions: FieldPermission[]
+ upsertRowLevelPermissionPredicates: UpsertRowLevelPermissionPredicatesResult
+ assignRoleToAgent: Scalars['Boolean']
+ removeRoleFromAgent: Scalars['Boolean']
createWebhook: Webhook
updateWebhook: Webhook
deleteWebhook: Webhook
- runAgent: RunAgentResult
+ createOneField: Field
+ updateOneField: Field
+ deleteOneField: Field
+ createViewGroup: ViewGroup
+ createManyViewGroups: ViewGroup[]
+ updateViewGroup: ViewGroup
+ updateManyViewGroups: ViewGroup[]
+ deleteViewGroup: ViewGroup
+ destroyViewGroup: ViewGroup
updateMessageFolder: MessageFolder
updateMessageFolders: MessageFolder[]
updateCalendarChannel: CalendarChannel
@@ -3789,6 +3762,16 @@ export interface Mutation {
generatePlaygroundToken: AuthToken
emailPasswordResetLink: EmailPasswordResetLink
updatePasswordViaResetToken: InvalidatePassword
+ createApplicationRegistration: CreateApplicationRegistration
+ updateApplicationRegistration: ApplicationRegistration
+ deleteApplicationRegistration: Scalars['Boolean']
+ rotateApplicationRegistrationClientSecret: RotateClientSecret
+ updateApplicationRegistrationVariable: ApplicationRegistrationVariable
+ completeAppTarballUpload: ApplicationRegistration
+ /** @deprecated Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage. */
+ uploadAppTarball: ApplicationRegistration
+ claimApplicationRegistrationOwnership: ApplicationRegistration
+ transferApplicationRegistrationOwnership: ApplicationRegistration
initiateOTPProvisioning: InitiateTwoFactorAuthenticationProvisioning
initiateOTPProvisioningForAuthenticatedUser: InitiateTwoFactorAuthenticationProvisioning
deleteTwoFactorAuthenticationMethod: DeleteTwoFactorAuthenticationMethod
@@ -3798,6 +3781,23 @@ export interface Mutation {
updateWorkspaceMemberSettings: Scalars['Boolean']
updateUserEmail: Scalars['Boolean']
resendEmailVerificationToken: ResendEmailVerificationToken
+ activateWorkspace: Workspace
+ updateWorkspace: Workspace
+ updateWorkspaceAllowedIframeOrigins: Workspace
+ deleteCurrentWorkspace: Workspace
+ checkCustomDomainValidRecords?: DomainValidRecords
+ enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult
+ upgradeApplication: Scalars['Boolean']
+ grantApplicationCapabilities: ApplicationCapabilityGrant
+ /** @deprecated Use installApplication instead */
+ installMarketplaceApp: Scalars['Boolean']
+ installApplication: Application
+ triggerInstallApplicationJob: TriggerInstallApplicationJobResult
+ triggerUninstallApplicationJob: TriggerUninstallApplicationJobResult
+ updateApplication: Application
+ uninstallApplication: Scalars['Boolean']
+ syncMarketplaceCatalog: Scalars['Boolean']
+ runApplicationHealthCheck?: ApplicationHealthCheckResult
createOIDCIdentityProvider: SetupSso
createSAMLIdentityProvider: SetupSso
deleteSSOIdentityProvider: DeleteSso
@@ -3826,10 +3826,10 @@ export interface Mutation {
__typename: 'Mutation'
}
-export type MessageParticipantRole = 'FROM' | 'TO' | 'CC' | 'BCC' | 'REPLY_TO'
-
export type RunAgentMessageRole = 'user' | 'assistant'
+export type MessageParticipantRole = 'FROM' | 'TO' | 'CC' | 'BCC' | 'REPLY_TO'
+
export type AnalyticsType = 'PAGEVIEW' | 'TRACK'
export interface Subscription {
@@ -7440,28 +7440,18 @@ export interface QueryGenqlSelection{
id: Scalars['UUID']} })
objectRecordCounts?: ObjectRecordCountGenqlSelection
mostlyEmptyFieldMetadataIds?: { __args: {objectMetadataId: Scalars['UUID']} }
+ getToolIndex?: ToolIndexEntryGenqlSelection
+ getToolInputSchema?: { __args: {toolName: Scalars['String']} }
+ previewMessageCampaignAudience?: (CampaignAudiencePreviewDTOGenqlSelection & { __args: {input: PreviewMessageCampaignAudienceInput} })
+ messageSuppressions?: (MessageSuppressionListGenqlSelection & { __args: {input: FindMessageSuppressionsInput} })
+ unsubscribeTopics?: UnsubscribeTopicGenqlSelection
+ myMessageChannels?: (MessageChannelGenqlSelection & { __args?: {connectedAccountId?: (Scalars['UUID'] | null)} })
+ appMessageChannels?: (MessageChannelGenqlSelection & { __args?: {filter?: (ListAppMessageChannelsInput | null)} })
+ getEmailingDomains?: EmailingDomainGenqlSelection
getRoles?: RoleGenqlSelection
getRole?: (RoleGenqlSelection & { __args: {id: Scalars['UUID']} })
- currentWorkspace?: WorkspaceGenqlSelection
- getPublicWorkspaceDataByDomain?: (PublicWorkspaceDataGenqlSelection & { __args?: {origin?: (Scalars['String'] | null)} })
- getPublicWorkspaceDataById?: (PublicWorkspaceDataSummaryGenqlSelection & { __args: {id: Scalars['UUID']} })
- findApplicationRegistrationByClientId?: (PublicApplicationRegistrationGenqlSelection & { __args: {clientId: Scalars['String']} })
- findApplicationRegistrationByUniversalIdentifier?: (ApplicationRegistrationGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
- findManyApplicationRegistrations?: ApplicationRegistrationGenqlSelection
- findOneApplicationRegistration?: (ApplicationRegistrationGenqlSelection & { __args: {id: Scalars['String']} })
- findApplicationRegistrationStats?: (ApplicationRegistrationStatsGenqlSelection & { __args: {id: Scalars['String']} })
- findApplicationRegistrationVariables?: (ApplicationRegistrationVariableGenqlSelection & { __args: {applicationRegistrationId: Scalars['String']} })
- applicationRegistrationTarballUrl?: { __args: {id: Scalars['String']} }
- findClaimableApplicationRegistration?: (ClaimableApplicationRegistrationGenqlSelection & { __args?: {sourcePackage?: (Scalars['String'] | null), universalIdentifier?: (Scalars['String'] | null)} })
- githubClaimAuthorizationUrl?: { __args: {applicationRegistrationId: Scalars['String']} }
- findManyApplications?: ApplicationGenqlSelection
- findOneApplication?: (ApplicationGenqlSelection & { __args?: {id?: (Scalars['UUID'] | null), universalIdentifier?: (Scalars['UUID'] | null)} })
- findInstallApplicationJobStatus?: (JobStatusGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
- findUninstallApplicationJobStatus?: (JobStatusGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
- findManyMarketplaceApps?: (MarketplaceAppGenqlSelection & { __args?: {universalIdentifiers?: (Scalars['String'][] | null)} })
- findMarketplaceAppDetail?: (MarketplaceAppDetailGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
- publicMarketplaceApps?: (MarketplaceAppGenqlSelection & { __args: {isVetted: Scalars['Boolean']} })
- publicMarketplaceAppDetail?: (MarketplaceAppDetailGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
+ webhooks?: WebhookGenqlSelection
+ webhook?: (WebhookGenqlSelection & { __args: {id: Scalars['UUID']} })
fields?: (FieldConnectionGenqlSelection & { __args: {
/** Limit or page results. */
paging: CursorPaging,
@@ -7472,16 +7462,6 @@ export interface QueryGenqlSelection{
id: Scalars['UUID']} })
getViewGroups?: (ViewGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
getViewGroup?: (ViewGroupGenqlSelection & { __args: {id: Scalars['String']} })
- previewMessageCampaignAudience?: (CampaignAudiencePreviewDTOGenqlSelection & { __args: {input: PreviewMessageCampaignAudienceInput} })
- messageSuppressions?: (MessageSuppressionListGenqlSelection & { __args: {input: FindMessageSuppressionsInput} })
- unsubscribeTopics?: UnsubscribeTopicGenqlSelection
- myMessageChannels?: (MessageChannelGenqlSelection & { __args?: {connectedAccountId?: (Scalars['UUID'] | null)} })
- appMessageChannels?: (MessageChannelGenqlSelection & { __args?: {filter?: (ListAppMessageChannelsInput | null)} })
- getEmailingDomains?: EmailingDomainGenqlSelection
- getToolIndex?: ToolIndexEntryGenqlSelection
- getToolInputSchema?: { __args: {toolName: Scalars['String']} }
- webhooks?: WebhookGenqlSelection
- webhook?: (WebhookGenqlSelection & { __args: {id: Scalars['UUID']} })
myMessageFolders?: (MessageFolderGenqlSelection & { __args?: {messageChannelId?: (Scalars['UUID'] | null)} })
myCalendarChannels?: (CalendarChannelGenqlSelection & { __args?: {connectedAccountId?: (Scalars['UUID'] | null)} })
getPermissionFlags?: PermissionFlagGenqlSelection
@@ -7508,7 +7488,27 @@ export interface QueryGenqlSelection{
checkWorkspaceSubdomainAvailability?: (SubdomainAvailabilityDTOGenqlSelection & { __args: {subdomain: Scalars['String']} })
getWorkspaceCreationDefaults?: WorkspaceCreationDefaultsDTOGenqlSelection
validatePasswordResetToken?: (ValidatePasswordResetTokenGenqlSelection & { __args: {passwordResetToken: Scalars['String']} })
+ findApplicationRegistrationByClientId?: (PublicApplicationRegistrationGenqlSelection & { __args: {clientId: Scalars['String']} })
+ findApplicationRegistrationByUniversalIdentifier?: (ApplicationRegistrationGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
+ findManyApplicationRegistrations?: ApplicationRegistrationGenqlSelection
+ findOneApplicationRegistration?: (ApplicationRegistrationGenqlSelection & { __args: {id: Scalars['String']} })
+ findApplicationRegistrationStats?: (ApplicationRegistrationStatsGenqlSelection & { __args: {id: Scalars['String']} })
+ findApplicationRegistrationVariables?: (ApplicationRegistrationVariableGenqlSelection & { __args: {applicationRegistrationId: Scalars['String']} })
+ applicationRegistrationTarballUrl?: { __args: {id: Scalars['String']} }
+ findClaimableApplicationRegistration?: (ClaimableApplicationRegistrationGenqlSelection & { __args?: {sourcePackage?: (Scalars['String'] | null), universalIdentifier?: (Scalars['String'] | null)} })
+ githubClaimAuthorizationUrl?: { __args: {applicationRegistrationId: Scalars['String']} }
currentUser?: UserGenqlSelection
+ currentWorkspace?: WorkspaceGenqlSelection
+ getPublicWorkspaceDataByDomain?: (PublicWorkspaceDataGenqlSelection & { __args?: {origin?: (Scalars['String'] | null)} })
+ getPublicWorkspaceDataById?: (PublicWorkspaceDataSummaryGenqlSelection & { __args: {id: Scalars['UUID']} })
+ findManyApplications?: ApplicationGenqlSelection
+ findOneApplication?: (ApplicationGenqlSelection & { __args?: {id?: (Scalars['UUID'] | null), universalIdentifier?: (Scalars['UUID'] | null)} })
+ findInstallApplicationJobStatus?: (JobStatusGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
+ findUninstallApplicationJobStatus?: (JobStatusGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
+ findManyMarketplaceApps?: (MarketplaceAppGenqlSelection & { __args?: {universalIdentifiers?: (Scalars['String'][] | null)} })
+ findMarketplaceAppDetail?: (MarketplaceAppDetailGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
+ publicMarketplaceApps?: (MarketplaceAppGenqlSelection & { __args: {isVetted: Scalars['Boolean']} })
+ publicMarketplaceAppDetail?: (MarketplaceAppDetailGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
getSSOIdentityProviders?: FindAvailableSSOIDPGenqlSelection
eventLogs?: (EventLogQueryResultGenqlSelection & { __args: {input: EventLogQueryInput} })
pieChartData?: (PieChartDataGenqlSelection & { __args: {input: PieChartDataInput} })
@@ -7686,52 +7686,7 @@ export interface MutationGenqlSelection{
updateManyObjects?: (ObjectGenqlSelection & { __args: {inputs: UpdateOneObjectInput[]} })
createOneIndex?: (IndexGenqlSelection & { __args: {input: CreateOneIndexInput} })
deleteOneIndex?: (IndexGenqlSelection & { __args: {input: DeleteOneIndexInput} })
- updateWorkspaceMemberRole?: (WorkspaceMemberGenqlSelection & { __args: {workspaceMemberId: Scalars['UUID'], roleId: Scalars['UUID']} })
- createOneRole?: (RoleGenqlSelection & { __args: {createRoleInput: CreateRoleInput} })
- updateOneRole?: (RoleGenqlSelection & { __args: {updateRoleInput: UpdateRoleInput} })
- deleteOneRole?: { __args: {roleId: Scalars['UUID']} }
- upsertObjectPermissions?: (ObjectPermissionGenqlSelection & { __args: {upsertObjectPermissionsInput: UpsertObjectPermissionsInput} })
- upsertPermissionFlags?: (RolePermissionFlagGenqlSelection & { __args: {upsertPermissionFlagsInput: UpsertPermissionFlagsInput} })
- upsertFieldPermissions?: (FieldPermissionGenqlSelection & { __args: {upsertFieldPermissionsInput: UpsertFieldPermissionsInput} })
- upsertRowLevelPermissionPredicates?: (UpsertRowLevelPermissionPredicatesResultGenqlSelection & { __args: {input: UpsertRowLevelPermissionPredicatesInput} })
- assignRoleToAgent?: { __args: {agentId: Scalars['UUID'], roleId: Scalars['UUID']} }
- removeRoleFromAgent?: { __args: {agentId: Scalars['UUID']} }
- activateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: ActivateWorkspaceInput} })
- updateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceInput} })
- updateWorkspaceAllowedIframeOrigins?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceAllowedIframeOriginsInput} })
- deleteCurrentWorkspace?: WorkspaceGenqlSelection
- checkCustomDomainValidRecords?: DomainValidRecordsGenqlSelection
- enrichWorkspaceCompany?: WorkspaceCompanyEnrichmentResultGenqlSelection
- upgradeApplication?: { __args: {appRegistrationId: Scalars['String'], targetVersion: Scalars['String']} }
- createApplicationRegistration?: (CreateApplicationRegistrationGenqlSelection & { __args: {input: CreateApplicationRegistrationInput} })
- updateApplicationRegistration?: (ApplicationRegistrationGenqlSelection & { __args: {input: UpdateApplicationRegistrationInput} })
- deleteApplicationRegistration?: { __args: {id: Scalars['String']} }
- rotateApplicationRegistrationClientSecret?: (RotateClientSecretGenqlSelection & { __args: {id: Scalars['String']} })
- updateApplicationRegistrationVariable?: (ApplicationRegistrationVariableGenqlSelection & { __args: {input: UpdateApplicationRegistrationVariableInput} })
- completeAppTarballUpload?: (ApplicationRegistrationGenqlSelection & { __args: {fileId: Scalars['UUID']} })
- /** @deprecated Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage. */
- uploadAppTarball?: (ApplicationRegistrationGenqlSelection & { __args: {file: Scalars['Upload'], universalIdentifier?: (Scalars['String'] | null)} })
- claimApplicationRegistrationOwnership?: (ApplicationRegistrationGenqlSelection & { __args: {applicationRegistrationId: Scalars['String']} })
- transferApplicationRegistrationOwnership?: (ApplicationRegistrationGenqlSelection & { __args: {applicationRegistrationId: Scalars['String'], targetWorkspaceSubdomain: Scalars['String']} })
- grantApplicationCapabilities?: (ApplicationCapabilityGrantGenqlSelection & { __args: {input: GrantApplicationCapabilitiesInput} })
- /** @deprecated Use installApplication instead */
- installMarketplaceApp?: { __args: {universalIdentifier: Scalars['String'], version?: (Scalars['String'] | null)} }
- installApplication?: (ApplicationGenqlSelection & { __args: {universalIdentifier: Scalars['String'], version?: (Scalars['String'] | null)} })
- triggerInstallApplicationJob?: (TriggerInstallApplicationJobResultGenqlSelection & { __args: {input: TriggerInstallApplicationJobInput} })
- triggerUninstallApplicationJob?: (TriggerUninstallApplicationJobResultGenqlSelection & { __args: {input: TriggerUninstallApplicationJobInput} })
- updateApplication?: (ApplicationGenqlSelection & { __args: {id: Scalars['UUID'], input: UpdateApplicationInput} })
- uninstallApplication?: { __args: {universalIdentifier: Scalars['String']} }
- syncMarketplaceCatalog?: boolean | number
- runApplicationHealthCheck?: (ApplicationHealthCheckResultGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
- createOneField?: (FieldGenqlSelection & { __args: {input: CreateOneFieldMetadataInput} })
- updateOneField?: (FieldGenqlSelection & { __args: {input: UpdateOneFieldMetadataInput} })
- deleteOneField?: (FieldGenqlSelection & { __args: {input: DeleteOneFieldInput} })
- createViewGroup?: (ViewGroupGenqlSelection & { __args: {input: CreateViewGroupInput} })
- createManyViewGroups?: (ViewGroupGenqlSelection & { __args: {inputs: CreateViewGroupInput[]} })
- updateViewGroup?: (ViewGroupGenqlSelection & { __args: {input: UpdateViewGroupInput} })
- updateManyViewGroups?: (ViewGroupGenqlSelection & { __args: {inputs: UpdateViewGroupInput[]} })
- deleteViewGroup?: (ViewGroupGenqlSelection & { __args: {input: DeleteViewGroupInput} })
- destroyViewGroup?: (ViewGroupGenqlSelection & { __args: {input: DestroyViewGroupInput} })
+ runAgent?: (RunAgentResultGenqlSelection & { __args: {input: RunAgentInput} })
sendMessageCampaign?: (SendMessageCampaignOutputDTOGenqlSelection & { __args: {input: SendMessageCampaignInput} })
cancelMessageCampaign?: (CancelMessageCampaignOutputDTOGenqlSelection & { __args: {input: CancelMessageCampaignInput} })
sendMessageCampaignTest?: (SendEmailViaDomainOutputGenqlSelection & { __args: {input: SendMessageCampaignTestInput} })
@@ -7752,10 +7707,28 @@ export interface MutationGenqlSelection{
createEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {input: CreateEmailingDomainInput} })
deleteEmailingDomain?: { __args: {id: Scalars['String']} }
verifyEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {id: Scalars['String']} })
+ updateWorkspaceMemberRole?: (WorkspaceMemberGenqlSelection & { __args: {workspaceMemberId: Scalars['UUID'], roleId: Scalars['UUID']} })
+ createOneRole?: (RoleGenqlSelection & { __args: {createRoleInput: CreateRoleInput} })
+ updateOneRole?: (RoleGenqlSelection & { __args: {updateRoleInput: UpdateRoleInput} })
+ deleteOneRole?: { __args: {roleId: Scalars['UUID']} }
+ upsertObjectPermissions?: (ObjectPermissionGenqlSelection & { __args: {upsertObjectPermissionsInput: UpsertObjectPermissionsInput} })
+ upsertPermissionFlags?: (RolePermissionFlagGenqlSelection & { __args: {upsertPermissionFlagsInput: UpsertPermissionFlagsInput} })
+ upsertFieldPermissions?: (FieldPermissionGenqlSelection & { __args: {upsertFieldPermissionsInput: UpsertFieldPermissionsInput} })
+ upsertRowLevelPermissionPredicates?: (UpsertRowLevelPermissionPredicatesResultGenqlSelection & { __args: {input: UpsertRowLevelPermissionPredicatesInput} })
+ assignRoleToAgent?: { __args: {agentId: Scalars['UUID'], roleId: Scalars['UUID']} }
+ removeRoleFromAgent?: { __args: {agentId: Scalars['UUID']} }
createWebhook?: (WebhookGenqlSelection & { __args: {input: CreateWebhookInput} })
updateWebhook?: (WebhookGenqlSelection & { __args: {input: UpdateWebhookInput} })
deleteWebhook?: (WebhookGenqlSelection & { __args: {id: Scalars['UUID']} })
- runAgent?: (RunAgentResultGenqlSelection & { __args: {input: RunAgentInput} })
+ createOneField?: (FieldGenqlSelection & { __args: {input: CreateOneFieldMetadataInput} })
+ updateOneField?: (FieldGenqlSelection & { __args: {input: UpdateOneFieldMetadataInput} })
+ deleteOneField?: (FieldGenqlSelection & { __args: {input: DeleteOneFieldInput} })
+ createViewGroup?: (ViewGroupGenqlSelection & { __args: {input: CreateViewGroupInput} })
+ createManyViewGroups?: (ViewGroupGenqlSelection & { __args: {inputs: CreateViewGroupInput[]} })
+ updateViewGroup?: (ViewGroupGenqlSelection & { __args: {input: UpdateViewGroupInput} })
+ updateManyViewGroups?: (ViewGroupGenqlSelection & { __args: {inputs: UpdateViewGroupInput[]} })
+ deleteViewGroup?: (ViewGroupGenqlSelection & { __args: {input: DeleteViewGroupInput} })
+ destroyViewGroup?: (ViewGroupGenqlSelection & { __args: {input: DestroyViewGroupInput} })
updateMessageFolder?: (MessageFolderGenqlSelection & { __args: {input: UpdateMessageFolderInput} })
updateMessageFolders?: (MessageFolderGenqlSelection & { __args: {input: UpdateMessageFoldersInput} })
updateCalendarChannel?: (CalendarChannelGenqlSelection & { __args: {input: UpdateCalendarChannelInput} })
@@ -7811,6 +7784,16 @@ export interface MutationGenqlSelection{
generatePlaygroundToken?: AuthTokenGenqlSelection
emailPasswordResetLink?: (EmailPasswordResetLinkGenqlSelection & { __args: {email: Scalars['String'], workspaceId?: (Scalars['UUID'] | null), captchaToken?: (Scalars['String'] | null)} })
updatePasswordViaResetToken?: (InvalidatePasswordGenqlSelection & { __args: {passwordResetToken: Scalars['String'], newPassword: Scalars['String']} })
+ createApplicationRegistration?: (CreateApplicationRegistrationGenqlSelection & { __args: {input: CreateApplicationRegistrationInput} })
+ updateApplicationRegistration?: (ApplicationRegistrationGenqlSelection & { __args: {input: UpdateApplicationRegistrationInput} })
+ deleteApplicationRegistration?: { __args: {id: Scalars['String']} }
+ rotateApplicationRegistrationClientSecret?: (RotateClientSecretGenqlSelection & { __args: {id: Scalars['String']} })
+ updateApplicationRegistrationVariable?: (ApplicationRegistrationVariableGenqlSelection & { __args: {input: UpdateApplicationRegistrationVariableInput} })
+ completeAppTarballUpload?: (ApplicationRegistrationGenqlSelection & { __args: {fileId: Scalars['UUID']} })
+ /** @deprecated Use createFileUpload with the AppTarball folder and completeAppTarballUpload, which send the tarball straight to file storage. */
+ uploadAppTarball?: (ApplicationRegistrationGenqlSelection & { __args: {file: Scalars['Upload'], universalIdentifier?: (Scalars['String'] | null)} })
+ claimApplicationRegistrationOwnership?: (ApplicationRegistrationGenqlSelection & { __args: {applicationRegistrationId: Scalars['String']} })
+ transferApplicationRegistrationOwnership?: (ApplicationRegistrationGenqlSelection & { __args: {applicationRegistrationId: Scalars['String'], targetWorkspaceSubdomain: Scalars['String']} })
initiateOTPProvisioning?: (InitiateTwoFactorAuthenticationProvisioningGenqlSelection & { __args: {loginToken: Scalars['String'], origin: Scalars['String']} })
initiateOTPProvisioningForAuthenticatedUser?: InitiateTwoFactorAuthenticationProvisioningGenqlSelection
deleteTwoFactorAuthenticationMethod?: (DeleteTwoFactorAuthenticationMethodGenqlSelection & { __args: {twoFactorAuthenticationMethodId: Scalars['UUID']} })
@@ -7820,6 +7803,23 @@ export interface MutationGenqlSelection{
updateWorkspaceMemberSettings?: { __args: {input: UpdateWorkspaceMemberSettingsInput} }
updateUserEmail?: { __args: {newEmail: Scalars['String'], verifyEmailRedirectPath?: (Scalars['String'] | null)} }
resendEmailVerificationToken?: (ResendEmailVerificationTokenGenqlSelection & { __args: {email: Scalars['String'], origin: Scalars['String']} })
+ activateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: ActivateWorkspaceInput} })
+ updateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceInput} })
+ updateWorkspaceAllowedIframeOrigins?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceAllowedIframeOriginsInput} })
+ deleteCurrentWorkspace?: WorkspaceGenqlSelection
+ checkCustomDomainValidRecords?: DomainValidRecordsGenqlSelection
+ enrichWorkspaceCompany?: WorkspaceCompanyEnrichmentResultGenqlSelection
+ upgradeApplication?: { __args: {appRegistrationId: Scalars['String'], targetVersion: Scalars['String']} }
+ grantApplicationCapabilities?: (ApplicationCapabilityGrantGenqlSelection & { __args: {input: GrantApplicationCapabilitiesInput} })
+ /** @deprecated Use installApplication instead */
+ installMarketplaceApp?: { __args: {universalIdentifier: Scalars['String'], version?: (Scalars['String'] | null)} }
+ installApplication?: (ApplicationGenqlSelection & { __args: {universalIdentifier: Scalars['String'], version?: (Scalars['String'] | null)} })
+ triggerInstallApplicationJob?: (TriggerInstallApplicationJobResultGenqlSelection & { __args: {input: TriggerInstallApplicationJobInput} })
+ triggerUninstallApplicationJob?: (TriggerUninstallApplicationJobResultGenqlSelection & { __args: {input: TriggerUninstallApplicationJobInput} })
+ updateApplication?: (ApplicationGenqlSelection & { __args: {id: Scalars['UUID'], input: UpdateApplicationInput} })
+ uninstallApplication?: { __args: {universalIdentifier: Scalars['String']} }
+ syncMarketplaceCatalog?: boolean | number
+ runApplicationHealthCheck?: (ApplicationHealthCheckResultGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
createOIDCIdentityProvider?: (SetupSsoGenqlSelection & { __args: {input: SetupOIDCSsoInput} })
createSAMLIdentityProvider?: (SetupSsoGenqlSelection & { __args: {input: SetupSAMLSsoInput} })
deleteSSOIdentityProvider?: (DeleteSsoGenqlSelection & { __args: {input: DeleteSsoInput} })
@@ -8095,6 +8095,46 @@ export interface DeleteOneIndexInput {
/** The id of the custom index to delete. */
id: Scalars['UUID']}
+export interface RunAgentInput {agentUniversalIdentifier: Scalars['String'],prompt?: (Scalars['String'] | null),runAsWorkspaceMemberId?: (Scalars['UUID'] | null),messages?: (RunAgentMessageInput[] | null),input?: (RunAgentMessageInput[] | null),additionalInstructions?: (Scalars['String'] | null),thread?: (RunAgentThreadInput | null)}
+
+export interface RunAgentMessageInput {role: RunAgentMessageRole,content: Scalars['String'],attachments?: (RunAgentMessageAttachmentInput[] | null)}
+
+export interface RunAgentMessageAttachmentInput {fileId: Scalars['UUID'],filename?: (Scalars['String'] | null)}
+
+export interface RunAgentThreadInput {key: Scalars['String'],title?: (Scalars['String'] | null)}
+
+export interface SendMessageCampaignInput {campaignId: Scalars['String'],scheduledAt?: (Scalars['DateTime'] | null)}
+
+export interface CancelMessageCampaignInput {campaignId: Scalars['String']}
+
+export interface SendMessageCampaignTestInput {toAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['String'] | null),subject: Scalars['String'],body: Scalars['String'],fromAddress: Scalars['String']}
+
+export interface CreateMessageSuppressionInput {emailAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['UUID'] | null)}
+
+export interface CreateUnsubscribeTopicInput {name: Scalars['String'],description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
+
+export interface UpdateUnsubscribeTopicInput {id: Scalars['String'],name?: (Scalars['String'] | null),description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
+
+export interface UpdateMessageChannelInput {id: Scalars['UUID'],update: UpdateMessageChannelInputUpdates}
+
+export interface UpdateMessageChannelInputUpdates {visibility?: (MessageChannelVisibility | null),isContactAutoCreationEnabled?: (Scalars['Boolean'] | null),contactAutoCreationPolicy?: (MessageChannelContactAutoCreationPolicy | null),messageFolderImportPolicy?: (MessageFolderImportPolicy | null),isSyncEnabled?: (Scalars['Boolean'] | null),excludeNonProfessionalEmails?: (Scalars['Boolean'] | null),excludeGroupEmails?: (Scalars['Boolean'] | null)}
+
+export interface CreateEmailGroupChannelInput {handle: Scalars['String'],displayName?: (Scalars['String'] | null)}
+
+export interface UpdateEmailGroupChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null)}
+
+export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],handle: Scalars['String'],displayName?: (Scalars['String'] | null),visibility: MessageChannelVisibility}
+
+export interface UpdateAppMessageChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null),visibility?: (MessageChannelVisibility | null),isSyncEnabled?: (Scalars['Boolean'] | null)}
+
+export interface IngestAppMessagesInput {messageChannelId: Scalars['UUID'],messages: AppMessageInput[]}
+
+export interface AppMessageInput {externalId: Scalars['String'],threadExternalId: Scalars['String'],subject?: (Scalars['String'] | null),text: Scalars['String'],receivedAt: Scalars['DateTime'],participants: AppMessageParticipantInput[]}
+
+export interface AppMessageParticipantInput {role: MessageParticipantRole,handle: Scalars['String'],displayName?: (Scalars['String'] | null),personId?: (Scalars['UUID'] | null),workspaceMemberId?: (Scalars['UUID'] | null)}
+
+export interface CreateEmailingDomainInput {domain: Scalars['String']}
+
export interface CreateRoleInput {id?: (Scalars['String'] | null),label: Scalars['String'],description?: (Scalars['String'] | null),icon?: (Scalars['String'] | null),canUpdateAllSettings?: (Scalars['Boolean'] | null),canAccessAllTools?: (Scalars['Boolean'] | null),canReadAllObjectRecords?: (Scalars['Boolean'] | null),canUpdateAllObjectRecords?: (Scalars['Boolean'] | null),canSoftDeleteAllObjectRecords?: (Scalars['Boolean'] | null),canDestroyAllObjectRecords?: (Scalars['Boolean'] | null),canBeAssignedToUsers?: (Scalars['Boolean'] | null),canBeAssignedToAgents?: (Scalars['Boolean'] | null),canBeAssignedToApiKeys?: (Scalars['Boolean'] | null)}
export interface UpdateRoleInput {update: UpdateRolePayload,
@@ -8119,31 +8159,15 @@ export interface RowLevelPermissionPredicateInput {id?: (Scalars['UUID'] | null)
export interface RowLevelPermissionPredicateGroupInput {id?: (Scalars['UUID'] | null),objectMetadataId: Scalars['UUID'],parentRowLevelPermissionPredicateGroupId?: (Scalars['UUID'] | null),logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator,positionInRowLevelPermissionPredicateGroup?: (Scalars['Float'] | null)}
-export interface ActivateWorkspaceInput {
-/** Deprecated: the workspace name is set at creation (signUpInNewWorkspace) and this field is ignored during activation. Kept for backward compatibility. */
-displayName?: (Scalars['String'] | null)}
-
-export interface UpdateWorkspaceInput {subdomain?: (Scalars['String'] | null),customDomain?: (Scalars['String'] | null),displayName?: (Scalars['String'] | null),logo?: (Scalars['String'] | null),inviteHash?: (Scalars['String'] | null),isPublicInviteLinkEnabled?: (Scalars['Boolean'] | null),isCampaignClickTrackingEnabled?: (Scalars['Boolean'] | null),workspaceDiscoverability?: (WorkspaceDiscoverability | null),allowImpersonation?: (Scalars['Boolean'] | null),isGoogleAuthEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthEnabled?: (Scalars['Boolean'] | null),isPasswordAuthEnabled?: (Scalars['Boolean'] | null),isGoogleAuthBypassEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthBypassEnabled?: (Scalars['Boolean'] | null),isPasswordAuthBypassEnabled?: (Scalars['Boolean'] | null),defaultRoleId?: (Scalars['UUID'] | null),isTwoFactorAuthenticationEnforced?: (Scalars['Boolean'] | null),trashRetentionDays?: (Scalars['Float'] | null),eventLogRetentionDays?: (Scalars['Float'] | null),aiChatModelTier?: (AiModelTier | null),aiAgentModelTier?: (AiModelTier | null),isAutoModelSelectionEnabled?: (Scalars['Boolean'] | null),aiModelIdByTier?: (Scalars['JSON'] | null),aiEvaluationModelId?: (Scalars['String'] | null),aiAdditionalInstructions?: (Scalars['String'] | null),editableProfileFields?: (Scalars['String'][] | null),isInternalMessagesImportEnabled?: (Scalars['Boolean'] | null)}
-
-export interface UpdateWorkspaceAllowedIframeOriginsInput {operation: Scalars['String'],origin: Scalars['String']}
-
-export interface CreateApplicationRegistrationInput {name: Scalars['String'],universalIdentifier?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
-
-export interface UpdateApplicationRegistrationInput {id: Scalars['String'],update: UpdateApplicationRegistrationPayload}
-
-export interface UpdateApplicationRegistrationPayload {name?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
-
-export interface UpdateApplicationRegistrationVariableInput {id: Scalars['String'],update: UpdateApplicationRegistrationVariablePayload}
-
-export interface UpdateApplicationRegistrationVariablePayload {value?: (Scalars['String'] | null),resetValue?: (Scalars['Boolean'] | null),description?: (Scalars['String'] | null)}
-
-export interface GrantApplicationCapabilitiesInput {applicationId: Scalars['UUID'],capabilities: Scalars['String'][]}
-
-export interface TriggerInstallApplicationJobInput {universalIdentifier: Scalars['String']}
+export interface CreateWebhookInput {id?: (Scalars['UUID'] | null),targetUrl: Scalars['String'],operations: Scalars['String'][],description?: (Scalars['String'] | null),secret?: (Scalars['String'] | null)}
-export interface TriggerUninstallApplicationJobInput {universalIdentifier: Scalars['String']}
+export interface UpdateWebhookInput {
+/** The id of the webhook to update */
+id: Scalars['UUID'],
+/** The webhook fields to update */
+update: UpdateWebhookInputUpdates}
-export interface UpdateApplicationInput {autoUpgrade?: (Scalars['Boolean'] | null)}
+export interface UpdateWebhookInputUpdates {targetUrl?: (Scalars['String'] | null),operations?: (Scalars['String'][] | null),description?: (Scalars['String'] | null),secret?: (Scalars['String'] | null)}
export interface CreateOneFieldMetadataInput {
/** The record to create */
@@ -8181,56 +8205,6 @@ export interface DestroyViewGroupInput {
/** The id of the view group to destroy. */
id: Scalars['UUID']}
-export interface SendMessageCampaignInput {campaignId: Scalars['String'],scheduledAt?: (Scalars['DateTime'] | null)}
-
-export interface CancelMessageCampaignInput {campaignId: Scalars['String']}
-
-export interface SendMessageCampaignTestInput {toAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['String'] | null),subject: Scalars['String'],body: Scalars['String'],fromAddress: Scalars['String']}
-
-export interface CreateMessageSuppressionInput {emailAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['UUID'] | null)}
-
-export interface CreateUnsubscribeTopicInput {name: Scalars['String'],description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
-
-export interface UpdateUnsubscribeTopicInput {id: Scalars['String'],name?: (Scalars['String'] | null),description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
-
-export interface UpdateMessageChannelInput {id: Scalars['UUID'],update: UpdateMessageChannelInputUpdates}
-
-export interface UpdateMessageChannelInputUpdates {visibility?: (MessageChannelVisibility | null),isContactAutoCreationEnabled?: (Scalars['Boolean'] | null),contactAutoCreationPolicy?: (MessageChannelContactAutoCreationPolicy | null),messageFolderImportPolicy?: (MessageFolderImportPolicy | null),isSyncEnabled?: (Scalars['Boolean'] | null),excludeNonProfessionalEmails?: (Scalars['Boolean'] | null),excludeGroupEmails?: (Scalars['Boolean'] | null)}
-
-export interface CreateEmailGroupChannelInput {handle: Scalars['String'],displayName?: (Scalars['String'] | null)}
-
-export interface UpdateEmailGroupChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null)}
-
-export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],handle: Scalars['String'],displayName?: (Scalars['String'] | null),visibility: MessageChannelVisibility}
-
-export interface UpdateAppMessageChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null),visibility?: (MessageChannelVisibility | null),isSyncEnabled?: (Scalars['Boolean'] | null)}
-
-export interface IngestAppMessagesInput {messageChannelId: Scalars['UUID'],messages: AppMessageInput[]}
-
-export interface AppMessageInput {externalId: Scalars['String'],threadExternalId: Scalars['String'],subject?: (Scalars['String'] | null),text: Scalars['String'],receivedAt: Scalars['DateTime'],participants: AppMessageParticipantInput[]}
-
-export interface AppMessageParticipantInput {role: MessageParticipantRole,handle: Scalars['String'],displayName?: (Scalars['String'] | null),personId?: (Scalars['UUID'] | null),workspaceMemberId?: (Scalars['UUID'] | null)}
-
-export interface CreateEmailingDomainInput {domain: Scalars['String']}
-
-export interface CreateWebhookInput {id?: (Scalars['UUID'] | null),targetUrl: Scalars['String'],operations: Scalars['String'][],description?: (Scalars['String'] | null),secret?: (Scalars['String'] | null)}
-
-export interface UpdateWebhookInput {
-/** The id of the webhook to update */
-id: Scalars['UUID'],
-/** The webhook fields to update */
-update: UpdateWebhookInputUpdates}
-
-export interface UpdateWebhookInputUpdates {targetUrl?: (Scalars['String'] | null),operations?: (Scalars['String'][] | null),description?: (Scalars['String'] | null),secret?: (Scalars['String'] | null)}
-
-export interface RunAgentInput {agentUniversalIdentifier: Scalars['String'],prompt?: (Scalars['String'] | null),runAsWorkspaceMemberId?: (Scalars['UUID'] | null),messages?: (RunAgentMessageInput[] | null),input?: (RunAgentMessageInput[] | null),additionalInstructions?: (Scalars['String'] | null),thread?: (RunAgentThreadInput | null)}
-
-export interface RunAgentMessageInput {role: RunAgentMessageRole,content: Scalars['String'],attachments?: (RunAgentMessageAttachmentInput[] | null)}
-
-export interface RunAgentMessageAttachmentInput {fileId: Scalars['UUID'],filename?: (Scalars['String'] | null)}
-
-export interface RunAgentThreadInput {key: Scalars['String'],title?: (Scalars['String'] | null)}
-
export interface UpdateMessageFolderInput {id: Scalars['UUID'],update: UpdateMessageFolderInputUpdates}
export interface UpdateMessageFolderInputUpdates {isSynced: Scalars['Boolean']}
@@ -8271,8 +8245,34 @@ export interface GetAuthorizationUrlForSSOInput {identityProviderId: Scalars['UU
export interface SignUpInNewWorkspaceInput {displayName?: (Scalars['String'] | null),subdomain?: (Scalars['String'] | null)}
+export interface CreateApplicationRegistrationInput {name: Scalars['String'],universalIdentifier?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
+
+export interface UpdateApplicationRegistrationInput {id: Scalars['String'],update: UpdateApplicationRegistrationPayload}
+
+export interface UpdateApplicationRegistrationPayload {name?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
+
+export interface UpdateApplicationRegistrationVariableInput {id: Scalars['String'],update: UpdateApplicationRegistrationVariablePayload}
+
+export interface UpdateApplicationRegistrationVariablePayload {value?: (Scalars['String'] | null),resetValue?: (Scalars['Boolean'] | null),description?: (Scalars['String'] | null)}
+
export interface UpdateWorkspaceMemberSettingsInput {workspaceMemberId: Scalars['UUID'],update: Scalars['JSON']}
+export interface ActivateWorkspaceInput {
+/** Deprecated: the workspace name is set at creation (signUpInNewWorkspace) and this field is ignored during activation. Kept for backward compatibility. */
+displayName?: (Scalars['String'] | null)}
+
+export interface UpdateWorkspaceInput {subdomain?: (Scalars['String'] | null),customDomain?: (Scalars['String'] | null),displayName?: (Scalars['String'] | null),logo?: (Scalars['String'] | null),inviteHash?: (Scalars['String'] | null),isPublicInviteLinkEnabled?: (Scalars['Boolean'] | null),isCampaignClickTrackingEnabled?: (Scalars['Boolean'] | null),workspaceDiscoverability?: (WorkspaceDiscoverability | null),allowImpersonation?: (Scalars['Boolean'] | null),isGoogleAuthEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthEnabled?: (Scalars['Boolean'] | null),isPasswordAuthEnabled?: (Scalars['Boolean'] | null),isGoogleAuthBypassEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthBypassEnabled?: (Scalars['Boolean'] | null),isPasswordAuthBypassEnabled?: (Scalars['Boolean'] | null),defaultRoleId?: (Scalars['UUID'] | null),isTwoFactorAuthenticationEnforced?: (Scalars['Boolean'] | null),trashRetentionDays?: (Scalars['Float'] | null),eventLogRetentionDays?: (Scalars['Float'] | null),aiChatModelTier?: (AiModelTier | null),aiAgentModelTier?: (AiModelTier | null),isAutoModelSelectionEnabled?: (Scalars['Boolean'] | null),aiModelIdByTier?: (Scalars['JSON'] | null),aiEvaluationModelId?: (Scalars['String'] | null),aiAdditionalInstructions?: (Scalars['String'] | null),editableProfileFields?: (Scalars['String'][] | null),isInternalMessagesImportEnabled?: (Scalars['Boolean'] | null)}
+
+export interface UpdateWorkspaceAllowedIframeOriginsInput {operation: Scalars['String'],origin: Scalars['String']}
+
+export interface GrantApplicationCapabilitiesInput {applicationId: Scalars['UUID'],capabilities: Scalars['String'][]}
+
+export interface TriggerInstallApplicationJobInput {universalIdentifier: Scalars['String']}
+
+export interface TriggerUninstallApplicationJobInput {universalIdentifier: Scalars['String']}
+
+export interface UpdateApplicationInput {autoUpgrade?: (Scalars['Boolean'] | null)}
+
export interface SetupOIDCSsoInput {name: Scalars['String'],issuer: Scalars['String'],clientID: Scalars['String'],clientSecret: Scalars['String']}
export interface SetupSAMLSsoInput {name: Scalars['String'],issuer: Scalars['String'],id: Scalars['UUID'],ssoURL: Scalars['String'],certificate: Scalars['String'],fingerprint?: (Scalars['String'] | null)}
@@ -11804,6 +11804,11 @@ export const enumEventLogFilterOperand = {
IS_NOT: 'IS_NOT' as const
}
+export const enumRunAgentMessageRole = {
+ user: 'user' as const,
+ assistant: 'assistant' as const
+}
+
export const enumMessageParticipantRole = {
FROM: 'FROM' as const,
TO: 'TO' as const,
@@ -11812,11 +11817,6 @@ export const enumMessageParticipantRole = {
REPLY_TO: 'REPLY_TO' as const
}
-export const enumRunAgentMessageRole = {
- user: 'user' as const,
- assistant: 'assistant' as const
-}
-
export const enumAnalyticsType = {
PAGEVIEW: 'PAGEVIEW' as const,
TRACK: 'TRACK' as const
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 74f4216a492..5596f0a953c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -112,8 +112,8 @@ export default {
443,
447,
458,
- 578,
- 585,
+ 532,
+ 550,
613
],
"types": {
@@ -8005,180 +8005,79 @@ export default {
]
}
],
- "getRoles": [
- 52
- ],
- "getRole": [
- 52,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "currentWorkspace": [
- 73
- ],
- "getPublicWorkspaceDataByDomain": [
- 226,
- {
- "origin": [
- 1
- ]
- }
- ],
- "getPublicWorkspaceDataById": [
- 227,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "findApplicationRegistrationByClientId": [
- 246,
- {
- "clientId": [
- 1,
- "String!"
- ]
- }
- ],
- "findApplicationRegistrationByUniversalIdentifier": [
- 80,
- {
- "universalIdentifier": [
- 1,
- "String!"
- ]
- }
- ],
- "findManyApplicationRegistrations": [
- 80
- ],
- "findOneApplicationRegistration": [
- 80,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "findApplicationRegistrationStats": [
- 219,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "findApplicationRegistrationVariables": [
- 217,
- {
- "applicationRegistrationId": [
- 1,
- "String!"
- ]
- }
+ "getToolIndex": [
+ 370
],
- "applicationRegistrationTarballUrl": [
- 1,
+ "getToolInputSchema": [
+ 9,
{
- "id": [
+ "toolName": [
1,
"String!"
]
}
],
- "findClaimableApplicationRegistration": [
- 244,
+ "previewMessageCampaignAudience": [
+ 351,
{
- "sourcePackage": [
- 1
- ],
- "universalIdentifier": [
- 1
+ "input": [
+ 437,
+ "PreviewMessageCampaignAudienceInput!"
]
}
],
- "githubClaimAuthorizationUrl": [
- 1,
+ "messageSuppressions": [
+ 359,
{
- "applicationRegistrationId": [
- 1,
- "String!"
+ "input": [
+ 438,
+ "FindMessageSuppressionsInput!"
]
}
],
- "findManyApplications": [
- 53
+ "unsubscribeTopics": [
+ 360
],
- "findOneApplication": [
- 53,
+ "myMessageChannels": [
+ 340,
{
- "id": [
- 3
- ],
- "universalIdentifier": [
+ "connectedAccountId": [
3
]
}
],
- "findInstallApplicationJobStatus": [
- 194,
+ "appMessageChannels": [
+ 340,
{
- "universalIdentifier": [
- 1,
- "String!"
+ "filter": [
+ 439
]
}
],
- "findUninstallApplicationJobStatus": [
- 194,
- {
- "universalIdentifier": [
- 1,
- "String!"
- ]
- }
+ "getEmailingDomains": [
+ 336
],
- "findManyMarketplaceApps": [
- 262,
- {
- "universalIdentifiers": [
- 1,
- "[String!]"
- ]
- }
+ "getRoles": [
+ 52
],
- "findMarketplaceAppDetail": [
- 266,
+ "getRole": [
+ 52,
{
- "universalIdentifier": [
- 1,
- "String!"
+ "id": [
+ 3,
+ "UUID!"
]
}
],
- "publicMarketplaceApps": [
- 262,
- {
- "isVetted": [
- 8,
- "Boolean!"
- ]
- }
+ "webhooks": [
+ 369
],
- "publicMarketplaceAppDetail": [
- 266,
+ "webhook": [
+ 369,
{
- "universalIdentifier": [
- 1,
- "String!"
+ "id": [
+ 3,
+ "UUID!"
]
}
],
@@ -8221,70 +8120,6 @@ export default {
]
}
],
- "previewMessageCampaignAudience": [
- 351,
- {
- "input": [
- 437,
- "PreviewMessageCampaignAudienceInput!"
- ]
- }
- ],
- "messageSuppressions": [
- 359,
- {
- "input": [
- 438,
- "FindMessageSuppressionsInput!"
- ]
- }
- ],
- "unsubscribeTopics": [
- 360
- ],
- "myMessageChannels": [
- 340,
- {
- "connectedAccountId": [
- 3
- ]
- }
- ],
- "appMessageChannels": [
- 340,
- {
- "filter": [
- 439
- ]
- }
- ],
- "getEmailingDomains": [
- 336
- ],
- "getToolIndex": [
- 370
- ],
- "getToolInputSchema": [
- 9,
- {
- "toolName": [
- 1,
- "String!"
- ]
- }
- ],
- "webhooks": [
- 369
- ],
- "webhook": [
- 369,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
"myMessageFolders": [
415,
{
@@ -8478,16 +8313,181 @@ export default {
]
}
],
- "currentUser": [
- 77
- ],
- "getSSOIdentityProviders": [
- 253
- ],
- "eventLogs": [
- 401,
+ "findApplicationRegistrationByClientId": [
+ 246,
{
- "input": [
+ "clientId": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findApplicationRegistrationByUniversalIdentifier": [
+ 80,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findManyApplicationRegistrations": [
+ 80
+ ],
+ "findOneApplicationRegistration": [
+ 80,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findApplicationRegistrationStats": [
+ 219,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findApplicationRegistrationVariables": [
+ 217,
+ {
+ "applicationRegistrationId": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "applicationRegistrationTarballUrl": [
+ 1,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findClaimableApplicationRegistration": [
+ 244,
+ {
+ "sourcePackage": [
+ 1
+ ],
+ "universalIdentifier": [
+ 1
+ ]
+ }
+ ],
+ "githubClaimAuthorizationUrl": [
+ 1,
+ {
+ "applicationRegistrationId": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "currentUser": [
+ 77
+ ],
+ "currentWorkspace": [
+ 73
+ ],
+ "getPublicWorkspaceDataByDomain": [
+ 226,
+ {
+ "origin": [
+ 1
+ ]
+ }
+ ],
+ "getPublicWorkspaceDataById": [
+ 227,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "findManyApplications": [
+ 53
+ ],
+ "findOneApplication": [
+ 53,
+ {
+ "id": [
+ 3
+ ],
+ "universalIdentifier": [
+ 3
+ ]
+ }
+ ],
+ "findInstallApplicationJobStatus": [
+ 194,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findUninstallApplicationJobStatus": [
+ 194,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "findManyMarketplaceApps": [
+ 262,
+ {
+ "universalIdentifiers": [
+ 1,
+ "[String!]"
+ ]
+ }
+ ],
+ "findMarketplaceAppDetail": [
+ 266,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "publicMarketplaceApps": [
+ 262,
+ {
+ "isVetted": [
+ 8,
+ "Boolean!"
+ ]
+ }
+ ],
+ "publicMarketplaceAppDetail": [
+ 266,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "getSSOIdentityProviders": [
+ 253
+ ],
+ "eventLogs": [
+ 401,
+ {
+ "input": [
442,
"EventLogQueryInput!"
]
@@ -9941,172 +9941,178 @@ export default {
]
}
],
- "updateWorkspaceMemberRole": [
- 39,
+ "runAgent": [
+ 373,
{
- "workspaceMemberId": [
- 3,
- "UUID!"
- ],
- "roleId": [
- 3,
- "UUID!"
+ "input": [
+ 530,
+ "RunAgentInput!"
]
}
],
- "createOneRole": [
- 52,
+ "sendMessageCampaign": [
+ 354,
{
- "createRoleInput": [
- 530,
- "CreateRoleInput!"
+ "input": [
+ 535,
+ "SendMessageCampaignInput!"
]
}
],
- "updateOneRole": [
- 52,
+ "cancelMessageCampaign": [
+ 352,
{
- "updateRoleInput": [
- 531,
- "UpdateRoleInput!"
+ "input": [
+ 536,
+ "CancelMessageCampaignInput!"
]
}
],
- "deleteOneRole": [
- 1,
+ "sendMessageCampaignTest": [
+ 353,
{
- "roleId": [
+ "input": [
+ 537,
+ "SendMessageCampaignTestInput!"
+ ]
+ }
+ ],
+ "duplicateMessageList": [
+ 355,
+ {
+ "id": [
3,
"UUID!"
]
}
],
- "upsertObjectPermissions": [
- 49,
+ "createMessageSuppression": [
+ 356,
{
- "upsertObjectPermissionsInput": [
- 533,
- "UpsertObjectPermissionsInput!"
+ "input": [
+ 538,
+ "CreateMessageSuppressionInput!"
]
}
],
- "upsertPermissionFlags": [
- 50,
+ "deleteMessageSuppression": [
+ 8,
{
- "upsertPermissionFlagsInput": [
- 535,
- "UpsertPermissionFlagsInput!"
+ "id": [
+ 3,
+ "UUID!"
]
}
],
- "upsertFieldPermissions": [
- 44,
+ "createUnsubscribeTopic": [
+ 360,
{
- "upsertFieldPermissionsInput": [
- 536,
- "UpsertFieldPermissionsInput!"
+ "input": [
+ 539,
+ "CreateUnsubscribeTopicInput!"
]
}
],
- "upsertRowLevelPermissionPredicates": [
- 294,
+ "updateUnsubscribeTopic": [
+ 360,
{
"input": [
- 538,
- "UpsertRowLevelPermissionPredicatesInput!"
+ 540,
+ "UpdateUnsubscribeTopicInput!"
]
}
],
- "assignRoleToAgent": [
+ "deleteUnsubscribeTopic": [
8,
{
- "agentId": [
- 3,
- "UUID!"
- ],
- "roleId": [
- 3,
- "UUID!"
+ "id": [
+ 1,
+ "String!"
]
}
],
- "removeRoleFromAgent": [
- 8,
+ "updateMessageChannel": [
+ 340,
{
- "agentId": [
- 3,
- "UUID!"
+ "input": [
+ 541,
+ "UpdateMessageChannelInput!"
]
}
],
- "activateWorkspace": [
- 73,
+ "createEmailGroupChannel": [
+ 350,
{
- "data": [
- 541,
- "ActivateWorkspaceInput!"
+ "input": [
+ 543,
+ "CreateEmailGroupChannelInput!"
]
}
],
- "updateWorkspace": [
- 73,
+ "updateEmailGroupChannel": [
+ 340,
{
- "data": [
- 542,
- "UpdateWorkspaceInput!"
+ "input": [
+ 544,
+ "UpdateEmailGroupChannelInput!"
]
}
],
- "updateWorkspaceAllowedIframeOrigins": [
- 73,
+ "deleteEmailGroupChannel": [
+ 340,
{
- "data": [
- 543,
- "UpdateWorkspaceAllowedIframeOriginsInput!"
+ "id": [
+ 3,
+ "UUID!"
]
}
],
- "deleteCurrentWorkspace": [
- 73
- ],
- "checkCustomDomainValidRecords": [
- 293
+ "createAppMessageChannel": [
+ 340,
+ {
+ "input": [
+ 545,
+ "CreateAppMessageChannelInput!"
+ ]
+ }
],
- "enrichWorkspaceCompany": [
- 270
+ "updateAppMessageChannel": [
+ 340,
+ {
+ "input": [
+ 546,
+ "UpdateAppMessageChannelInput!"
+ ]
+ }
],
- "upgradeApplication": [
- 8,
+ "deleteAppMessageChannel": [
+ 340,
{
- "appRegistrationId": [
- 1,
- "String!"
- ],
- "targetVersion": [
- 1,
- "String!"
+ "id": [
+ 3,
+ "UUID!"
]
}
],
- "createApplicationRegistration": [
- 245,
+ "ingestAppMessages": [
+ 349,
{
"input": [
- 544,
- "CreateApplicationRegistrationInput!"
+ 547,
+ "IngestAppMessagesInput!"
]
}
],
- "updateApplicationRegistration": [
- 80,
+ "createEmailingDomain": [
+ 336,
{
"input": [
- 545,
- "UpdateApplicationRegistrationInput!"
+ 551,
+ "CreateEmailingDomainInput!"
]
}
],
- "deleteApplicationRegistration": [
+ "deleteEmailingDomain": [
8,
{
"id": [
@@ -10115,8 +10121,8 @@ export default {
]
}
],
- "rotateApplicationRegistrationClientSecret": [
- 247,
+ "verifyEmailingDomain": [
+ 336,
{
"id": [
1,
@@ -10124,138 +10130,126 @@ export default {
]
}
],
- "updateApplicationRegistrationVariable": [
- 217,
- {
- "input": [
- 547,
- "UpdateApplicationRegistrationVariableInput!"
- ]
- }
- ],
- "completeAppTarballUpload": [
- 80,
+ "updateWorkspaceMemberRole": [
+ 39,
{
- "fileId": [
+ "workspaceMemberId": [
+ 3,
+ "UUID!"
+ ],
+ "roleId": [
3,
"UUID!"
]
}
],
- "uploadAppTarball": [
- 80,
+ "createOneRole": [
+ 52,
{
- "file": [
- 458,
- "Upload!"
- ],
- "universalIdentifier": [
- 1
+ "createRoleInput": [
+ 552,
+ "CreateRoleInput!"
]
}
],
- "claimApplicationRegistrationOwnership": [
- 80,
+ "updateOneRole": [
+ 52,
{
- "applicationRegistrationId": [
- 1,
- "String!"
+ "updateRoleInput": [
+ 553,
+ "UpdateRoleInput!"
]
}
],
- "transferApplicationRegistrationOwnership": [
- 80,
+ "deleteOneRole": [
+ 1,
{
- "applicationRegistrationId": [
- 1,
- "String!"
- ],
- "targetWorkspaceSubdomain": [
- 1,
- "String!"
+ "roleId": [
+ 3,
+ "UUID!"
]
}
],
- "grantApplicationCapabilities": [
- 269,
+ "upsertObjectPermissions": [
+ 49,
{
- "input": [
- 549,
- "GrantApplicationCapabilitiesInput!"
+ "upsertObjectPermissionsInput": [
+ 555,
+ "UpsertObjectPermissionsInput!"
]
}
],
- "installMarketplaceApp": [
- 8,
+ "upsertPermissionFlags": [
+ 50,
{
- "universalIdentifier": [
- 1,
- "String!"
- ],
- "version": [
- 1
+ "upsertPermissionFlagsInput": [
+ 557,
+ "UpsertPermissionFlagsInput!"
]
}
],
- "installApplication": [
- 53,
+ "upsertFieldPermissions": [
+ 44,
{
- "universalIdentifier": [
- 1,
- "String!"
- ],
- "version": [
- 1
+ "upsertFieldPermissionsInput": [
+ 558,
+ "UpsertFieldPermissionsInput!"
]
}
],
- "triggerInstallApplicationJob": [
- 267,
+ "upsertRowLevelPermissionPredicates": [
+ 294,
{
"input": [
- 550,
- "TriggerInstallApplicationJobInput!"
+ 560,
+ "UpsertRowLevelPermissionPredicatesInput!"
]
}
],
- "triggerUninstallApplicationJob": [
- 268,
+ "assignRoleToAgent": [
+ 8,
{
- "input": [
- 551,
- "TriggerUninstallApplicationJobInput!"
+ "agentId": [
+ 3,
+ "UUID!"
+ ],
+ "roleId": [
+ 3,
+ "UUID!"
]
}
],
- "updateApplication": [
- 53,
+ "removeRoleFromAgent": [
+ 8,
{
- "id": [
+ "agentId": [
3,
"UUID!"
- ],
- "input": [
- 552,
- "UpdateApplicationInput!"
]
}
],
- "uninstallApplication": [
- 8,
+ "createWebhook": [
+ 369,
{
- "universalIdentifier": [
- 1,
- "String!"
+ "input": [
+ 563,
+ "CreateWebhookInput!"
]
}
],
- "syncMarketplaceCatalog": [
- 8
+ "updateWebhook": [
+ 369,
+ {
+ "input": [
+ 564,
+ "UpdateWebhookInput!"
+ ]
+ }
],
- "runApplicationHealthCheck": [
- 260,
+ "deleteWebhook": [
+ 369,
{
- "applicationId": [
+ "id": [
3,
"UUID!"
]
@@ -10265,7 +10259,7 @@ export default {
273,
{
"input": [
- 553,
+ 566,
"CreateOneFieldMetadataInput!"
]
}
@@ -10274,7 +10268,7 @@ export default {
273,
{
"input": [
- 555,
+ 568,
"UpdateOneFieldMetadataInput!"
]
}
@@ -10283,7 +10277,7 @@ export default {
273,
{
"input": [
- 557,
+ 570,
"DeleteOneFieldInput!"
]
}
@@ -10292,7 +10286,7 @@ export default {
63,
{
"input": [
- 558,
+ 571,
"CreateViewGroupInput!"
]
}
@@ -10301,7 +10295,7 @@ export default {
63,
{
"inputs": [
- 558,
+ 571,
"[CreateViewGroupInput!]!"
]
}
@@ -10310,7 +10304,7 @@ export default {
63,
{
"input": [
- 559,
+ 572,
"UpdateViewGroupInput!"
]
}
@@ -10319,7 +10313,7 @@ export default {
63,
{
"inputs": [
- 559,
+ 572,
"[UpdateViewGroupInput!]!"
]
}
@@ -10328,233 +10322,17 @@ export default {
63,
{
"input": [
- 561,
+ 574,
"DeleteViewGroupInput!"
]
}
],
"destroyViewGroup": [
63,
- {
- "input": [
- 562,
- "DestroyViewGroupInput!"
- ]
- }
- ],
- "sendMessageCampaign": [
- 354,
- {
- "input": [
- 563,
- "SendMessageCampaignInput!"
- ]
- }
- ],
- "cancelMessageCampaign": [
- 352,
- {
- "input": [
- 564,
- "CancelMessageCampaignInput!"
- ]
- }
- ],
- "sendMessageCampaignTest": [
- 353,
- {
- "input": [
- 565,
- "SendMessageCampaignTestInput!"
- ]
- }
- ],
- "duplicateMessageList": [
- 355,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "createMessageSuppression": [
- 356,
- {
- "input": [
- 566,
- "CreateMessageSuppressionInput!"
- ]
- }
- ],
- "deleteMessageSuppression": [
- 8,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "createUnsubscribeTopic": [
- 360,
- {
- "input": [
- 567,
- "CreateUnsubscribeTopicInput!"
- ]
- }
- ],
- "updateUnsubscribeTopic": [
- 360,
- {
- "input": [
- 568,
- "UpdateUnsubscribeTopicInput!"
- ]
- }
- ],
- "deleteUnsubscribeTopic": [
- 8,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "updateMessageChannel": [
- 340,
- {
- "input": [
- 569,
- "UpdateMessageChannelInput!"
- ]
- }
- ],
- "createEmailGroupChannel": [
- 350,
- {
- "input": [
- 571,
- "CreateEmailGroupChannelInput!"
- ]
- }
- ],
- "updateEmailGroupChannel": [
- 340,
- {
- "input": [
- 572,
- "UpdateEmailGroupChannelInput!"
- ]
- }
- ],
- "deleteEmailGroupChannel": [
- 340,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "createAppMessageChannel": [
- 340,
- {
- "input": [
- 573,
- "CreateAppMessageChannelInput!"
- ]
- }
- ],
- "updateAppMessageChannel": [
- 340,
- {
- "input": [
- 574,
- "UpdateAppMessageChannelInput!"
- ]
- }
- ],
- "deleteAppMessageChannel": [
- 340,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "ingestAppMessages": [
- 349,
{
"input": [
575,
- "IngestAppMessagesInput!"
- ]
- }
- ],
- "createEmailingDomain": [
- 336,
- {
- "input": [
- 579,
- "CreateEmailingDomainInput!"
- ]
- }
- ],
- "deleteEmailingDomain": [
- 8,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "verifyEmailingDomain": [
- 336,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "createWebhook": [
- 369,
- {
- "input": [
- 580,
- "CreateWebhookInput!"
- ]
- }
- ],
- "updateWebhook": [
- 369,
- {
- "input": [
- 581,
- "UpdateWebhookInput!"
- ]
- }
- ],
- "deleteWebhook": [
- 369,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "runAgent": [
- 373,
- {
- "input": [
- 583,
- "RunAgentInput!"
+ "DestroyViewGroupInput!"
]
}
],
@@ -10562,7 +10340,7 @@ export default {
415,
{
"input": [
- 588,
+ 576,
"UpdateMessageFolderInput!"
]
}
@@ -10571,7 +10349,7 @@ export default {
415,
{
"input": [
- 590,
+ 578,
"UpdateMessageFoldersInput!"
]
}
@@ -10580,7 +10358,7 @@ export default {
410,
{
"input": [
- 591,
+ 579,
"UpdateCalendarChannelInput!"
]
}
@@ -10589,7 +10367,7 @@ export default {
408,
{
"input": [
- 593,
+ 581,
"SetAppKeyValueInput!"
]
}
@@ -10610,7 +10388,7 @@ export default {
406,
{
"input": [
- 594,
+ 582,
"EnqueueJobInput!"
]
}
@@ -10619,7 +10397,7 @@ export default {
407,
{
"input": [
- 595,
+ 583,
"EnqueueJobsInput!"
]
}
@@ -10628,7 +10406,7 @@ export default {
8,
{
"input": [
- 597,
+ 585,
"ReportAppConnectionAuthFailureInput!"
]
}
@@ -10658,7 +10436,7 @@ export default {
1
],
"fileAttachments": [
- 598,
+ 586,
"[FileAttachmentInput!]"
]
}
@@ -10770,7 +10548,7 @@ export default {
394,
{
"input": [
- 599,
+ 587,
"SendInboxMessageInput!"
]
}
@@ -10779,7 +10557,7 @@ export default {
385,
{
"input": [
- 600,
+ 588,
"CreateSkillInput!"
]
}
@@ -10788,7 +10566,7 @@ export default {
385,
{
"input": [
- 601,
+ 589,
"UpdateSkillInput!"
]
}
@@ -10824,7 +10602,7 @@ export default {
422,
{
"input": [
- 602,
+ 590,
"CreateValidationRuleInput!"
]
}
@@ -10833,7 +10611,7 @@ export default {
422,
{
"input": [
- 603,
+ 591,
"UpdateValidationRuleInput!"
]
}
@@ -10851,7 +10629,7 @@ export default {
421,
{
"input": [
- 605,
+ 593,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -10869,7 +10647,7 @@ export default {
303,
{
"input": [
- 606,
+ 594,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -11035,7 +10813,7 @@ export default {
306,
{
"input": [
- 607
+ 595
]
}
],
@@ -11193,20 +10971,108 @@ export default {
]
}
],
- "initiateOTPProvisioning": [
- 297,
+ "createApplicationRegistration": [
+ 245,
{
- "loginToken": [
- 1,
- "String!"
- ],
- "origin": [
- 1,
- "String!"
+ "input": [
+ 596,
+ "CreateApplicationRegistrationInput!"
]
}
],
- "initiateOTPProvisioningForAuthenticatedUser": [
+ "updateApplicationRegistration": [
+ 80,
+ {
+ "input": [
+ 597,
+ "UpdateApplicationRegistrationInput!"
+ ]
+ }
+ ],
+ "deleteApplicationRegistration": [
+ 8,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "rotateApplicationRegistrationClientSecret": [
+ 247,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "updateApplicationRegistrationVariable": [
+ 217,
+ {
+ "input": [
+ 599,
+ "UpdateApplicationRegistrationVariableInput!"
+ ]
+ }
+ ],
+ "completeAppTarballUpload": [
+ 80,
+ {
+ "fileId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "uploadAppTarball": [
+ 80,
+ {
+ "file": [
+ 458,
+ "Upload!"
+ ],
+ "universalIdentifier": [
+ 1
+ ]
+ }
+ ],
+ "claimApplicationRegistrationOwnership": [
+ 80,
+ {
+ "applicationRegistrationId": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "transferApplicationRegistrationOwnership": [
+ 80,
+ {
+ "applicationRegistrationId": [
+ 1,
+ "String!"
+ ],
+ "targetWorkspaceSubdomain": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "initiateOTPProvisioning": [
+ 297,
+ {
+ "loginToken": [
+ 1,
+ "String!"
+ ],
+ "origin": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "initiateOTPProvisioningForAuthenticatedUser": [
297
],
"deleteTwoFactorAuthenticationMethod": [
@@ -11243,7 +11109,7 @@ export default {
8,
{
"input": [
- 608,
+ 601,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -11273,6 +11139,140 @@ export default {
]
}
],
+ "activateWorkspace": [
+ 73,
+ {
+ "data": [
+ 602,
+ "ActivateWorkspaceInput!"
+ ]
+ }
+ ],
+ "updateWorkspace": [
+ 73,
+ {
+ "data": [
+ 603,
+ "UpdateWorkspaceInput!"
+ ]
+ }
+ ],
+ "updateWorkspaceAllowedIframeOrigins": [
+ 73,
+ {
+ "data": [
+ 604,
+ "UpdateWorkspaceAllowedIframeOriginsInput!"
+ ]
+ }
+ ],
+ "deleteCurrentWorkspace": [
+ 73
+ ],
+ "checkCustomDomainValidRecords": [
+ 293
+ ],
+ "enrichWorkspaceCompany": [
+ 270
+ ],
+ "upgradeApplication": [
+ 8,
+ {
+ "appRegistrationId": [
+ 1,
+ "String!"
+ ],
+ "targetVersion": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "grantApplicationCapabilities": [
+ 269,
+ {
+ "input": [
+ 605,
+ "GrantApplicationCapabilitiesInput!"
+ ]
+ }
+ ],
+ "installMarketplaceApp": [
+ 8,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ],
+ "version": [
+ 1
+ ]
+ }
+ ],
+ "installApplication": [
+ 53,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ],
+ "version": [
+ 1
+ ]
+ }
+ ],
+ "triggerInstallApplicationJob": [
+ 267,
+ {
+ "input": [
+ 606,
+ "TriggerInstallApplicationJobInput!"
+ ]
+ }
+ ],
+ "triggerUninstallApplicationJob": [
+ 268,
+ {
+ "input": [
+ 607,
+ "TriggerUninstallApplicationJobInput!"
+ ]
+ }
+ ],
+ "updateApplication": [
+ 53,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ],
+ "input": [
+ 608,
+ "UpdateApplicationInput!"
+ ]
+ }
+ ],
+ "uninstallApplication": [
+ 8,
+ {
+ "universalIdentifier": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "syncMarketplaceCatalog": [
+ 8
+ ],
+ "runApplicationHealthCheck": [
+ 260,
+ {
+ "applicationId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
"createOIDCIdentityProvider": [
254,
{
@@ -13114,443 +13114,584 @@ export default {
1
]
},
- "CreateRoleInput": {
- "id": [
- 1
- ],
- "label": [
+ "RunAgentInput": {
+ "agentUniversalIdentifier": [
1
],
- "description": [
+ "prompt": [
1
],
- "icon": [
- 1
+ "runAsWorkspaceMemberId": [
+ 3
],
- "canUpdateAllSettings": [
- 8
+ "messages": [
+ 531
],
- "canAccessAllTools": [
- 8
+ "input": [
+ 531
],
- "canReadAllObjectRecords": [
- 8
+ "additionalInstructions": [
+ 1
],
- "canUpdateAllObjectRecords": [
- 8
+ "thread": [
+ 534
],
- "canSoftDeleteAllObjectRecords": [
- 8
+ "__typename": [
+ 1
+ ]
+ },
+ "RunAgentMessageInput": {
+ "role": [
+ 532
],
- "canDestroyAllObjectRecords": [
- 8
+ "content": [
+ 1
],
- "canBeAssignedToUsers": [
- 8
+ "attachments": [
+ 533
],
- "canBeAssignedToAgents": [
- 8
+ "__typename": [
+ 1
+ ]
+ },
+ "RunAgentMessageRole": {},
+ "RunAgentMessageAttachmentInput": {
+ "fileId": [
+ 3
],
- "canBeAssignedToApiKeys": [
- 8
+ "filename": [
+ 1
],
"__typename": [
1
]
},
- "UpdateRoleInput": {
- "update": [
- 532
+ "RunAgentThreadInput": {
+ "key": [
+ 1
],
- "id": [
- 3
+ "title": [
+ 1
],
"__typename": [
1
]
},
- "UpdateRolePayload": {
- "label": [
+ "SendMessageCampaignInput": {
+ "campaignId": [
1
],
- "description": [
+ "scheduledAt": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "CancelMessageCampaignInput": {
+ "campaignId": [
1
],
- "icon": [
+ "__typename": [
+ 1
+ ]
+ },
+ "SendMessageCampaignTestInput": {
+ "toAddress": [
1
],
- "canUpdateAllSettings": [
- 8
+ "unsubscribeTopicId": [
+ 1
],
- "canAccessAllTools": [
- 8
+ "subject": [
+ 1
],
- "canReadAllObjectRecords": [
- 8
+ "body": [
+ 1
],
- "canUpdateAllObjectRecords": [
- 8
+ "fromAddress": [
+ 1
],
- "canSoftDeleteAllObjectRecords": [
- 8
+ "__typename": [
+ 1
+ ]
+ },
+ "CreateMessageSuppressionInput": {
+ "emailAddress": [
+ 1
],
- "canDestroyAllObjectRecords": [
- 8
+ "unsubscribeTopicId": [
+ 3
],
- "canBeAssignedToUsers": [
- 8
+ "__typename": [
+ 1
+ ]
+ },
+ "CreateUnsubscribeTopicInput": {
+ "name": [
+ 1
],
- "canBeAssignedToAgents": [
- 8
+ "description": [
+ 1
],
- "canBeAssignedToApiKeys": [
- 8
+ "visibility": [
+ 361
],
"__typename": [
1
]
},
- "UpsertObjectPermissionsInput": {
- "roleId": [
- 3
+ "UpdateUnsubscribeTopicInput": {
+ "id": [
+ 1
],
- "objectPermissions": [
- 534
+ "name": [
+ 1
+ ],
+ "description": [
+ 1
+ ],
+ "visibility": [
+ 361
],
"__typename": [
1
]
},
- "ObjectPermissionInput": {
- "objectMetadataId": [
+ "UpdateMessageChannelInput": {
+ "id": [
3
],
- "canReadObjectRecords": [
+ "update": [
+ 542
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateMessageChannelInputUpdates": {
+ "visibility": [
+ 341
+ ],
+ "isContactAutoCreationEnabled": [
8
],
- "canUpdateObjectRecords": [
+ "contactAutoCreationPolicy": [
+ 343
+ ],
+ "messageFolderImportPolicy": [
+ 344
+ ],
+ "isSyncEnabled": [
8
],
- "canSoftDeleteObjectRecords": [
+ "excludeNonProfessionalEmails": [
8
],
- "canDestroyObjectRecords": [
+ "excludeGroupEmails": [
8
],
"__typename": [
1
]
},
- "UpsertPermissionFlagsInput": {
- "roleId": [
- 3
+ "CreateEmailGroupChannelInput": {
+ "handle": [
+ 1
],
- "permissionFlagKeys": [
+ "displayName": [
1
],
"__typename": [
1
]
},
- "UpsertFieldPermissionsInput": {
- "roleId": [
+ "UpdateEmailGroupChannelInput": {
+ "id": [
3
],
- "fieldPermissions": [
- 537
+ "displayName": [
+ 1
],
"__typename": [
1
]
},
- "FieldPermissionInput": {
- "objectMetadataId": [
+ "CreateAppMessageChannelInput": {
+ "connectedAccountId": [
3
],
- "fieldMetadataId": [
- 3
+ "handle": [
+ 1
],
- "canReadFieldValue": [
- 8
+ "displayName": [
+ 1
],
- "canUpdateFieldValue": [
- 8
+ "visibility": [
+ 341
],
"__typename": [
1
]
},
- "UpsertRowLevelPermissionPredicatesInput": {
- "roleId": [
+ "UpdateAppMessageChannelInput": {
+ "id": [
3
],
- "objectMetadataId": [
- 3
+ "displayName": [
+ 1
],
- "predicates": [
- 539
+ "visibility": [
+ 341
],
- "predicateGroups": [
- 540
+ "isSyncEnabled": [
+ 8
],
"__typename": [
1
]
},
- "RowLevelPermissionPredicateInput": {
- "id": [
- 3
- ],
- "fieldMetadataId": [
+ "IngestAppMessagesInput": {
+ "messageChannelId": [
3
],
- "operand": [
- 48
+ "messages": [
+ 548
],
- "value": [
- 9
+ "__typename": [
+ 1
+ ]
+ },
+ "AppMessageInput": {
+ "externalId": [
+ 1
],
- "subFieldName": [
+ "threadExternalId": [
1
],
- "workspaceMemberFieldMetadataId": [
+ "subject": [
1
],
- "workspaceMemberSubFieldName": [
+ "text": [
1
],
- "rowLevelPermissionPredicateGroupId": [
- 3
+ "receivedAt": [
+ 4
],
- "positionInRowLevelPermissionPredicateGroup": [
- 16
+ "participants": [
+ 549
],
"__typename": [
1
]
},
- "RowLevelPermissionPredicateGroupInput": {
- "id": [
- 3
+ "AppMessageParticipantInput": {
+ "role": [
+ 550
],
- "objectMetadataId": [
- 3
+ "handle": [
+ 1
],
- "parentRowLevelPermissionPredicateGroupId": [
- 3
+ "displayName": [
+ 1
],
- "logicalOperator": [
- 46
+ "personId": [
+ 3
],
- "positionInRowLevelPermissionPredicateGroup": [
- 16
+ "workspaceMemberId": [
+ 3
],
"__typename": [
1
]
},
- "ActivateWorkspaceInput": {
- "displayName": [
+ "MessageParticipantRole": {},
+ "CreateEmailingDomainInput": {
+ "domain": [
1
],
"__typename": [
1
]
},
- "UpdateWorkspaceInput": {
- "subdomain": [
- 1
- ],
- "customDomain": [
+ "CreateRoleInput": {
+ "id": [
1
],
- "displayName": [
+ "label": [
1
],
- "logo": [
+ "description": [
1
],
- "inviteHash": [
+ "icon": [
1
],
- "isPublicInviteLinkEnabled": [
+ "canUpdateAllSettings": [
8
],
- "isCampaignClickTrackingEnabled": [
+ "canAccessAllTools": [
8
],
- "workspaceDiscoverability": [
- 74
- ],
- "allowImpersonation": [
+ "canReadAllObjectRecords": [
8
],
- "isGoogleAuthEnabled": [
+ "canUpdateAllObjectRecords": [
8
],
- "isMicrosoftAuthEnabled": [
+ "canSoftDeleteAllObjectRecords": [
8
],
- "isPasswordAuthEnabled": [
+ "canDestroyAllObjectRecords": [
8
],
- "isGoogleAuthBypassEnabled": [
+ "canBeAssignedToUsers": [
8
],
- "isMicrosoftAuthBypassEnabled": [
+ "canBeAssignedToAgents": [
8
],
- "isPasswordAuthBypassEnabled": [
+ "canBeAssignedToApiKeys": [
8
],
- "defaultRoleId": [
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateRoleInput": {
+ "update": [
+ 554
+ ],
+ "id": [
3
],
- "isTwoFactorAuthenticationEnforced": [
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateRolePayload": {
+ "label": [
+ 1
+ ],
+ "description": [
+ 1
+ ],
+ "icon": [
+ 1
+ ],
+ "canUpdateAllSettings": [
8
],
- "trashRetentionDays": [
- 16
+ "canAccessAllTools": [
+ 8
],
- "eventLogRetentionDays": [
- 16
+ "canReadAllObjectRecords": [
+ 8
],
- "aiChatModelTier": [
- 76
+ "canUpdateAllObjectRecords": [
+ 8
],
- "aiAgentModelTier": [
- 76
+ "canSoftDeleteAllObjectRecords": [
+ 8
],
- "isAutoModelSelectionEnabled": [
+ "canDestroyAllObjectRecords": [
8
],
- "aiModelIdByTier": [
- 9
+ "canBeAssignedToUsers": [
+ 8
],
- "aiEvaluationModelId": [
- 1
+ "canBeAssignedToAgents": [
+ 8
],
- "aiAdditionalInstructions": [
+ "canBeAssignedToApiKeys": [
+ 8
+ ],
+ "__typename": [
1
+ ]
+ },
+ "UpsertObjectPermissionsInput": {
+ "roleId": [
+ 3
],
- "editableProfileFields": [
+ "objectPermissions": [
+ 556
+ ],
+ "__typename": [
1
+ ]
+ },
+ "ObjectPermissionInput": {
+ "objectMetadataId": [
+ 3
],
- "isInternalMessagesImportEnabled": [
+ "canReadObjectRecords": [
+ 8
+ ],
+ "canUpdateObjectRecords": [
+ 8
+ ],
+ "canSoftDeleteObjectRecords": [
+ 8
+ ],
+ "canDestroyObjectRecords": [
8
],
"__typename": [
1
]
},
- "UpdateWorkspaceAllowedIframeOriginsInput": {
- "operation": [
- 1
+ "UpsertPermissionFlagsInput": {
+ "roleId": [
+ 3
],
- "origin": [
+ "permissionFlagKeys": [
1
],
"__typename": [
1
]
},
- "CreateApplicationRegistrationInput": {
- "name": [
- 1
+ "UpsertFieldPermissionsInput": {
+ "roleId": [
+ 3
],
- "universalIdentifier": [
- 1
+ "fieldPermissions": [
+ 559
],
- "oAuthRedirectUris": [
+ "__typename": [
1
+ ]
+ },
+ "FieldPermissionInput": {
+ "objectMetadataId": [
+ 3
],
- "oAuthScopes": [
- 1
+ "fieldMetadataId": [
+ 3
+ ],
+ "canReadFieldValue": [
+ 8
+ ],
+ "canUpdateFieldValue": [
+ 8
],
"__typename": [
1
]
},
- "UpdateApplicationRegistrationInput": {
- "id": [
- 1
+ "UpsertRowLevelPermissionPredicatesInput": {
+ "roleId": [
+ 3
],
- "update": [
- 546
+ "objectMetadataId": [
+ 3
+ ],
+ "predicates": [
+ 561
+ ],
+ "predicateGroups": [
+ 562
],
"__typename": [
1
]
},
- "UpdateApplicationRegistrationPayload": {
- "name": [
+ "RowLevelPermissionPredicateInput": {
+ "id": [
+ 3
+ ],
+ "fieldMetadataId": [
+ 3
+ ],
+ "operand": [
+ 48
+ ],
+ "value": [
+ 9
+ ],
+ "subFieldName": [
1
],
- "oAuthRedirectUris": [
+ "workspaceMemberFieldMetadataId": [
1
],
- "oAuthScopes": [
+ "workspaceMemberSubFieldName": [
1
],
+ "rowLevelPermissionPredicateGroupId": [
+ 3
+ ],
+ "positionInRowLevelPermissionPredicateGroup": [
+ 16
+ ],
"__typename": [
1
]
},
- "UpdateApplicationRegistrationVariableInput": {
+ "RowLevelPermissionPredicateGroupInput": {
"id": [
- 1
+ 3
],
- "update": [
- 548
+ "objectMetadataId": [
+ 3
+ ],
+ "parentRowLevelPermissionPredicateGroupId": [
+ 3
+ ],
+ "logicalOperator": [
+ 46
+ ],
+ "positionInRowLevelPermissionPredicateGroup": [
+ 16
],
"__typename": [
1
]
},
- "UpdateApplicationRegistrationVariablePayload": {
- "value": [
+ "CreateWebhookInput": {
+ "id": [
+ 3
+ ],
+ "targetUrl": [
1
],
- "resetValue": [
- 8
+ "operations": [
+ 1
],
"description": [
1
],
+ "secret": [
+ 1
+ ],
"__typename": [
1
]
},
- "GrantApplicationCapabilitiesInput": {
- "applicationId": [
+ "UpdateWebhookInput": {
+ "id": [
3
],
- "capabilities": [
- 1
+ "update": [
+ 565
],
"__typename": [
1
]
},
- "TriggerInstallApplicationJobInput": {
- "universalIdentifier": [
+ "UpdateWebhookInputUpdates": {
+ "targetUrl": [
1
],
- "__typename": [
+ "operations": [
1
- ]
- },
- "TriggerUninstallApplicationJobInput": {
- "universalIdentifier": [
+ ],
+ "description": [
1
],
- "__typename": [
+ "secret": [
1
- ]
- },
- "UpdateApplicationInput": {
- "autoUpgrade": [
- 8
],
"__typename": [
1
@@ -13558,7 +13699,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 554
+ 567
],
"__typename": [
1
@@ -13637,7 +13778,7 @@ export default {
3
],
"update": [
- 556
+ 569
],
"__typename": [
1
@@ -13720,409 +13861,61 @@ export default {
"id": [
3
],
- "isVisible": [
- 8
- ],
- "fieldValue": [
- 1
- ],
- "position": [
- 16
- ],
- "viewId": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewGroupInput": {
- "id": [
- 3
- ],
- "update": [
- 560
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewGroupInputUpdates": {
- "fieldMetadataId": [
- 3
- ],
- "isVisible": [
- 8
- ],
- "fieldValue": [
- 1
- ],
- "position": [
- 16
- ],
- "__typename": [
- 1
- ]
- },
- "DeleteViewGroupInput": {
- "id": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "DestroyViewGroupInput": {
- "id": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "SendMessageCampaignInput": {
- "campaignId": [
- 1
- ],
- "scheduledAt": [
- 4
- ],
- "__typename": [
- 1
- ]
- },
- "CancelMessageCampaignInput": {
- "campaignId": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "SendMessageCampaignTestInput": {
- "toAddress": [
- 1
- ],
- "unsubscribeTopicId": [
- 1
- ],
- "subject": [
- 1
- ],
- "body": [
- 1
- ],
- "fromAddress": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "CreateMessageSuppressionInput": {
- "emailAddress": [
- 1
- ],
- "unsubscribeTopicId": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "CreateUnsubscribeTopicInput": {
- "name": [
- 1
- ],
- "description": [
- 1
- ],
- "visibility": [
- 361
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateUnsubscribeTopicInput": {
- "id": [
- 1
- ],
- "name": [
- 1
- ],
- "description": [
- 1
- ],
- "visibility": [
- 361
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateMessageChannelInput": {
- "id": [
- 3
- ],
- "update": [
- 570
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateMessageChannelInputUpdates": {
- "visibility": [
- 341
- ],
- "isContactAutoCreationEnabled": [
- 8
- ],
- "contactAutoCreationPolicy": [
- 343
- ],
- "messageFolderImportPolicy": [
- 344
- ],
- "isSyncEnabled": [
- 8
- ],
- "excludeNonProfessionalEmails": [
- 8
- ],
- "excludeGroupEmails": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "CreateEmailGroupChannelInput": {
- "handle": [
- 1
- ],
- "displayName": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateEmailGroupChannelInput": {
- "id": [
- 3
- ],
- "displayName": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "CreateAppMessageChannelInput": {
- "connectedAccountId": [
- 3
- ],
- "handle": [
- 1
- ],
- "displayName": [
- 1
- ],
- "visibility": [
- 341
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateAppMessageChannelInput": {
- "id": [
- 3
- ],
- "displayName": [
- 1
- ],
- "visibility": [
- 341
- ],
- "isSyncEnabled": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "IngestAppMessagesInput": {
- "messageChannelId": [
- 3
- ],
- "messages": [
- 576
- ],
- "__typename": [
- 1
- ]
- },
- "AppMessageInput": {
- "externalId": [
- 1
- ],
- "threadExternalId": [
- 1
- ],
- "subject": [
- 1
- ],
- "text": [
- 1
- ],
- "receivedAt": [
- 4
- ],
- "participants": [
- 577
- ],
- "__typename": [
- 1
- ]
- },
- "AppMessageParticipantInput": {
- "role": [
- 578
- ],
- "handle": [
- 1
- ],
- "displayName": [
- 1
- ],
- "personId": [
- 3
- ],
- "workspaceMemberId": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "MessageParticipantRole": {},
- "CreateEmailingDomainInput": {
- "domain": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "CreateWebhookInput": {
- "id": [
- 3
- ],
- "targetUrl": [
- 1
- ],
- "operations": [
- 1
- ],
- "description": [
- 1
- ],
- "secret": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateWebhookInput": {
- "id": [
- 3
- ],
- "update": [
- 582
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateWebhookInputUpdates": {
- "targetUrl": [
- 1
- ],
- "operations": [
- 1
- ],
- "description": [
- 1
- ],
- "secret": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "RunAgentInput": {
- "agentUniversalIdentifier": [
- 1
- ],
- "prompt": [
- 1
- ],
- "runAsWorkspaceMemberId": [
- 3
- ],
- "messages": [
- 584
- ],
- "input": [
- 584
+ "isVisible": [
+ 8
],
- "additionalInstructions": [
+ "fieldValue": [
1
],
- "thread": [
- 587
+ "position": [
+ 16
+ ],
+ "viewId": [
+ 3
],
"__typename": [
1
]
},
- "RunAgentMessageInput": {
- "role": [
- 585
- ],
- "content": [
- 1
+ "UpdateViewGroupInput": {
+ "id": [
+ 3
],
- "attachments": [
- 586
+ "update": [
+ 573
],
"__typename": [
1
]
},
- "RunAgentMessageRole": {},
- "RunAgentMessageAttachmentInput": {
- "fileId": [
+ "UpdateViewGroupInputUpdates": {
+ "fieldMetadataId": [
3
],
- "filename": [
+ "isVisible": [
+ 8
+ ],
+ "fieldValue": [
1
],
+ "position": [
+ 16
+ ],
"__typename": [
1
]
},
- "RunAgentThreadInput": {
- "key": [
- 1
+ "DeleteViewGroupInput": {
+ "id": [
+ 3
],
- "title": [
+ "__typename": [
1
+ ]
+ },
+ "DestroyViewGroupInput": {
+ "id": [
+ 3
],
"__typename": [
1
@@ -14133,7 +13926,7 @@ export default {
3
],
"update": [
- 589
+ 577
],
"__typename": [
1
@@ -14152,7 +13945,7 @@ export default {
3
],
"update": [
- 589
+ 577
],
"__typename": [
1
@@ -14163,7 +13956,7 @@ export default {
3
],
"update": [
- 592
+ 580
],
"__typename": [
1
@@ -14228,7 +14021,7 @@ export default {
9
],
"jobs": [
- 596
+ 584
],
"retryLimit": [
32
@@ -14379,7 +14172,7 @@ export default {
3
],
"update": [
- 604
+ 592
],
"__typename": [
1
@@ -14453,6 +14246,73 @@ export default {
1
]
},
+ "CreateApplicationRegistrationInput": {
+ "name": [
+ 1
+ ],
+ "universalIdentifier": [
+ 1
+ ],
+ "oAuthRedirectUris": [
+ 1
+ ],
+ "oAuthScopes": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApplicationRegistrationInput": {
+ "id": [
+ 1
+ ],
+ "update": [
+ 598
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApplicationRegistrationPayload": {
+ "name": [
+ 1
+ ],
+ "oAuthRedirectUris": [
+ 1
+ ],
+ "oAuthScopes": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApplicationRegistrationVariableInput": {
+ "id": [
+ 1
+ ],
+ "update": [
+ 600
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApplicationRegistrationVariablePayload": {
+ "value": [
+ 1
+ ],
+ "resetValue": [
+ 8
+ ],
+ "description": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"UpdateWorkspaceMemberSettingsInput": {
"workspaceMemberId": [
3
@@ -14464,6 +14324,146 @@ export default {
1
]
},
+ "ActivateWorkspaceInput": {
+ "displayName": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateWorkspaceInput": {
+ "subdomain": [
+ 1
+ ],
+ "customDomain": [
+ 1
+ ],
+ "displayName": [
+ 1
+ ],
+ "logo": [
+ 1
+ ],
+ "inviteHash": [
+ 1
+ ],
+ "isPublicInviteLinkEnabled": [
+ 8
+ ],
+ "isCampaignClickTrackingEnabled": [
+ 8
+ ],
+ "workspaceDiscoverability": [
+ 74
+ ],
+ "allowImpersonation": [
+ 8
+ ],
+ "isGoogleAuthEnabled": [
+ 8
+ ],
+ "isMicrosoftAuthEnabled": [
+ 8
+ ],
+ "isPasswordAuthEnabled": [
+ 8
+ ],
+ "isGoogleAuthBypassEnabled": [
+ 8
+ ],
+ "isMicrosoftAuthBypassEnabled": [
+ 8
+ ],
+ "isPasswordAuthBypassEnabled": [
+ 8
+ ],
+ "defaultRoleId": [
+ 3
+ ],
+ "isTwoFactorAuthenticationEnforced": [
+ 8
+ ],
+ "trashRetentionDays": [
+ 16
+ ],
+ "eventLogRetentionDays": [
+ 16
+ ],
+ "aiChatModelTier": [
+ 76
+ ],
+ "aiAgentModelTier": [
+ 76
+ ],
+ "isAutoModelSelectionEnabled": [
+ 8
+ ],
+ "aiModelIdByTier": [
+ 9
+ ],
+ "aiEvaluationModelId": [
+ 1
+ ],
+ "aiAdditionalInstructions": [
+ 1
+ ],
+ "editableProfileFields": [
+ 1
+ ],
+ "isInternalMessagesImportEnabled": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateWorkspaceAllowedIframeOriginsInput": {
+ "operation": [
+ 1
+ ],
+ "origin": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GrantApplicationCapabilitiesInput": {
+ "applicationId": [
+ 3
+ ],
+ "capabilities": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "TriggerInstallApplicationJobInput": {
+ "universalIdentifier": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "TriggerUninstallApplicationJobInput": {
+ "universalIdentifier": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApplicationInput": {
+ "autoUpgrade": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"SetupOIDCSsoInput": {
"name": [
1
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-resolver.service.spec.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-resolver.service.spec.ts
deleted file mode 100644
index a6248d16d59..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up-resolver.service.spec.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
-import { PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';
-import { type PendingWakeUpBeforeClaimDecision } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
-
-const WORKSPACE_ID = 'workspace-id';
-const WAKE_UP_ID = 'wake-up-id';
-
-const EVENT = {
- eventName: 'company.updated',
- recordId: 'company-id',
- record: { id: 'company-id', name: 'Acme' },
-};
-
-const STORED_WAKE_UP = {
- id: WAKE_UP_ID,
- workspaceId: WORKSPACE_ID,
- ownerType: 'WORKFLOW_STEP',
- ownerId: 'owner-id',
- ownerKey: 'owner-key',
- condition: { type: 'EVENT', eventName: 'company.updated' },
-};
-
-const buildService = ({
- storedWakeUp = STORED_WAKE_UP,
- claimedWakeUp = storedWakeUp,
- decision = { type: 'RESOLVE', context: 'context' },
-}: {
- storedWakeUp?: object | null;
- claimedWakeUp?: object | null;
- decision?: PendingWakeUpBeforeClaimDecision<string>;
-} = {}) => {
- const pendingWakeUpService = {
- find: jest.fn().mockResolvedValue(storedWakeUp),
- claim: jest.fn().mockResolvedValue(claimedWakeUp),
- scheduleResolution: jest.fn(),
- };
- const handler = {
- ownerType: 'WORKFLOW_STEP' as const,
- buildResumeJobOptions: jest.fn(),
- beforeClaim: jest.fn().mockResolvedValue(decision),
- resolve: jest.fn(),
- };
- const registry = new PendingWakeUpOwnerHandlerRegistryService();
-
- registry.register(handler);
-
- const service = new PendingWakeUpResolverService(
- pendingWakeUpService as never,
- registry,
- );
-
- return { service, pendingWakeUpService, handler };
-};
-
-describe('PendingWakeUpResolverService', () => {
- it('does nothing when the wake-up was already resolved or cancelled', async () => {
- const { service, handler } = buildService({ storedWakeUp: null });
-
- await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAKE_UP_ID });
-
- expect(handler.beforeClaim).not.toHaveBeenCalled();
- expect(handler.resolve).not.toHaveBeenCalled();
- });
-
- it('claims the wake-up and hands the event to its owner', async () => {
- const { service, pendingWakeUpService, handler } = buildService();
-
- await service.resolve({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- event: EVENT,
- });
-
- expect(pendingWakeUpService.claim).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- });
- expect(handler.resolve).toHaveBeenCalledWith({
- claimedWakeUp: STORED_WAKE_UP,
- outcome: { type: 'EVENT_RECEIVED', event: EVENT },
- context: 'context',
- });
- });
-
- it('hands over the event as the owner restricted it', async () => {
- const restrictedEvent = { ...EVENT, record: { id: 'company-id' } };
- const { service, handler } = buildService({
- decision: { type: 'RESOLVE', event: restrictedEvent, context: 'context' },
- });
-
- await service.resolve({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- event: EVENT,
- });
-
- expect(handler.resolve).toHaveBeenCalledWith(
- expect.objectContaining({
- outcome: { type: 'EVENT_RECEIVED', event: restrictedEvent },
- }),
- );
- });
-
- it('reports an expiry when an event wake-up resolves without an event', async () => {
- const { service, handler } = buildService();
-
- await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAKE_UP_ID });
-
- expect(handler.resolve).toHaveBeenCalledWith(
- expect.objectContaining({ outcome: { type: 'EXPIRED' } }),
- );
- });
-
- it('starts the attempt counters at zero for the owner', async () => {
- const { service, handler } = buildService();
-
- await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAKE_UP_ID });
-
- expect(handler.beforeClaim).toHaveBeenCalledWith({
- wakeUp: STORED_WAKE_UP,
- event: undefined,
- attempt: 0,
- recordReadAttempt: 0,
- });
- });
-
- it('puts the resolution off with the counters the owner asks for', async () => {
- const { service, pendingWakeUpService, handler } = buildService({
- decision: { type: 'RETRY_LATER', delayMs: 4_000, recordReadAttempt: 2 },
- });
-
- await service.resolve({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- event: EVENT,
- attempt: 3,
- recordReadAttempt: 1,
- });
-
- expect(pendingWakeUpService.claim).not.toHaveBeenCalled();
- expect(handler.resolve).not.toHaveBeenCalled();
- expect(pendingWakeUpService.scheduleResolution).toHaveBeenCalledWith({
- wakeUp: STORED_WAKE_UP,
- event: EVENT,
- attempt: undefined,
- recordReadAttempt: 2,
- delayMs: 4_000,
- });
- });
-
- it('leaves the wake-up pending when its owner ignores the event', async () => {
- const { service, pendingWakeUpService, handler } = buildService({
- decision: { type: 'IGNORE' },
- });
-
- await service.resolve({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- event: EVENT,
- });
-
- expect(pendingWakeUpService.claim).not.toHaveBeenCalled();
- expect(pendingWakeUpService.scheduleResolution).not.toHaveBeenCalled();
- expect(handler.resolve).not.toHaveBeenCalled();
- });
-
- it('does not resolve a wake-up another resolution claimed first', async () => {
- const { service, handler } = buildService({ claimedWakeUp: null });
-
- await service.resolve({
- workspaceId: WORKSPACE_ID,
- wakeUpId: WAKE_UP_ID,
- event: EVENT,
- });
-
- expect(handler.resolve).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up.service.spec.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up.service.spec.ts
deleted file mode 100644
index 248e0232d05..00000000000
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/__tests__/pending-wake-up.service.spec.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { RESUME_PENDING_WAKE_UP_JOB_NAME } from 'src/engine/core-modules/pending-wake-up/constants/resume-pending-wake-up-job-name.constant';
-import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
-import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
-
-const WORKSPACE_ID = 'workspace-id';
-const OWNER = { type: 'WORKFLOW_STEP' as const, id: 'run-id', key: 'step-id' };
-const OWNER_JOB_OPTIONS = { id: 'run-id', allowDuplicatedPrefixes: true };
-
-const buildService = () => {
- const pendingWakeUpRepository = {
- upsert: jest.fn(),
- delete: jest.fn(),
- };
- const messageQueueService = { add: jest.fn() };
- const registry = new PendingWakeUpOwnerHandlerRegistryService();
-
- registry.register({
- ownerType: 'WORKFLOW_STEP',
- buildResumeJobOptions: jest.fn().mockReturnValue(OWNER_JOB_OPTIONS),
- beforeClaim: jest.fn(),
- resolve: jest.fn(),
- });
-
- const service = new PendingWakeUpService(
- pendingWakeUpRepository as never,
- messageQueueService as never,
- registry,
- );
-
- return { service, pendingWakeUpRepository, messageQueueService };
-};
-
-describe('PendingWakeUpService', () => {
- it('stores an event wake-up without scheduling it when it never expires', async () => {
- const { service, pendingWakeUpRepository, messageQueueService } =
- buildService();
-
- await service.arm({
- workspaceId: WORKSPACE_ID,
- owner: OWNER,
- condition: { type: 'EVENT', eventName: 'company.updated' },
- });
-
- expect(pendingWakeUpRepository.upsert).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({
- ownerType: 'WORKFLOW_STEP',
- ownerId: 'run-id',
- ownerKey: 'step-id',
- eventName: 'company.updated',
- resumeAt: null,
- }),
- ['ownerType', 'ownerId', 'ownerKey'],
- );
- expect(messageQueueService.add).not.toHaveBeenCalled();
- });
-
- it('schedules a time wake-up with the job options of its owner', async () => {
- const { service, pendingWakeUpRepository, messageQueueService } =
- buildService();
- const resumeAt = new Date(Date.now() + 60_000).toISOString();
-
- await service.arm({
- workspaceId: WORKSPACE_ID,
- owner: OWNER,
- condition: { type: 'TIME', resumeAt },
- });
-
- const [, storedWakeUp] = pendingWakeUpRepository.upsert.mock.calls[0];
-
- expect(storedWakeUp).toMatchObject({
- eventName: null,
- resumeAt: new Date(resumeAt),
- });
- expect(messageQueueService.add).toHaveBeenCalledWith(
- RESUME_PENDING_WAKE_UP_JOB_NAME,
- expect.objectContaining({
- workspaceId: WORKSPACE_ID,
- wakeUpId: storedWakeUp.id,
- }),
- expect.objectContaining({
- ...OWNER_JOB_OPTIONS,
- delay: expect.any(Number),
- }),
- );
- });
-
- it('cancels one wake-up of an owner by its key', async () => {
- const { service, pendingWakeUpRepository } = buildService();
-
- await service.cancel({ workspaceId: WORKSPACE_ID, owner: OWNER });
-
- expect(pendingWakeUpRepository.delete).toHaveBeenCalledWith(WORKSPACE_ID, {
- ownerType: 'WORKFLOW_STEP',
- ownerId: 'run-id',
- ownerKey: 'step-id',
- });
- });
-
- it('cancels every wake-up of an owner', async () => {
- const { service, pendingWakeUpRepository } = buildService();
-
- await service.cancelAllForOwner({
- workspaceId: WORKSPACE_ID,
- ownerType: 'WORKFLOW_STEP',
- ownerId: 'run-id',
- });
-
- expect(pendingWakeUpRepository.delete).toHaveBeenCalledWith(WORKSPACE_ID, {
- ownerType: 'WORKFLOW_STEP',
- ownerId: 'run-id',
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
index b0a4e1d3f9f..f37ed47926e 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
@@ -14,11 +14,15 @@ import { AgentMessageResolver } from 'src/engine/metadata-modules/ai/ai-agent-ex
import { AgentRunResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.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 { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
+import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
+import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
import { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-billing.module';
import { AiModelsModule } from 'src/engine/metadata-modules/ai/ai-models/ai-models.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
@@ -30,6 +34,8 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
@Module({
imports: [
+ AgentChatThreadLifecycleModule,
+ AgentChatThreadModule,
AgentHistoryModule,
AiBillingModule,
AiModelsModule,
@@ -52,12 +58,14 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
providers: [
AgentAsyncExecutorService,
AgentActorContextService,
+ AgentCallerConversationService,
+ AgentRunConversationService,
AiGraphqlApiExceptionInterceptor,
AgentMessagePartResolver,
AgentMessageResolver,
AgentRunResolver,
- AgentRunConversationService,
AgentRunService,
+ AgentRunnerService,
RunAgentAttachmentService,
provideWorkspaceScopedRepository(RoleTargetEntity),
provideWorkspaceScopedRepository(AgentEntity),
@@ -66,7 +74,9 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
exports: [
AgentAsyncExecutorService,
AgentActorContextService,
+ AgentCallerConversationService,
AgentRunConversationService,
+ AgentRunnerService,
],
})
export class AiAgentExecutionModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
new file mode 100644
index 00000000000..defce7e2ac7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
@@ -0,0 +1,441 @@
+import { IsNull } from 'typeorm';
+
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+const SENDER = {
+ type: 'workflow' as const,
+ workflowId: 'workflow-id',
+ workflowName: 'New deals',
+};
+
+const OPEN_ARGS = {
+ workspaceId: 'workspace-id',
+ sender: SENDER,
+ title: 'Draft the quote',
+ threadKey: 'run-id:step-id',
+ fallbackThreadKey: 'run-id:step-id:run-id:step-id',
+};
+
+const CALLER = {
+ type: 'WORKFLOW_STEP' as const,
+ ref: { workflowRunId: 'run-id', stepId: 'step-id' },
+};
+
+const QUESTION = {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+};
+
+const buildService = ({ isCreated = true } = {}) => {
+ const threadRepository = {
+ find: jest
+ .fn()
+ .mockResolvedValue([
+ { id: 'thread-id', pendingQuestionMessageId: 'message-id' },
+ ]),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ };
+ const messageRepository = { find: jest.fn().mockResolvedValue([]) };
+ const messagePartRepository = {
+ find: jest.fn().mockResolvedValue([
+ {
+ id: 'part-id',
+ messageId: 'message-id',
+ toolName: 'ask_question',
+ toolInput: QUESTION,
+ toolOutput: {
+ result: { question: QUESTION, status: 'pending' },
+ workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
+ },
+ },
+ ]),
+ update: jest.fn(),
+ writePart: jest.fn(),
+ query: jest.fn(),
+ };
+
+ messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>
+ run({
+ table: (name: string) => name,
+ manager: { query: messagePartRepository.writePart },
+ }),
+ );
+
+ const agentInboxService = {
+ openThread: jest.fn().mockImplementation(({ workspaceMemberId }) =>
+ Promise.resolve({
+ thread: { id: `thread-for-${workspaceMemberId ?? 'nobody'}` },
+ isCreated,
+ }),
+ ),
+ };
+ const threadRecordEventService = {
+ emitPendingQuestionCleared: jest.fn().mockResolvedValue(undefined),
+ };
+ const turnRecorderService = {
+ endWaitingTurn: jest.fn().mockResolvedValue(undefined),
+ };
+
+ const service = new AgentCallerConversationService(
+ threadRepository as never,
+ messageRepository as never,
+ messagePartRepository as never,
+ agentInboxService as never,
+ threadRecordEventService as never,
+ turnRecorderService as never,
+ );
+
+ return {
+ service,
+ threadRepository,
+ messageRepository,
+ messagePartRepository,
+ agentInboxService,
+ threadRecordEventService,
+ turnRecorderService,
+ };
+};
+
+describe('AgentCallerConversationService', () => {
+ describe('openConversation', () => {
+ it('opens the conversation with the recipient, filed under done', async () => {
+ const { service, agentInboxService } = buildService();
+
+ const conversation = await service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ fallbackRecipientWorkspaceMemberId: 'creator-id',
+ });
+
+ expect(conversation).toEqual({
+ status: 'OPENED',
+ threadId: 'thread-for-recipient-id',
+ isCreated: true,
+ });
+ expect(agentInboxService.openThread).toHaveBeenCalledTimes(1);
+ expect(agentInboxService.openThread).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ sender: SENDER,
+ workspaceMemberId: 'recipient-id',
+ threadKey: 'run-id:step-id',
+ title: 'Draft the quote',
+ isArchivedOnCreate: true,
+ });
+ });
+
+ it('falls back to the fallback recipient without a recipient', async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ fallbackRecipientWorkspaceMemberId: 'creator-id',
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-creator-id' });
+ });
+
+ it('keeps a conversation no inbox receives when the fallback recipient cannot have it', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockRejectedValueOnce(
+ new AiException(
+ 'Thread owner is no longer a workspace member',
+ AiExceptionCode.THREAD_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ fallbackRecipientWorkspaceMemberId: 'creator-id',
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
+ });
+
+ it('keeps a conversation no inbox receives without any recipient', async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
+ });
+
+ it('fails when the recipient cannot have the conversation', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockRejectedValueOnce(
+ new AiException(
+ 'Thread owner is no longer a workspace member',
+ AiExceptionCode.THREAD_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_NOT_FOUND });
+ });
+
+ it('starts its own conversation when the recipient deleted the one its key names', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValueOnce({
+ thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({
+ status: 'OPENED',
+ threadId: 'thread-for-recipient-id',
+ isCreated: true,
+ });
+ expect(agentInboxService.openThread).toHaveBeenLastCalledWith(
+ expect.objectContaining({ threadKey: 'run-id:step-id:run-id:step-id' }),
+ );
+ });
+
+ it('starts its own conversation while the one its key names waits on another answer', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValueOnce({
+ thread: {
+ id: 'waiting-thread-id',
+ pendingQuestionMessageId: 'question-message-id',
+ },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-recipient-id' });
+ });
+
+ it('reports a conversation the recipient also deleted under the fallback key', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValue({
+ thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({ status: 'DELETED' });
+ });
+ });
+
+ describe('recordWaitOutcome', () => {
+ const waitPart = (id: string, workflowStep: Record<string, string>) => ({
+ id,
+ toolName: 'wait_for_duration',
+ toolOutput: { result: { status: 'pending' }, workflowStep },
+ });
+
+ const recordWaitOutcome = (service: AgentCallerConversationService) =>
+ service.recordWaitOutcome({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ caller: CALLER,
+ toolNames: ['wait_for_duration'],
+ toolOutput: { success: true },
+ });
+
+ it("settles the caller's own wait, not another caller's waiting in the same conversation", async () => {
+ const { service, messageRepository, messagePartRepository } =
+ buildService();
+
+ messageRepository.find.mockResolvedValue([
+ {
+ parts: [
+ waitPart('other-run-part', {
+ workflowRunId: 'other-run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ {
+ parts: [
+ waitPart('other-step-part', {
+ workflowRunId: 'run-id',
+ stepId: 'other-step-id',
+ }),
+ ],
+ },
+ {
+ parts: [
+ waitPart('own-part', {
+ workflowRunId: 'run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ ]);
+
+ await recordWaitOutcome(service);
+
+ expect(messagePartRepository.update).toHaveBeenCalledWith(
+ 'workspace-id',
+ { id: 'own-part' },
+ { toolOutput: { success: true } },
+ );
+ });
+
+ it('refuses to settle a wait the caller never posted', async () => {
+ const { service, messageRepository } = buildService();
+
+ messageRepository.find.mockResolvedValue([
+ {
+ parts: [
+ waitPart('other-run-part', {
+ workflowRunId: 'other-run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ ]);
+
+ await expect(recordWaitOutcome(service)).rejects.toMatchObject({
+ code: AiExceptionCode.TOOL_CALL_NOT_FOUND,
+ });
+ });
+ });
+
+ describe('cancelAwaitingConversations', () => {
+ const cancel = (service: AgentCallerConversationService) =>
+ service.cancelAwaitingConversations({
+ workspaceId: 'workspace-id',
+ threadIds: ['thread-id'],
+ caller: { type: 'WORKFLOW_STEP', ref: { workflowRunId: 'run-id' } },
+ });
+
+ it('stops its conversations waiting and closes their calls as skipped', async () => {
+ const {
+ service,
+ threadRepository,
+ messagePartRepository,
+ turnRecorderService,
+ } = buildService();
+
+ await cancel(service);
+
+ expect(threadRepository.update).toHaveBeenCalledWith(
+ 'workspace-id',
+ {
+ id: 'thread-id',
+ pendingQuestionMessageId: 'message-id',
+ activeStreamId: IsNull(),
+ },
+ { pendingQuestionMessageId: null },
+ );
+ expect(turnRecorderService.endWaitingTurn).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ messageId: 'message-id',
+ status: AgentTurnStatus.CANCELLED,
+ });
+ const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] =
+ messagePartRepository.writePart.mock.calls;
+
+ expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);
+ expect({
+ partId,
+ result: JSON.parse(closedToolOutput).result,
+ expectedStatus,
+ }).toEqual({
+ partId: 'part-id',
+ result: { question: QUESTION, status: 'skipped' },
+ expectedStatus: 'pending',
+ });
+ });
+
+ it('tells open chat lists the conversation no longer waits on an answer', async () => {
+ const { service, threadRecordEventService } = buildService();
+
+ await cancel(service);
+
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ messageId: 'message-id',
+ });
+ });
+
+ it('leaves open a call another caller posted in a conversation they share', async () => {
+ const { service, threadRepository, messagePartRepository } =
+ buildService();
+
+ messagePartRepository.find.mockResolvedValue([
+ {
+ id: 'part-id',
+ messageId: 'message-id',
+ toolName: 'ask_question',
+ toolInput: QUESTION,
+ toolOutput: {
+ result: { question: QUESTION, status: 'pending' },
+ workflowStep: { workflowRunId: 'other-run-id', stepId: 'step-id' },
+ },
+ },
+ ]);
+
+ await cancel(service);
+
+ expect(threadRepository.update).not.toHaveBeenCalled();
+ expect(messagePartRepository.writePart).not.toHaveBeenCalled();
+ });
+
+ it('leaves a conversation to the answer holding its claim', async () => {
+ const {
+ service,
+ threadRepository,
+ messagePartRepository,
+ threadRecordEventService,
+ } = buildService();
+
+ threadRepository.update.mockResolvedValue({ affected: 0 });
+
+ await cancel(service);
+
+ expect(messagePartRepository.writePart).not.toHaveBeenCalled();
+ expect(
+ threadRecordEventService.emitPendingQuestionCleared,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('reads nothing without conversations', async () => {
+ const { service, threadRepository } = buildService();
+
+ await service.cancelAwaitingConversations({
+ workspaceId: 'workspace-id',
+ threadIds: [],
+ caller: { type: 'WORKFLOW_STEP', ref: { workflowRunId: 'run-id' } },
+ });
+
+ expect(threadRepository.find).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.close-turn.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.close-turn.spec.ts
deleted file mode 100644
index d3ca6f3445a..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-conversation.service.close-turn.spec.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
-
-const execution = {
- modelId: 'model-id',
- hasNoMoreAvailableCredits: false,
-} as AgentExecutionResult;
-
-const turn = {
- workspaceId: 'workspace-id',
- threadId: 'thread-id',
- turnId: 'turn-id',
-};
-
-const buildService = () => {
- const conversationWriterService = {
- insertExecutionReply: jest
- .fn()
- .mockResolvedValue({ isAwaitingAnswer: false, replyParts: [] }),
- };
- const turnRecorderService = {
- finishExecutedTurn: jest.fn().mockResolvedValue(undefined),
- };
-
- const service = new AgentRunConversationService(
- {} as never,
- conversationWriterService as never,
- {} as never,
- turnRecorderService as never,
- );
-
- return { service, conversationWriterService, turnRecorderService };
-};
-
-describe('AgentRunConversationService.closeTurn', () => {
- it('leaves the turn waiting when the agent asked a question', async () => {
- const { service, conversationWriterService, turnRecorderService } =
- buildService();
-
- conversationWriterService.insertExecutionReply.mockResolvedValue({
- isAwaitingAnswer: true,
- replyParts: [],
- });
-
- await service.closeTurn({ ...turn, agentId: 'agent-id', execution });
-
- expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledWith({
- ...turn,
- execution,
- isAwaitingAnswer: true,
- });
- });
-
- it('fails the turn when its reply cannot be saved', async () => {
- const { service, conversationWriterService, turnRecorderService } =
- buildService();
-
- conversationWriterService.insertExecutionReply.mockRejectedValue(
- new Error('question slot taken'),
- );
-
- await expect(
- service.closeTurn({ ...turn, agentId: 'agent-id', execution }),
- ).rejects.toThrow('question slot taken');
-
- expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledTimes(1);
- expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledWith({
- ...turn,
- execution,
- error: expect.objectContaining({ code: expect.any(String) }),
- });
- });
-});
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.ts
index cca58a3502f..0cf34f91d84 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
@@ -1,8 +1,20 @@
import { FieldActorSource } from 'twenty-shared/types';
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
+const execution = {
+ modelId: 'model-id',
+ hasNoMoreAvailableCredits: false,
+} as AgentExecutionResult;
+
+const turn = {
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ turnId: 'turn-id',
+};
+
const buildService = () => {
const scope = { insert: jest.fn().mockResolvedValue(undefined) };
const conversationWriterService = {
@@ -11,6 +23,15 @@ const buildService = () => {
.mockImplementation(async (_workspaceId, work) => work(scope)),
insertTurn: jest.fn().mockResolvedValue('turn-id'),
insertMessage: jest.fn().mockResolvedValue(undefined),
+ insertExecutionReply: jest
+ .fn()
+ .mockResolvedValue({ isAwaitingAnswer: false, replyParts: [] }),
+ };
+ const turnRecorderService = {
+ finishExecutedTurn: jest.fn().mockResolvedValue(undefined),
+ };
+ const threadService = {
+ recordThreadActivity: jest.fn().mockResolvedValue(undefined),
};
return {
@@ -18,13 +39,24 @@ const buildService = () => {
{ findOne: jest.fn().mockResolvedValue(null) } as never,
conversationWriterService as never,
{} as never,
- {} as never,
+ turnRecorderService as never,
+ threadService as never,
),
conversationWriterService,
+ turnRecorderService,
+ threadService,
};
};
-describe('AgentRunConversationService openTurn', () => {
+const closeTurn = (service: AgentRunConversationService) =>
+ service.closeTurn({
+ ...turn,
+ title: 'Draft the quote',
+ agentId: 'agent-id',
+ execution,
+ });
+
+describe('AgentRunConversationService', () => {
it('stores handed-over replies as assistant messages with no sender', async () => {
const { service, conversationWriterService } = buildService();
@@ -77,4 +109,88 @@ describe('AgentRunConversationService openTurn', () => {
},
]);
});
+
+ it('leaves the turn waiting and brings the conversation back to the inbox when the agent asked a question', async () => {
+ const {
+ service,
+ conversationWriterService,
+ turnRecorderService,
+ threadService,
+ } = buildService();
+
+ conversationWriterService.insertExecutionReply.mockResolvedValue({
+ isAwaitingAnswer: true,
+ replyParts: [{ type: 'text', text: 'Which plan?' }],
+ });
+
+ await expect(closeTurn(service)).resolves.toEqual({
+ isAwaitingAnswer: true,
+ });
+ expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledWith({
+ ...turn,
+ execution,
+ isAwaitingAnswer: true,
+ });
+ expect(threadService.recordThreadActivity).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ text: 'Which plan?',
+ });
+ });
+
+ it('keeps the answer awaited when the inbox cannot be told', async () => {
+ const { service, conversationWriterService, threadService } =
+ buildService();
+
+ conversationWriterService.insertExecutionReply.mockResolvedValue({
+ isAwaitingAnswer: true,
+ replyParts: [],
+ });
+ threadService.recordThreadActivity.mockRejectedValue(new Error('boom'));
+
+ await expect(closeTurn(service)).resolves.toEqual({
+ isAwaitingAnswer: true,
+ });
+ });
+
+ it('fails the turn when its reply cannot be saved', async () => {
+ const { service, conversationWriterService, turnRecorderService } =
+ buildService();
+
+ conversationWriterService.insertExecutionReply.mockRejectedValue(
+ new Error('question slot taken'),
+ );
+
+ await expect(closeTurn(service)).rejects.toThrow('question slot taken');
+
+ expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledTimes(1);
+ expect(turnRecorderService.finishExecutedTurn).toHaveBeenCalledWith({
+ ...turn,
+ execution,
+ error: expect.objectContaining({ code: expect.any(String) }),
+ });
+ });
+
+ it('names the caller on the calls it leaves pending', async () => {
+ const { service, conversationWriterService, threadService } =
+ buildService();
+
+ await service.closeTurn({
+ ...turn,
+ title: 'Draft the quote',
+ agentId: null,
+ execution,
+ caller: {
+ type: 'WORKFLOW_STEP',
+ ref: { workflowRunId: 'run-id', stepId: 'step-id' },
+ },
+ });
+
+ expect(conversationWriterService.insertExecutionReply).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
+ }),
+ );
+ 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.ts
index f219d7697c6..b780f0b02dd 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
@@ -19,25 +19,15 @@ const RUN_AS_ACTOR = {
workspaceMemberId: 'workspace-member-id',
context: {},
};
-const PRIOR_MESSAGES = [{ id: 'message-1', role: 'user', parts: [] }];
-
const buildService = () => {
- const executionResult = {
- result: { response: 'Acme is your biggest customer' },
- hasNoMoreAvailableCredits: false,
- steps: [],
- };
- const agentAsyncExecutorService = {
- executeAgent: jest.fn().mockResolvedValue(executionResult),
- };
- const agentRunConversationService = {
- openTurn: jest.fn().mockResolvedValue('turn-id'),
- closeTurn: jest.fn().mockResolvedValue(undefined),
- failTurn: jest.fn().mockResolvedValue(undefined),
- withThreadLock: jest.fn(({ work }) => work()),
- };
- const conversationReaderService = {
- loadMessages: jest.fn().mockResolvedValue(PRIOR_MESSAGES),
+ const agentRunnerService = {
+ run: jest.fn().mockImplementation(async ({ conversation }) => ({
+ threadId: conversation.threadId,
+ outcome: {
+ status: 'COMPLETED',
+ result: { response: 'Acme is your biggest customer' },
+ },
+ })),
};
const agentActorContextService = {
buildRunAsWorkspaceMemberContext: jest.fn().mockResolvedValue({
@@ -49,22 +39,17 @@ const buildService = () => {
const service = new AgentRunService(
agentActorContextService as never,
- agentAsyncExecutorService as never,
- agentRunConversationService as never,
+ agentRunnerService as never,
{ findById: jest.fn().mockResolvedValue(APPLICATION) } as never,
- conversationReaderService as never,
{ findOne: jest.fn().mockResolvedValue(AGENT) } as never,
);
- return {
- service,
- executionResult,
- agentAsyncExecutorService,
- agentRunConversationService,
- conversationReaderService,
- };
+ return { service, agentRunnerService };
};
+const runInput = (agentRunnerService: { run: jest.Mock }) =>
+ agentRunnerService.run.mock.calls[0][0];
+
const run = (
service: AgentRunService,
input: Record<string, unknown>,
@@ -89,13 +74,8 @@ const run = (
const userInput = (content: string) => [{ role: 'user', content }];
describe('AgentRunService', () => {
- it('records a run without a thread in a conversation of its own', async () => {
- const {
- service,
- agentAsyncExecutorService,
- agentRunConversationService,
- conversationReaderService,
- } = buildService();
+ it('runs without a thread in a new conversation of its own', async () => {
+ const { service, agentRunnerService } = buildService();
const result = await run(service, {
input: userInput('Who is our biggest customer?'),
@@ -111,34 +91,27 @@ describe('AgentRunService', () => {
threadId: expect.any(String),
});
expect(secondResult.threadId).not.toBe(result.threadId);
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: secondResult.threadId }),
- );
- expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: secondResult.threadId }),
- );
- expect(conversationReaderService.loadMessages).not.toHaveBeenCalled();
- expect(agentRunConversationService.withThreadLock).not.toHaveBeenCalled();
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId: result.threadId,
- title: AGENT.label,
- senderUserWorkspaceId: null,
- senderApplicationId: APPLICATION.id,
- createdBy: expect.objectContaining({ source: 'APPLICATION' }),
- messages: userInput('Who is our biggest customer?'),
- }),
- );
- expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: result.threadId, turnId: 'turn-id' }),
- );
- expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(
- expect.objectContaining({ priorMessages: [] }),
- );
+
+ const { conversation, turn, execution } = runInput(agentRunnerService);
+
+ expect(conversation).toEqual({
+ threadId: result.threadId,
+ isCreated: true,
+ });
+ expect(turn).toMatchObject({
+ title: AGENT.label,
+ senderUserWorkspaceId: null,
+ senderApplicationId: APPLICATION.id,
+ messages: userInput('Who is our biggest customer?'),
+ });
+ await expect(turn.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 () => {
- const { service, agentRunConversationService } = buildService();
+ const { service, agentRunnerService } = buildService();
const history = [
{ role: 'user', content: 'Who is our biggest customer?' },
{ role: 'assistant', content: 'Acme.' },
@@ -147,31 +120,21 @@ describe('AgentRunService', () => {
await run(service, { input: history });
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({ messages: history }),
- );
+ expect(runInput(agentRunnerService).turn.messages).toEqual(history);
});
it('keeps accepting a prompt', async () => {
- const { service, agentAsyncExecutorService } = buildService();
+ const { service, agentRunnerService } = buildService();
await run(service, { prompt: 'Who is our biggest customer?' });
- expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- messages: userInput('Who is our biggest customer?'),
- }),
+ expect(runInput(agentRunnerService).execution.messages).toEqual(
+ userInput('Who is our biggest customer?'),
);
});
it('continues the thread as the member it runs as', async () => {
- const {
- service,
- executionResult,
- agentAsyncExecutorService,
- agentRunConversationService,
- conversationReaderService,
- } = buildService();
+ const { service, agentRunnerService } = buildService();
const threadId = buildAgentRunThreadId({
applicationId: APPLICATION.id,
agentId: AGENT.id,
@@ -184,41 +147,29 @@ describe('AgentRunService', () => {
runAsWorkspaceMemberId: 'workspace-member-id',
});
- const actor = { type: 'user', userWorkspaceId: RUN_AS_USER_WORKSPACE_ID };
+ const { conversation, conversationActor, turn, execution } =
+ runInput(agentRunnerService);
expect(result.threadId).toBe(threadId);
- expect(agentRunConversationService.withThreadLock).toHaveBeenCalledWith(
- expect.objectContaining({ workspaceId: 'workspace-id', threadId }),
- );
- expect(conversationReaderService.loadMessages).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- threadId,
- actor,
+ expect(conversation).toEqual({ threadId, isCreated: false });
+ expect(conversationActor).toEqual({
+ type: 'user',
+ userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ });
+ expect(turn).toMatchObject({
+ title: AGENT.label,
+ senderUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ });
+ await expect(turn.resolveCreatedBy()).resolves.toEqual(RUN_AS_ACTOR);
+ expect(execution).toMatchObject({
+ actorContext: RUN_AS_ACTOR,
+ userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ runAsRoleId: 'role-id',
});
- expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(
- expect.objectContaining({ priorMessages: PRIOR_MESSAGES }),
- );
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId,
- title: AGENT.label,
- senderUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
- createdBy: RUN_AS_ACTOR,
- messages: userInput('And the second one?'),
- }),
- );
- expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId,
- turnId: 'turn-id',
- execution: executionResult,
- }),
- );
});
it('gives the additional instructions to the model without recording them', async () => {
- const { service, agentAsyncExecutorService, agentRunConversationService } =
- buildService();
+ const { service, agentRunnerService } = buildService();
await run(service, {
input: userInput('And the second one?'),
@@ -226,22 +177,20 @@ describe('AgentRunService', () => {
additionalInstructions: 'Answer in Slack markdown',
});
- expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- messages: userInput('Answer in Slack markdown\n\nAnd the second one?'),
- }),
- );
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- title: 'Acme renewal',
- messages: userInput('And the second one?'),
- senderUserWorkspaceId: null,
- }),
+ const { turn, execution } = runInput(agentRunnerService);
+
+ expect(execution.messages).toEqual(
+ userInput('Answer in Slack markdown\n\nAnd the second one?'),
);
+ expect(turn).toMatchObject({
+ title: 'Acme renewal',
+ messages: userInput('And the second one?'),
+ senderUserWorkspaceId: null,
+ });
});
it('records the member who called without an application as the sender', async () => {
- const { service, agentRunConversationService } = buildService();
+ const { service, agentRunnerService } = buildService();
await run(
service,
@@ -252,49 +201,40 @@ describe('AgentRunService', () => {
},
);
- expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- senderUserWorkspaceId: 'caller-user-workspace-id',
- senderApplicationId: null,
- }),
- );
+ expect(runInput(agentRunnerService).turn).toMatchObject({
+ senderUserWorkspaceId: 'caller-user-workspace-id',
+ senderApplicationId: null,
+ });
});
- it('still returns the reply when the turn cannot be recorded', async () => {
- const { service, agentRunConversationService } = buildService();
+ it('reports a run that ran out of credits', async () => {
+ const { service, agentRunnerService } = buildService();
- jest.spyOn(Logger.prototype, 'error').mockImplementation();
- agentRunConversationService.openTurn.mockRejectedValue(
- new Error('write failed'),
- );
-
- const result = await run(service, {
- input: userInput('And the second one?'),
- thread: { key: 'thread' },
+ agentRunnerService.run.mockResolvedValue({
+ threadId: 'thread-id',
+ outcome: { status: 'NO_CREDITS' },
});
- expect(result.success).toBe(true);
- expect(agentRunConversationService.closeTurn).not.toHaveBeenCalled();
+ await expect(
+ run(service, { input: userInput('Hello') }),
+ ).resolves.toMatchObject({
+ success: false,
+ error: 'Agent stopped: no more available credits.',
+ });
});
- it('records the turn as failed when the execution throws', async () => {
- const { service, agentAsyncExecutorService, agentRunConversationService } =
- buildService();
- const executionError = new Error('provider down');
+ it('reports a failed run without throwing', async () => {
+ const { service, agentRunnerService } = buildService();
jest.spyOn(Logger.prototype, 'error').mockImplementation();
- agentAsyncExecutorService.executeAgent.mockRejectedValue(executionError);
+ agentRunnerService.run.mockRejectedValue(new Error('provider down'));
- const result = await run(service, {
- input: userInput('And the second one?'),
- thread: { key: 'thread' },
+ await expect(
+ run(service, { input: userInput('Hello') }),
+ ).resolves.toMatchObject({
+ success: false,
+ error: 'Agent execution failed.',
});
-
- expect(result.success).toBe(false);
- expect(agentRunConversationService.failTurn).toHaveBeenCalledWith(
- expect.objectContaining({ turnId: 'turn-id', error: executionError }),
- );
- expect(agentRunConversationService.closeTurn).not.toHaveBeenCalled();
});
it('refuses a thread without an application token', async () => {
@@ -310,12 +250,12 @@ describe('AgentRunService', () => {
});
it('refuses a thread with a blank key', async () => {
- const { service, agentAsyncExecutorService } = buildService();
+ const { service, agentRunnerService } = buildService();
await expect(
run(service, { input: userInput('Hello'), thread: { key: ' ' } }),
).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });
- expect(agentAsyncExecutorService.executeAgent).not.toHaveBeenCalled();
+ expect(agentRunnerService.run).not.toHaveBeenCalled();
});
it('refuses assistant messages sent to a thread', async () => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
new file mode 100644
index 00000000000..e40789a3282
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
@@ -0,0 +1,294 @@
+import { Logger } from '@nestjs/common';
+
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
+
+const CALLER = {
+ type: 'WORKFLOW_STEP' as const,
+ ref: { workflowRunId: 'run-id', stepId: 'step-id' },
+};
+
+const CREATED_BY = {
+ source: 'WORKFLOW',
+ name: 'New deals',
+ workspaceMemberId: null,
+ context: {},
+} as Awaited<ReturnType<AgentRunnerRunInput['turn']['resolveCreatedBy']>>;
+
+const PRIOR_MESSAGES = [{ id: 'message-id', role: 'assistant', parts: [] }];
+
+const MESSAGES = [{ role: 'user' as const, content: 'Draft a quote' }];
+
+const buildExecution = (
+ overrides: Partial<AgentExecutionResult> = {},
+): AgentExecutionResult => ({
+ result: { answer: 'done' },
+ usage: {
+ inputTokens: 1,
+ outputTokens: 2,
+ totalTokens: 3,
+ } as AgentExecutionResult['usage'],
+ cacheCreationTokens: 0,
+ nativeWebSearchCallCount: 0,
+ hasNoMoreAvailableCredits: false,
+ isPaused: false,
+ steps: [],
+ modelId: 'model-id',
+ totalCostInDollars: 0,
+ creditsUsedMicro: 0,
+ turnUsage: {
+ inputTokens: 1,
+ outputTokens: 2,
+ cacheReadTokens: 0,
+ cacheCreationTokens: 0,
+ inputCredits: 0,
+ outputCredits: 0,
+ },
+ ...overrides,
+});
+
+const RUN_INPUT: AgentRunnerRunInput = {
+ workspaceId: 'workspace-id',
+ conversation: { threadId: 'thread-id', isCreated: false },
+ caller: CALLER,
+ turn: {
+ title: 'Draft the quote',
+ senderUserWorkspaceId: 'user-workspace-id',
+ senderApplicationId: null,
+ messages: MESSAGES,
+ resolveCreatedBy: async () => CREATED_BY,
+ },
+ execution: {
+ agent: null,
+ messages: MESSAGES,
+ baseSystemPrompt: 'base prompt',
+ workspaceId: 'workspace-id',
+ },
+};
+
+const buildService = (execution = buildExecution()) => {
+ const agentAsyncExecutorService = {
+ executeAgent: jest.fn().mockResolvedValue(execution),
+ };
+ const agentRunConversationService = {
+ openTurn: jest.fn().mockResolvedValue('turn-id'),
+ closeTurn: jest.fn().mockResolvedValue({ isAwaitingAnswer: false }),
+ failTurn: jest.fn().mockResolvedValue(undefined),
+ withThreadLock: jest.fn(({ work }) => work()),
+ };
+ const conversationReaderService = {
+ loadMessages: jest.fn().mockResolvedValue(PRIOR_MESSAGES),
+ };
+
+ jest.spyOn(Logger.prototype, 'error').mockImplementation();
+
+ const service = new AgentRunnerService(
+ agentAsyncExecutorService as never,
+ agentRunConversationService as never,
+ conversationReaderService as never,
+ );
+
+ return {
+ service,
+ agentAsyncExecutorService,
+ agentRunConversationService,
+ conversationReaderService,
+ };
+};
+
+const pausedOnWait = buildExecution({
+ isPaused: true,
+ steps: [
+ { content: [], toolResults: [{ toolName: 'search', output: {} }] },
+ {
+ content: [],
+ toolResults: [
+ {
+ toolName: 'wait_for_event',
+ output: { result: { status: 'pending' } },
+ },
+ ],
+ },
+ ] as unknown as AgentExecutionResult['steps'],
+});
+
+describe('AgentRunnerService', () => {
+ it('continues a conversation under its lock and records the turn', async () => {
+ const {
+ service,
+ agentAsyncExecutorService,
+ agentRunConversationService,
+ conversationReaderService,
+ } = buildService();
+
+ const { threadId, outcome, summary } = await service.run({
+ ...RUN_INPUT,
+ conversationActor: { type: 'application', applicationId: 'app-id' },
+ });
+
+ expect(threadId).toBe('thread-id');
+ expect(outcome).toEqual({
+ status: 'COMPLETED',
+ result: { answer: 'done' },
+ });
+ expect(summary).toMatchObject({ modelId: 'model-id', toolCalls: [] });
+ expect(agentRunConversationService.withThreadLock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ }),
+ );
+ expect(conversationReaderService.loadMessages).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ actor: { type: 'application', applicationId: 'app-id' },
+ });
+ expect(agentRunConversationService.openTurn).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ title: 'Draft the quote',
+ agentId: null,
+ senderUserWorkspaceId: 'user-workspace-id',
+ senderApplicationId: null,
+ createdBy: CREATED_BY,
+ messages: MESSAGES,
+ });
+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith({
+ ...RUN_INPUT.execution,
+ priorMessages: PRIOR_MESSAGES,
+ });
+ expect(agentRunConversationService.closeTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ turnId: 'turn-id',
+ title: 'Draft the quote',
+ caller: CALLER,
+ }),
+ );
+ });
+
+ it('neither reads nor locks a conversation it just created', async () => {
+ const {
+ service,
+ agentRunConversationService,
+ conversationReaderService,
+ agentAsyncExecutorService,
+ } = buildService();
+
+ await service.run({
+ ...RUN_INPUT,
+ conversation: { threadId: 'thread-id', isCreated: true },
+ });
+
+ expect(agentRunConversationService.withThreadLock).not.toHaveBeenCalled();
+ expect(conversationReaderService.loadMessages).not.toHaveBeenCalled();
+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ priorMessages: [] }),
+ );
+ });
+
+ it.each([
+ [
+ 'the turn author cannot be resolved',
+ { resolveCreatedBy: jest.fn().mockRejectedValue(new Error('gone')) },
+ {},
+ ],
+ [
+ 'the turn cannot be opened',
+ {},
+ { openTurn: jest.fn().mockRejectedValue(new Error('db down')) },
+ ],
+ ])(
+ 'still runs the agent when %s',
+ async (_, turnOverrides, conversationOverrides) => {
+ const {
+ service,
+ agentAsyncExecutorService,
+ agentRunConversationService,
+ } = buildService();
+
+ Object.assign(agentRunConversationService, conversationOverrides);
+
+ const { outcome } = await service.run({
+ ...RUN_INPUT,
+ turn: { ...RUN_INPUT.turn, ...turnOverrides },
+ });
+
+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalled();
+ expect(agentRunConversationService.closeTurn).not.toHaveBeenCalled();
+ expect(outcome).toEqual({
+ status: 'COMPLETED',
+ result: { answer: 'done' },
+ });
+ },
+ );
+
+ it('fails the turn of a run that throws', async () => {
+ const { service, agentAsyncExecutorService, agentRunConversationService } =
+ buildService();
+ const error = new Error('provider down');
+
+ agentAsyncExecutorService.executeAgent.mockRejectedValue(error);
+
+ await expect(service.run(RUN_INPUT)).rejects.toThrow('provider down');
+ expect(agentRunConversationService.failTurn).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ turnId: 'turn-id',
+ error,
+ });
+ expect(agentRunConversationService.closeTurn).not.toHaveBeenCalled();
+ });
+
+ it('reports a run that ran out of credits', async () => {
+ const { service } = buildService(
+ buildExecution({ hasNoMoreAvailableCredits: true }),
+ );
+
+ await expect(service.run(RUN_INPUT)).resolves.toMatchObject({
+ outcome: { status: 'NO_CREDITS' },
+ });
+ });
+
+ it('reports a run awaiting an answer once its question is recorded', async () => {
+ const { service, agentRunConversationService } = buildService(
+ buildExecution({ isPaused: true }),
+ );
+
+ agentRunConversationService.closeTurn.mockResolvedValue({
+ isAwaitingAnswer: true,
+ });
+
+ await expect(service.run(RUN_INPUT)).resolves.toMatchObject({
+ outcome: { status: 'AWAITING_ANSWER' },
+ });
+ });
+
+ it('hands back the calls of the last step a run paused on', async () => {
+ const { service } = buildService(pausedOnWait);
+
+ await expect(service.run(RUN_INPUT)).resolves.toMatchObject({
+ outcome: {
+ status: 'PAUSED',
+ isResumable: true,
+ pausedToolResults: [
+ {
+ toolName: 'wait_for_event',
+ output: { result: { status: 'pending' } },
+ },
+ ],
+ },
+ });
+ });
+
+ it('cannot resume a pause it failed to record', async () => {
+ const { service, agentRunConversationService } = buildService(pausedOnWait);
+
+ agentRunConversationService.closeTurn.mockRejectedValue(
+ new Error('db down'),
+ );
+
+ await expect(service.run(RUN_INPUT)).resolves.toMatchObject({
+ outcome: { status: 'PAUSED', isResumable: false },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
new file mode 100644
index 00000000000..2a789aa5f4e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
@@ -0,0 +1,287 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+import { In, IsNull, Not } from 'typeorm';
+
+import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+import { type AgentRunCallerFilter } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-filter.type';
+import { type AgentRunnerOpenedConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type';
+import { isToolOutputAwaitedByCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util';
+import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-history/utils/is-awaiting-pausing-tool-output.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+const RECENT_MESSAGES_TO_SEARCH_FOR_PENDING_CALL = 50;
+
+// The conversation of a run a caller drives, such as a workflow step: the calls
+// the run pauses on name the caller, so an answer or an outcome can find its
+// way back to it, and the caller can close them when it stops waiting.
+// Kept apart from the runner so callers that only settle or cancel waits avoid the
+// agent execution and tool dependencies.
+@Injectable()
+export class AgentCallerConversationService {
+ constructor(
+ @InjectAgentHistoryRepository('agentChatThread')
+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
+ @InjectAgentHistoryRepository('agentMessage')
+ private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
+ @InjectAgentHistoryRepository('agentMessagePart')
+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
+ private readonly agentInboxService: AgentInboxService,
+ private readonly threadRecordEventService: AgentChatThreadRecordEventService,
+ private readonly turnRecorderService: AgentTurnRecorderService,
+ ) {}
+
+ // A conversation the run opens is filed under done, and only comes back to
+ // the inbox when the agent needs its member
+ async openConversation({
+ workspaceId,
+ sender,
+ title,
+ threadKey,
+ fallbackThreadKey,
+ recipientWorkspaceMemberId,
+ fallbackRecipientWorkspaceMemberId = null,
+ }: {
+ workspaceId: string;
+ sender: AgentInboxSender;
+ title: string;
+ threadKey: string;
+ // where the run writes when the conversation its key names is unavailable
+ fallbackThreadKey: string;
+ recipientWorkspaceMemberId: string | null;
+ // used without a recipient; a member who cannot have the conversation leaves it to no inbox
+ fallbackRecipientWorkspaceMemberId?: string | null;
+ }): Promise<AgentRunnerOpenedConversation> {
+ const openThreadUnderKey = (key: string) => {
+ const openThread = (workspaceMemberId: string | null) =>
+ this.agentInboxService.openThread({
+ workspaceId,
+ sender,
+ workspaceMemberId,
+ threadKey: key,
+ title,
+ isArchivedOnCreate: true,
+ });
+
+ return isDefined(recipientWorkspaceMemberId)
+ ? openThread(recipientWorkspaceMemberId)
+ : this.openThreadWithFallbackRecipient({
+ fallbackRecipientWorkspaceMemberId,
+ openThread,
+ });
+ };
+
+ const keyedConversation = await openThreadUnderKey(threadKey);
+
+ // a conversation the recipient deleted is not written to again, and one already waiting on an answer
+ // has no room for another question, so this run starts its own
+ const isKeyedConversationUnavailable =
+ isDefined(keyedConversation.thread.deletedAt) ||
+ isDefined(keyedConversation.thread.pendingQuestionMessageId);
+ const { thread, isCreated } = isKeyedConversationUnavailable
+ ? await openThreadUnderKey(fallbackThreadKey)
+ : keyedConversation;
+
+ if (isDefined(thread.deletedAt)) {
+ return { status: 'DELETED' };
+ }
+
+ return { status: 'OPENED', threadId: thread.id, isCreated };
+ }
+
+ // The paused call stays pending in the conversation until the caller resolves it, then carries the outcome
+ async recordWaitOutcome({
+ workspaceId,
+ threadId,
+ caller,
+ toolNames,
+ toolOutput,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ caller: AgentRunCaller;
+ toolNames: string[];
+ toolOutput: Record<string, unknown>;
+ }): Promise<void> {
+ // messages can follow the call while it waits, so the latest one may not carry it
+ const recentMessages = await this.messageRepository.find(workspaceId, {
+ where: { threadId },
+ order: { createdAt: 'DESC' },
+ take: RECENT_MESSAGES_TO_SEARCH_FOR_PENDING_CALL,
+ relations: ['parts'],
+ });
+
+ const pendingPart = recentMessages
+ .flatMap((message) => message.parts ?? [])
+ .find(
+ (part) =>
+ isDefined(part.toolName) &&
+ toolNames.includes(part.toolName) &&
+ isAwaitingPausingToolOutput(part.toolOutput) &&
+ isToolOutputAwaitedByCaller({ toolOutput: part.toolOutput, caller }),
+ );
+
+ if (!isDefined(pendingPart)) {
+ throw new AiException(
+ 'The waiting call could not be found in the conversation',
+ AiExceptionCode.TOOL_CALL_NOT_FOUND,
+ );
+ }
+
+ await this.messagePartRepository.update(
+ workspaceId,
+ { id: pendingPart.id },
+ { toolOutput },
+ );
+ }
+
+ // A caller that stops waiting closes the calls its conversations wait on, so
+ // they no longer look waiting
+ async cancelAwaitingConversations({
+ workspaceId,
+ threadIds,
+ caller,
+ }: {
+ workspaceId: string;
+ threadIds: string[];
+ caller: AgentRunCallerFilter;
+ }): Promise<void> {
+ if (threadIds.length === 0) {
+ return;
+ }
+
+ // An answer holding a conversation's claim closes its calls itself once it finds its caller gone
+ const awaitingThreads = await this.threadRepository.find(workspaceId, {
+ where: {
+ id: In(threadIds),
+ pendingQuestionMessageId: Not(IsNull()),
+ activeStreamId: IsNull(),
+ },
+ select: ['id', 'pendingQuestionMessageId'],
+ });
+
+ const threadsAwaitingCaller = await this.filterThreadsAwaitingCaller({
+ threads: awaitingThreads,
+ caller,
+ workspaceId,
+ });
+
+ for (const { id, pendingQuestionMessageId } of threadsAwaitingCaller) {
+ if (!isDefined(pendingQuestionMessageId)) {
+ continue;
+ }
+
+ const { affected } = await this.threadRepository.update(
+ workspaceId,
+ { id, pendingQuestionMessageId, activeStreamId: IsNull() },
+ { pendingQuestionMessageId: null },
+ );
+
+ if (affected === 0) {
+ continue;
+ }
+
+ await this.threadRecordEventService.emitPendingQuestionCleared({
+ workspaceId,
+ threadId: id,
+ messageId: pendingQuestionMessageId,
+ });
+
+ // the question is already cleared, so its calls must close before anything else can fail
+ await closeOpenToolParts({
+ messagePartRepository: this.messagePartRepository,
+ messageId: pendingQuestionMessageId,
+ workspaceId,
+ });
+
+ await this.turnRecorderService.endWaitingTurn({
+ workspaceId,
+ messageId: pendingQuestionMessageId,
+ status: AgentTurnStatus.CANCELLED,
+ });
+ }
+ }
+
+ // the member may have moved on to another question in their conversation, which the caller must not close
+ private async filterThreadsAwaitingCaller<
+ TThread extends { pendingQuestionMessageId: string | null },
+ >({
+ threads,
+ caller,
+ workspaceId,
+ }: {
+ threads: TThread[];
+ caller: AgentRunCallerFilter;
+ workspaceId: string;
+ }): Promise<TThread[]> {
+ const pendingMessageIds = threads
+ .map((thread) => thread.pendingQuestionMessageId)
+ .filter(isDefined);
+
+ if (pendingMessageIds.length === 0) {
+ return [];
+ }
+
+ const pendingParts = await this.messagePartRepository.find(workspaceId, {
+ where: { messageId: In(pendingMessageIds) },
+ select: ['messageId', 'toolOutput'],
+ });
+
+ const messageIdsAwaitingCaller = new Set(
+ pendingParts
+ .filter((part) =>
+ isToolOutputAwaitedByCaller({ toolOutput: part.toolOutput, caller }),
+ )
+ .map((part) => part.messageId),
+ );
+
+ return threads.filter(
+ (thread) =>
+ isDefined(thread.pendingQuestionMessageId) &&
+ messageIdsAwaitingCaller.has(thread.pendingQuestionMessageId),
+ );
+ }
+
+ // a member who cannot have the conversation, such as one who cannot use AI,
+ // leaves a conversation no inbox receives
+ private async openThreadWithFallbackRecipient({
+ fallbackRecipientWorkspaceMemberId,
+ openThread,
+ }: {
+ fallbackRecipientWorkspaceMemberId: string | null;
+ openThread: (
+ workspaceMemberId: string | null,
+ ) => ReturnType<AgentInboxService['openThread']>;
+ }): ReturnType<AgentInboxService['openThread']> {
+ if (!isDefined(fallbackRecipientWorkspaceMemberId)) {
+ return openThread(null);
+ }
+
+ try {
+ return await openThread(fallbackRecipientWorkspaceMemberId);
+ } catch (error) {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return openThread(null);
+ }
+
+ throw error;
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
index 58e2770087b..0388945fda3 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
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import {
@@ -10,7 +10,10 @@ import { type ActorMetadata } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+import { mapAgentRunCallerToToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-run-caller-to-tool-call-workflow-step.util';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
@@ -23,15 +26,19 @@ import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-histor
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
@Injectable()
export class AgentRunConversationService {
+ private readonly logger = new Logger(AgentRunConversationService.name);
+
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly cacheLockService: CacheLockService,
private readonly turnRecorderService: AgentTurnRecorderService,
+ private readonly threadService: AgentChatThreadService,
) {}
withThreadLock<TResult>({
@@ -70,7 +77,7 @@ export class AgentRunConversationService {
workspaceId: string;
threadId: string;
title: string;
- agentId: string;
+ agentId: string | null;
senderUserWorkspaceId: string | null;
senderApplicationId: string | null;
createdBy: ActorMetadata;
@@ -128,38 +135,56 @@ export class AgentRunConversationService {
workspaceId,
threadId,
turnId,
+ title,
agentId,
execution,
+ caller,
}: {
workspaceId: string;
threadId: string;
turnId: string;
- agentId: string;
- execution: AgentExecutionResult;
- }): Promise<void> {
+ title: string;
+ agentId: string | null;
+ execution: RecordableAgentExecution;
+ caller?: AgentRunCaller;
+ }): Promise<{ isAwaitingAnswer: boolean }> {
const turn = { workspaceId, threadId, turnId, execution };
- const { isAwaitingAnswer } = await this.conversationWriterService
- .insertExecutionReply({
- workspaceId,
- threadId,
- turnId,
- agentId,
- execution,
- })
- .catch(async (error: unknown) => {
- await this.turnRecorderService.finishExecutedTurn({
- ...turn,
- error: mapErrorToStreamError(error),
- });
+ const { isAwaitingAnswer, replyParts } =
+ await this.conversationWriterService
+ .insertExecutionReply({
+ workspaceId,
+ threadId,
+ turnId,
+ agentId,
+ execution,
+ workflowStep: isDefined(caller)
+ ? mapAgentRunCallerToToolCallWorkflowStep(caller)
+ : undefined,
+ })
+ .catch(async (error: unknown) => {
+ await this.turnRecorderService.finishExecutedTurn({
+ ...turn,
+ error: mapErrorToStreamError(error),
+ });
- throw error;
- });
+ throw error;
+ });
await this.turnRecorderService.finishExecutedTurn({
...turn,
isAwaitingAnswer,
});
+
+ if (isAwaitingAnswer) {
+ await this.recordWaitingActivity({
+ workspaceId,
+ threadId,
+ text: findLastMessageText(replyParts) ?? title,
+ });
+ }
+
+ return { isAwaitingAnswer };
}
async failTurn({
@@ -179,6 +204,22 @@ export class AgentRunConversationService {
});
}
+ // the waiting call is already saved and can be answered from the conversation, so a
+ // failure to bring it back to the inbox must not fail the run
+ private async recordWaitingActivity(args: {
+ workspaceId: string;
+ threadId: string;
+ text: string;
+ }): Promise<void> {
+ await this.threadService
+ .recordThreadActivity(args)
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not record waiting activity on thread ${args.threadId}: ${error instanceof Error ? error.message : String(error)}`,
+ ),
+ );
+ }
+
private buildMessageParts(message: RunAgentMessage): ExtendedUIMessagePart[] {
const fileParts = (message.attachments ?? []).map(
(attachment): ExtendedFileUIPart => ({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
index 1bc7a696b60..c8e35d5e681 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
@@ -19,18 +19,13 @@ import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storag
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 { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
-import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
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 { 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';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
-import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
-import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
-import { withDedicatedAiTrace } from 'src/engine/metadata-modules/ai/ai-models/utils/with-dedicated-ai-trace.util';
import {
AiException,
AiExceptionCode,
@@ -54,10 +49,8 @@ export class AgentRunService {
constructor(
private readonly agentActorContextService: AgentActorContextService,
- private readonly agentAsyncExecutorService: AgentAsyncExecutorService,
- private readonly agentRunConversationService: AgentRunConversationService,
+ private readonly agentRunnerService: AgentRunnerService,
private readonly applicationLookupService: ApplicationLookupService,
- private readonly conversationReaderService: AgentConversationReaderService,
@InjectWorkspaceScopedRepository(AgentEntity)
private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
) {}
@@ -142,13 +135,6 @@ export class AgentRunService {
application,
};
- const actor: AgentConversationActor = isDefined(runAsContext)
- ? {
- type: 'user',
- userWorkspaceId: runAsContext.authContext.userWorkspaceId,
- }
- : { type: 'application', applicationId: application.id };
-
const senderUserWorkspaceId = this.resolveRunSender({
runAsContext,
callerApplication,
@@ -178,83 +164,38 @@ export class AgentRunService {
})
: messages;
- const runTurn = async (): Promise<RunAgentResult> => {
- const priorMessages = isDefined(thread)
- ? await this.conversationReaderService.loadMessages({
- workspaceId: workspace.id,
- threadId,
- actor,
- })
- : [];
-
- const turnId = await this.recordConversation({
- threadId,
- agentUniversalIdentifier: input.agentUniversalIdentifier,
- record: () =>
- this.agentRunConversationService.openTurn({
- workspaceId: workspace.id,
- threadId,
- title: threadTitle,
- agentId: agent.id,
- senderUserWorkspaceId,
- senderApplicationId: callerApplication?.id ?? null,
- createdBy,
- messages,
- }),
+ 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,
+ baseSystemPrompt: AGENT_RUN_BASE_SYSTEM_PROMPT,
+ actorContext: runAsContext?.actorContext,
+ authContext,
+ workspaceId: workspace.id,
+ userWorkspaceId:
+ runAsContext?.authContext.userWorkspaceId ?? requestUserWorkspaceId,
+ runAsRoleId: runAsContext?.roleId,
+ toolLoadingStrategy: 'lazy',
+ },
});
- let executionResult: AgentExecutionResult;
-
- try {
- executionResult = await withDedicatedAiTrace(() =>
- this.agentAsyncExecutorService.executeAgent({
- agent,
- messages: executionMessages,
- priorMessages,
- baseSystemPrompt: AGENT_RUN_BASE_SYSTEM_PROMPT,
- actorContext: runAsContext?.actorContext,
- authContext,
- workspaceId: workspace.id,
- userWorkspaceId:
- runAsContext?.authContext.userWorkspaceId ??
- requestUserWorkspaceId,
- runAsRoleId: runAsContext?.roleId,
- toolLoadingStrategy: 'lazy',
- }),
- );
- } catch (error) {
- if (isDefined(turnId)) {
- await this.recordConversation({
- threadId,
- agentUniversalIdentifier: input.agentUniversalIdentifier,
- record: () =>
- this.agentRunConversationService.failTurn({
- workspaceId: workspace.id,
- turnId,
- error,
- }),
- });
- }
-
- throw error;
- }
-
- if (isDefined(turnId)) {
- await this.recordConversation({
- threadId,
- agentUniversalIdentifier: input.agentUniversalIdentifier,
- record: () =>
- this.agentRunConversationService.closeTurn({
- workspaceId: workspace.id,
- threadId,
- turnId,
- agentId: agent.id,
- execution: executionResult,
- }),
- });
- }
-
- if (executionResult.hasNoMoreAvailableCredits) {
+ if (outcome.status === 'NO_CREDITS') {
return {
result: null,
error: 'Agent stopped: no more available credits.',
@@ -264,21 +205,11 @@ export class AgentRunService {
}
return {
- result: executionResult.result,
+ result: outcome.status === 'COMPLETED' ? outcome.result : null,
error: null,
success: true,
threadId,
};
- };
-
- try {
- return isDefined(thread)
- ? await this.agentRunConversationService.withThreadLock({
- workspaceId: workspace.id,
- threadId,
- work: runTurn,
- })
- : await runTurn();
} catch (error) {
if (
error instanceof AiException &&
@@ -340,28 +271,6 @@ export class AgentRunService {
: buildCreatedByFromApplication({ application });
}
- // A record of the run, not its outcome, so a write failure must not fail the run
- private async recordConversation<TResult>({
- threadId,
- agentUniversalIdentifier,
- record,
- }: {
- threadId: string;
- agentUniversalIdentifier: string;
- record: () => Promise<TResult>;
- }): Promise<TResult | null> {
- try {
- return await record();
- } catch (error) {
- this.logger.error(
- `Failed to record the turn of ${agentUniversalIdentifier} in thread ${threadId}`,
- error instanceof Error ? error.stack : error,
- );
-
- return null;
- }
- }
-
private assertCanContinueConversation({
callerApplication,
messages,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
new file mode 100644
index 00000000000..ceda7fc66f1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
@@ -0,0 +1,171 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
+import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
+import { type AgentRunnerResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type';
+import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
+import { buildAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util';
+import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
+import { withDedicatedAiTrace } from 'src/engine/metadata-modules/ai/ai-models/utils/with-dedicated-ai-trace.util';
+
+// Runs one agent turn and records it in its conversation
+@Injectable()
+export class AgentRunnerService {
+ private readonly logger = new Logger(AgentRunnerService.name);
+
+ constructor(
+ private readonly agentAsyncExecutorService: AgentAsyncExecutorService,
+ private readonly agentRunConversationService: AgentRunConversationService,
+ private readonly conversationReaderService: AgentConversationReaderService,
+ ) {}
+
+ run(input: AgentRunnerRunInput): Promise<AgentRunnerResult> {
+ const { workspaceId, conversation } = input;
+
+ // a continued conversation is read before the run, so two runs on it must not interleave
+ return conversation.isCreated
+ ? this.runTurn(input)
+ : this.agentRunConversationService.withThreadLock({
+ workspaceId,
+ threadId: conversation.threadId,
+ work: () => this.runTurn(input),
+ });
+ }
+
+ private async runTurn({
+ workspaceId,
+ conversation: { threadId, isCreated },
+ conversationActor,
+ caller,
+ turn,
+ execution,
+ }: AgentRunnerRunInput): Promise<AgentRunnerResult> {
+ const priorMessages = isCreated
+ ? []
+ : await this.conversationReaderService.loadMessages({
+ workspaceId,
+ threadId,
+ actor: conversationActor,
+ });
+ const agentId = execution.agent?.id ?? null;
+
+ const turnId = await this.recordConversation(threadId, async () =>
+ this.agentRunConversationService.openTurn({
+ workspaceId,
+ threadId,
+ title: turn.title,
+ agentId,
+ senderUserWorkspaceId: turn.senderUserWorkspaceId,
+ senderApplicationId: turn.senderApplicationId,
+ createdBy: await turn.resolveCreatedBy(),
+ messages: turn.messages,
+ }),
+ );
+
+ const startedAtMs = Date.now();
+
+ let executionResult: AgentExecutionResult;
+
+ try {
+ executionResult = await withDedicatedAiTrace(() =>
+ this.agentAsyncExecutorService.executeAgent({
+ ...execution,
+ priorMessages,
+ }),
+ );
+ } catch (error) {
+ if (isDefined(turnId)) {
+ await this.recordConversation(threadId, () =>
+ this.agentRunConversationService.failTurn({
+ workspaceId,
+ turnId,
+ error,
+ }),
+ );
+ }
+
+ throw error;
+ }
+
+ const durationMs = Date.now() - startedAtMs;
+
+ const closedTurn = isDefined(turnId)
+ ? await this.recordConversation(threadId, () =>
+ this.agentRunConversationService.closeTurn({
+ workspaceId,
+ threadId,
+ turnId,
+ title: turn.title,
+ agentId,
+ execution: executionResult,
+ caller,
+ }),
+ )
+ : null;
+
+ return {
+ threadId,
+ outcome: this.buildOutcome({
+ execution: executionResult,
+ isRecorded: isDefined(closedTurn),
+ isAwaitingAnswer: closedTurn?.isAwaitingAnswer ?? false,
+ }),
+ summary: buildAgentRunSummary({ execution: executionResult, durationMs }),
+ };
+ }
+
+ // A record of the run, not its outcome, so a write failure must not fail the run
+ private async recordConversation<TResult>(
+ threadId: string,
+ record: () => Promise<TResult>,
+ ): Promise<TResult | null> {
+ try {
+ return await record();
+ } catch (error) {
+ this.logger.error(
+ `Failed to record the agent turn in thread ${threadId}`,
+ error instanceof Error ? error.stack : error,
+ );
+
+ return null;
+ }
+ }
+
+ private buildOutcome({
+ execution,
+ isRecorded,
+ isAwaitingAnswer,
+ }: {
+ execution: AgentExecutionResult;
+ isRecorded: boolean;
+ isAwaitingAnswer: boolean;
+ }): AgentRunnerOutcome {
+ if (execution.hasNoMoreAvailableCredits) {
+ return { status: 'NO_CREDITS' };
+ }
+
+ if (!execution.isPaused) {
+ return { status: 'COMPLETED', result: execution.result };
+ }
+
+ if (isAwaitingAnswer) {
+ return { status: 'AWAITING_ANSWER' };
+ }
+
+ const lastStepToolResults =
+ execution.steps[execution.steps.length - 1]?.toolResults ?? [];
+
+ return {
+ status: 'PAUSED',
+ isResumable: isRecorded,
+ pausedToolResults: lastStepToolResults.map(({ toolName, output }) => ({
+ toolName,
+ output,
+ })),
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-filter.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-filter.type.ts
new file mode 100644
index 00000000000..942fc096cab
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-filter.type.ts
@@ -0,0 +1,7 @@
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+
+// matches every caller whose ref holds these values, such as every step of one run
+export type AgentRunCallerFilter = {
+ type: AgentRunCaller['type'];
+ ref: Partial<AgentRunCaller['ref']>;
+};
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.ts
new file mode 100644
index 00000000000..15d7d8711d8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type.ts
@@ -0,0 +1,5 @@
+// who started a run and waits on what it pauses on; written on the calls it leaves pending
+export type AgentRunCaller = {
+ type: 'WORKFLOW_STEP';
+ ref: { workflowRunId: string; stepId: string };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type.ts
new file mode 100644
index 00000000000..a5544a4d0ef
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type.ts
@@ -0,0 +1,5 @@
+export type AgentRunConversation = {
+ threadId: string;
+ // a conversation just created holds nothing to continue from
+ isCreated: boolean;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-paused-tool-result.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-paused-tool-result.type.ts
new file mode 100644
index 00000000000..df3b3f64a48
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-paused-tool-result.type.ts
@@ -0,0 +1,4 @@
+export type AgentRunPausedToolResult = {
+ toolName: string;
+ output: unknown;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts
new file mode 100644
index 00000000000..3643289228c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type.ts
@@ -0,0 +1,20 @@
+import { type AgentRunToolCallLog } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type';
+
+export type AgentRunSummary = {
+ modelId: string;
+ usage: {
+ inputTokens: number;
+ outputTokens: number;
+ reasoningTokens?: number;
+ cacheReadTokens?: number;
+ cacheCreationTokens?: number;
+ totalTokens: number;
+ };
+ cost: {
+ totalCostInDollars: number;
+ creditsUsedMicro: number;
+ };
+ nativeWebSearchCallCount: number;
+ toolCalls: AgentRunToolCallLog[];
+ durationMs: number;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts
new file mode 100644
index 00000000000..89a58d58199
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type.ts
@@ -0,0 +1,9 @@
+export type AgentRunToolCallLog = {
+ toolName: string;
+ toolCallId: string;
+ providerExecuted?: boolean;
+ input?: unknown;
+ output?: unknown;
+ errorMessage?: string;
+ state: 'started' | 'success' | 'error' | 'awaiting-approval';
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts
new file mode 100644
index 00000000000..cc256be9bdc
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-opened-conversation.type.ts
@@ -0,0 +1,6 @@
+import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
+
+export type AgentRunnerOpenedConversation =
+ | ({ status: 'OPENED' } & AgentRunConversation)
+ // the recipient deleted both the conversation its key names and the fallback one
+ | { status: 'DELETED' };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type.ts
new file mode 100644
index 00000000000..5de11538507
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type.ts
@@ -0,0 +1,13 @@
+import { type AgentRunPausedToolResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-paused-tool-result.type';
+
+export type AgentRunnerOutcome =
+ | { status: 'COMPLETED'; result: object }
+ | { status: 'NO_CREDITS' }
+ | { status: 'AWAITING_ANSWER' }
+ // paused on a call that is not a question, such as a wait the caller resolves itself.
+ // Only a recorded pause can be continued, since continuing reads the conversation
+ | {
+ status: 'PAUSED';
+ isResumable: boolean;
+ pausedToolResults: AgentRunPausedToolResult[];
+ };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts
new file mode 100644
index 00000000000..aab1a56fc34
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-result.type.ts
@@ -0,0 +1,8 @@
+import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
+import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
+
+export type AgentRunnerResult = {
+ threadId: string;
+ outcome: AgentRunnerOutcome;
+ summary: AgentRunSummary;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
new file mode 100644
index 00000000000..a4a8f5894f4
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
@@ -0,0 +1,29 @@
+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 AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
+
+export type AgentRunnerRunInput = {
+ workspaceId: string;
+ conversation: AgentRunConversation;
+ // who the continued conversation is read for, so turns others acted on read as theirs
+ conversationActor?: AgentConversationActor;
+ // set when the caller waits on the calls the run pauses on
+ caller?: AgentRunCaller;
+ 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'
+ >;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-summary.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-summary.util.spec.ts
new file mode 100644
index 00000000000..c1462071725
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-summary.util.spec.ts
@@ -0,0 +1,80 @@
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { buildAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util';
+
+jest.mock(
+ 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util',
+ () => ({
+ mapAgentStepsToToolCallLogs: jest.fn().mockReturnValue([
+ {
+ toolName: 'web_search',
+ toolCallId: 'call-1',
+ state: 'success',
+ },
+ ]),
+ }),
+);
+
+const baseExecution: AgentExecutionResult = {
+ result: { answer: 'hello' },
+ usage: {
+ inputTokens: 100,
+ outputTokens: 50,
+ totalTokens: 150,
+ inputTokenDetails: { cacheReadTokens: 20 },
+ outputTokenDetails: { reasoningTokens: 10 },
+ } as AgentExecutionResult['usage'],
+ cacheCreationTokens: 5,
+ nativeWebSearchCallCount: 2,
+ hasNoMoreAvailableCredits: false,
+ isPaused: false,
+ modelId: 'claude-sonnet-4',
+ totalCostInDollars: 0.012,
+ creditsUsedMicro: 12_000,
+ turnUsage: {
+ inputTokens: 100,
+ outputTokens: 50,
+ cacheReadTokens: 20,
+ cacheCreationTokens: 5,
+ inputCredits: 0,
+ outputCredits: 0,
+ },
+ steps: [],
+};
+
+describe('buildAgentRunSummary', () => {
+ it('summarizes usage, cost and tool calls of a run', () => {
+ expect(
+ buildAgentRunSummary({ execution: baseExecution, durationMs: 1234 }),
+ ).toEqual({
+ modelId: 'claude-sonnet-4',
+ usage: {
+ inputTokens: 100,
+ outputTokens: 50,
+ reasoningTokens: 10,
+ cacheReadTokens: 20,
+ cacheCreationTokens: 5,
+ totalTokens: 150,
+ },
+ cost: { totalCostInDollars: 0.012, creditsUsedMicro: 12_000 },
+ nativeWebSearchCallCount: 2,
+ toolCalls: [
+ { toolName: 'web_search', toolCallId: 'call-1', state: 'success' },
+ ],
+ durationMs: 1234,
+ });
+ });
+
+ it('falls back to zero tokens when the provider did not report usage', () => {
+ const summary = buildAgentRunSummary({
+ execution: {
+ ...baseExecution,
+ usage: {} as AgentExecutionResult['usage'],
+ },
+ durationMs: 100,
+ });
+
+ expect(summary.usage.inputTokens).toBe(0);
+ expect(summary.usage.outputTokens).toBe(0);
+ expect(summary.usage.totalTokens).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/map-ai-steps-to-tool-call-logs.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-agent-steps-to-tool-call-logs.util.spec.ts
similarity index 89%
rename from packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/map-ai-steps-to-tool-call-logs.util.spec.ts
rename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-agent-steps-to-tool-call-logs.util.spec.ts
index f2efc21429f..2a27a708db0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/map-ai-steps-to-tool-call-logs.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-agent-steps-to-tool-call-logs.util.spec.ts
@@ -1,15 +1,15 @@
import { type StepResult, type ToolSet } from 'ai';
-import { mapAiStepsToToolCallLogs } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util';
+import { mapAgentStepsToToolCallLogs } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util';
type StepContentPart = StepResult<ToolSet>['content'][number];
const buildStep = (content: StepContentPart[]): StepResult<ToolSet> =>
({ content }) as unknown as StepResult<ToolSet>;
-describe('mapAiStepsToToolCallLogs', () => {
+describe('mapAgentStepsToToolCallLogs', () => {
it('returns an empty array when there are no steps', () => {
- expect(mapAiStepsToToolCallLogs([])).toEqual([]);
+ expect(mapAgentStepsToToolCallLogs([])).toEqual([]);
});
it('pairs a tool-call with its tool-result into a single success entry', () => {
@@ -31,7 +31,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
@@ -61,7 +61,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
expect(result).toHaveLength(1);
expect(result[0].state).toBe('error');
@@ -92,7 +92,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- expect(mapAiStepsToToolCallLogs(steps)[0]).toMatchObject({
+ expect(mapAgentStepsToToolCallLogs(steps)[0]).toMatchObject({
state: 'error',
errorMessage: 'View not found',
output,
@@ -120,7 +120,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
const serializedInput = JSON.stringify(result[0].input);
const serializedOutput = JSON.stringify(result[0].output);
@@ -146,7 +146,7 @@ describe('mapAiStepsToToolCallLogs', () => {
const steps = [buildStep(buildToolCalls(0)), buildStep(buildToolCalls(1))];
- expect(mapAiStepsToToolCallLogs(steps)).toHaveLength(200);
+ expect(mapAgentStepsToToolCallLogs(steps)).toHaveLength(200);
});
it('preserves all web_search sources in tool output', () => {
@@ -176,7 +176,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
const output = result[0].output as {
sources: unknown[];
sourcesDroppedCount?: number;
@@ -216,7 +216,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
const output = result[0].output as {
result: { records: Array<Record<string, unknown>> };
};
@@ -243,7 +243,7 @@ describe('mapAiStepsToToolCallLogs', () => {
]),
];
- const result = mapAiStepsToToolCallLogs(steps);
+ const result = mapAgentStepsToToolCallLogs(steps);
expect(result).toHaveLength(1);
expect(result[0].toolName).toBe('foo');
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts
new file mode 100644
index 00000000000..921943fae5a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util.ts
@@ -0,0 +1,28 @@
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
+import { mapAgentStepsToToolCallLogs } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util';
+
+export const buildAgentRunSummary = ({
+ execution,
+ durationMs,
+}: {
+ execution: AgentExecutionResult;
+ durationMs: number;
+}): AgentRunSummary => ({
+ modelId: execution.modelId,
+ usage: {
+ inputTokens: execution.usage.inputTokens ?? 0,
+ outputTokens: execution.usage.outputTokens ?? 0,
+ reasoningTokens: execution.usage.outputTokenDetails?.reasoningTokens,
+ cacheReadTokens: execution.usage.inputTokenDetails?.cacheReadTokens,
+ cacheCreationTokens: execution.cacheCreationTokens,
+ totalTokens: execution.usage.totalTokens ?? 0,
+ },
+ cost: {
+ totalCostInDollars: execution.totalCostInDollars,
+ creditsUsedMicro: execution.creditsUsedMicro,
+ },
+ nativeWebSearchCallCount: execution.nativeWebSearchCallCount,
+ toolCalls: mapAgentStepsToToolCallLogs(execution.steps),
+ durationMs,
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util.ts
new file mode 100644
index 00000000000..1110a1af3df
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/is-tool-output-awaited-by-caller.util.ts
@@ -0,0 +1,24 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AgentRunCallerFilter } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-filter.type';
+import { readToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-workflow-step.util';
+
+export const isToolOutputAwaitedByCaller = ({
+ toolOutput,
+ caller,
+}: {
+ toolOutput: unknown;
+ caller: AgentRunCallerFilter;
+}): boolean => {
+ const workflowStep = readToolCallWorkflowStep(toolOutput);
+
+ if (!isDefined(workflowStep) || caller.type !== 'WORKFLOW_STEP') {
+ return false;
+ }
+
+ return (
+ (!isDefined(caller.ref.workflowRunId) ||
+ caller.ref.workflowRunId === workflowStep.workflowRunId) &&
+ (!isDefined(caller.ref.stepId) || caller.ref.stepId === workflowStep.stepId)
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-run-caller-to-tool-call-workflow-step.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-run-caller-to-tool-call-workflow-step.util.ts
new file mode 100644
index 00000000000..679b9ce5ffc
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-run-caller-to-tool-call-workflow-step.util.ts
@@ -0,0 +1,10 @@
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+import { type ToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-history/types/tool-call-workflow-step.type';
+
+// the caller is written on pending calls in the shape answers already read
+export const mapAgentRunCallerToToolCallWorkflowStep = (
+ caller: AgentRunCaller,
+): ToolCallWorkflowStep => ({
+ workflowRunId: caller.ref.workflowRunId,
+ stepId: caller.ref.stepId,
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
similarity index 89%
rename from packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util.ts
rename to packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
index b72e6c24783..695fcb1ae7d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-agent-steps-to-tool-call-logs.util.ts
@@ -1,8 +1,7 @@
import { type StepResult, type ToolSet } from 'ai';
-import { type AiToolCallLog } from 'twenty-shared/workflow';
-
import { isFailedToolOutput } from 'src/engine/core-modules/tool-provider/utils/is-failed-tool-output.util';
+import { type AgentRunToolCallLog } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-tool-call-log.type';
import {
TRUNCATION_SENTINEL,
truncateStringToUtf8ByteBudget,
@@ -67,11 +66,11 @@ const truncateUnknownForLog = (value: unknown, maxBytes: number): unknown => {
return truncated ? truncatedValue : value;
};
-export const mapAiStepsToToolCallLogs = (
+export const mapAgentStepsToToolCallLogs = (
steps: StepResult<ToolSet>[],
-): AiToolCallLog[] => {
- const ordered: AiToolCallLog[] = [];
- const openByCallId = new Map<string, AiToolCallLog>();
+): AgentRunToolCallLog[] => {
+ const ordered: AgentRunToolCallLog[] = [];
+ const openByCallId = new Map<string, AgentRunToolCallLog>();
for (const step of steps) {
for (const part of step.content) {
@@ -80,7 +79,7 @@ export const mapAiStepsToToolCallLogs = (
}
if (part.type === 'tool-call') {
- const entry: AiToolCallLog = {
+ const entry: AgentRunToolCallLog = {
toolName: part.toolName,
toolCallId: part.toolCallId,
input: truncateUnknownForLog(part.input, MAX_TOOL_INPUT_BYTES),
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.ts
index 445eec58486..9d7acd1078c 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
@@ -3,8 +3,7 @@ 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 { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
-import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.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';
@@ -46,10 +45,7 @@ const buildAgent = (isTriggerActive = true) => ({
describe('AgentTriggerRunnerService', () => {
let service: AgentTriggerRunnerService;
- let executeAgent: jest.Mock;
- let openTurn: jest.Mock;
- let closeTurn: jest.Mock;
- let failTurn: jest.Mock;
+ let runAgent: jest.Mock;
let currentRoleId: string | undefined;
let findAgent: jest.Mock;
let findApplication: jest.Mock;
@@ -60,21 +56,14 @@ describe('AgentTriggerRunnerService', () => {
findApplication = jest
.fn()
.mockResolvedValue({ id: 'application-id', name: 'App' });
- executeAgent = jest.fn().mockResolvedValue({ result: { text: 'done' } });
- openTurn = jest.fn().mockResolvedValue('turn-id');
- closeTurn = jest.fn().mockResolvedValue(undefined);
- failTurn = jest.fn().mockResolvedValue(undefined);
+ runAgent = jest.fn().mockResolvedValue(undefined);
const module: TestingModule = await Test.createTestingModule({
providers: [
AgentTriggerRunnerService,
{
- provide: AgentAsyncExecutorService,
- useValue: { executeAgent },
- },
- {
- provide: AgentRunConversationService,
- useValue: { openTurn, closeTurn, failTurn },
+ provide: AgentRunnerService,
+ useValue: { run: runAgent },
},
{
provide: ApplicationLookupService,
@@ -111,42 +100,27 @@ describe('AgentTriggerRunnerService', () => {
service = module.get(AgentTriggerRunnerService);
});
- it('should run the agent and record the run', async () => {
+ it('should run the agent as itself in a new conversation', async () => {
await service.run(JOB_DATA);
- expect(executeAgent).toHaveBeenCalledWith(
+ expect(runAgent).toHaveBeenCalledWith(
expect.objectContaining({
- authContext: expect.objectContaining({
- type: 'application',
- actingAgent: { id: AGENT_ID, label: 'Enricher' },
+ conversation: { threadId: expect.any(String), isCreated: true },
+ turn: expect.objectContaining({
+ title: 'Enricher',
+ senderUserWorkspaceId: null,
+ senderApplicationId: 'application-id',
+ }),
+ execution: expect.objectContaining({
+ actorContext: expect.objectContaining({ name: 'Enricher' }),
+ authContext: expect.objectContaining({
+ type: 'application',
+ actingAgent: { id: AGENT_ID, label: 'Enricher' },
+ }),
+ toolLoadingStrategy: 'lazy',
}),
- toolLoadingStrategy: 'lazy',
- }),
- );
- expect(openTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: AGENT_ID,
- createdBy: expect.objectContaining({ name: 'Enricher' }),
}),
);
- expect(closeTurn).toHaveBeenCalledWith(
- expect.objectContaining({ turnId: 'turn-id' }),
- );
- });
-
- it('should record a failed run when the agent throws', async () => {
- const error = new Error('model unavailable');
-
- executeAgent.mockRejectedValue(error);
-
- await expect(service.run(JOB_DATA)).rejects.toThrow('model unavailable');
-
- expect(failTurn).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- turnId: 'turn-id',
- error,
- });
- expect(closeTurn).not.toHaveBeenCalled();
});
it.each([
@@ -168,8 +142,7 @@ describe('AgentTriggerRunnerService', () => {
await service.run(JOB_DATA);
- expect(executeAgent).not.toHaveBeenCalled();
- expect(openTurn).not.toHaveBeenCalled();
+ expect(runAgent).not.toHaveBeenCalled();
});
it('should not run when the agent role changed since dispatch', async () => {
@@ -177,21 +150,6 @@ describe('AgentTriggerRunnerService', () => {
await service.run(JOB_DATA);
- expect(executeAgent).not.toHaveBeenCalled();
- });
-
- it('should still run the agent when the run cannot be recorded', async () => {
- openTurn.mockRejectedValue(new Error('history unavailable'));
-
- await expect(service.run(JOB_DATA)).resolves.toBeUndefined();
-
- expect(executeAgent).toHaveBeenCalled();
- expect(closeTurn).not.toHaveBeenCalled();
- });
-
- it('should not fail the run when closing its record fails', async () => {
- closeTurn.mockRejectedValue(new Error('history unavailable'));
-
- await expect(service.run(JOB_DATA)).resolves.toBeUndefined();
+ expect(runAgent).not.toHaveBeenCalled();
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
index 2b2619b93d4..a1220fd5adb 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
@@ -10,15 +10,12 @@ import { buildCreatedByFromAgent } from 'src/engine/core-modules/actor/utils/bui
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 { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
-import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
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 { withDedicatedAiTrace } from 'src/engine/metadata-modules/ai/ai-models/utils/with-dedicated-ai-trace.util';
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';
@@ -28,8 +25,7 @@ export class AgentTriggerRunnerService {
private readonly logger = new Logger(AgentTriggerRunnerService.name);
constructor(
- private readonly agentAsyncExecutorService: AgentAsyncExecutorService,
- private readonly agentRunConversationService: AgentRunConversationService,
+ private readonly agentRunnerService: AgentRunnerService,
private readonly applicationLookupService: ApplicationLookupService,
@InjectWorkspaceScopedRepository(AgentEntity)
private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
@@ -101,73 +97,38 @@ export class AgentTriggerRunnerService {
instructions: trigger.instructions,
payload,
});
- const threadId = buildAgentRunThreadId({
- applicationId: application.id,
- agentId: agent.id,
- threadKey: `trigger:${trigger.id}:${v4()}`,
- });
const createdBy = buildCreatedByFromAgent({
agent: actingAgent,
applicationId: application.id,
});
- const logRecordFailure = (error: unknown) => {
- this.logger.error(
- `Failed to record the run of trigger ${triggerId} of agent ${agentId} in thread ${threadId}`,
- error instanceof Error ? error.stack : error,
- );
- return null;
- };
-
- // The agent acts through its tools, so a failed log write must not fail the run
- const turnId = await this.agentRunConversationService
- .openTurn({
- workspaceId,
- threadId,
+ 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,
- agentId: agent.id,
senderUserWorkspaceId: null,
senderApplicationId: application.id,
- createdBy,
messages,
- })
- .catch(logRecordFailure);
-
- let execution: AgentExecutionResult;
-
- try {
- execution = await withDedicatedAiTrace(() =>
- this.agentAsyncExecutorService.executeAgent({
- agent,
- messages,
- baseSystemPrompt: AGENT_TRIGGER_BASE_SYSTEM_PROMPT,
- actorContext: createdBy,
- authContext,
- workspaceId,
- userWorkspaceId: null,
- toolLoadingStrategy: 'lazy',
- }),
- );
- } catch (error) {
- if (isDefined(turnId)) {
- await this.agentRunConversationService
- .failTurn({ workspaceId, turnId, error })
- .catch(logRecordFailure);
- }
-
- throw error;
- }
-
- if (isDefined(turnId)) {
- await this.agentRunConversationService
- .closeTurn({
- workspaceId,
- threadId,
- turnId,
- agentId: agent.id,
- execution,
- })
- .catch(logRecordFailure);
- }
+ resolveCreatedBy: async () => createdBy,
+ },
+ execution: {
+ agent,
+ messages,
+ baseSystemPrompt: AGENT_TRIGGER_BASE_SYSTEM_PROMPT,
+ actorContext: createdBy,
+ authContext,
+ workspaceId,
+ userWorkspaceId: null,
+ toolLoadingStrategy: 'lazy',
+ },
+ });
}
}
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.ts
index 04ba7d58148..144872f15dc 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
@@ -10,6 +10,7 @@ import {
WorkflowVersionStatus,
} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import {
AiException,
AiExceptionCode,
@@ -29,6 +30,7 @@ import {
WorkflowStatus,
type WorkflowWorkspaceEntity,
} from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';
+import { buildWorkflowStepCaller } from 'src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util';
import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
@@ -169,6 +171,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
constructor(
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
+ private readonly agentRunConversationService: AgentRunConversationService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
@InjectWorkspaceScopedRepository(WorkflowEntity)
private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
@@ -267,22 +270,32 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
throw error;
});
- const turnId = await this.workflowAgentConversationService.openTurn({
- runInfo: { workspaceId, workflowRunId },
+ const turnId = await this.agentRunConversationService.openTurn({
+ workspaceId,
threadId,
+ title: workflow.step.name,
agentId: null,
- prompt: agentWorkflow.runPrompt,
- initiatorUserWorkspaceId: null,
+ senderUserWorkspaceId: null,
+ senderApplicationId: null,
+ messages: [{ role: 'user', content: agentWorkflow.runPrompt }],
+ createdBy:
+ await this.workflowAgentConversationService.findTurnCreatedBy({
+ workspaceId,
+ workflowRunId,
+ }),
});
- await this.workflowAgentConversationService.closeTurn({
+ await this.agentRunConversationService.closeTurn({
workspaceId,
threadId,
turnId,
- workflowStep: { workflowRunId, stepId: workflow.step.id },
+ caller: buildWorkflowStepCaller({
+ workflowRunId,
+ stepId: workflow.step.id,
+ }),
title: workflow.step.name,
agentId: null,
- executionResult: {
+ execution: {
isPaused: true,
steps: [{ content }],
},
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
index 39172d891b8..00ca005ac46 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
@@ -1,3 +1,4 @@
+import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@@ -46,6 +47,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
@Module({
imports: [
AgentHistoryModule,
+ AiAgentExecutionModule,
TimelineActivityModule,
ObjectMetadataModule,
FieldMetadataModule,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-manager.module.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-manager.module.ts
index 829df2efa3b..88e15be4b0a 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-manager.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-manager.module.ts
@@ -17,7 +17,6 @@ import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
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';
import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';
-import { DevSeederModule } from 'src/engine/workspace-manager/dev-seeder/dev-seeder.module';
import { TwentyStandardApplicationModule } from 'src/engine/workspace-manager/twenty-standard-application/twenty-standard-application.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -28,7 +27,6 @@ import { WorkspaceManagerService } from './workspace-manager.service';
WorkspaceDataSourceModule,
WorkspaceMigrationModule,
ObjectMetadataModule,
- DevSeederModule,
FeatureFlagModule,
PermissionsModule,
AiAgentModule,
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/calendar-event-participant-manager.module.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/calendar-event-participant-manager.module.ts
index e96d51a6061..f2a9e32c67d 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/calendar-event-participant-manager.module.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/calendar-event-participant-manager.module.ts
@@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';
import { CalendarEventParticipantMatchParticipantJob } from 'src/modules/calendar/calendar-event-participant-manager/jobs/calendar-event-participant-match-participant.job';
import { CalendarEventParticipantPersonListener } from 'src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-person.listener';
@@ -14,7 +13,6 @@ import { MatchParticipantModule } from 'src/modules/match-participant/match-part
@Module({
imports: [
WorkspaceDataSourceModule,
- WorkspaceModule,
TypeOrmModule.forFeature([WorkspaceEntity]),
ContactCreationManagerModule,
MatchParticipantModule,
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.ts
new file mode 100644
index 00000000000..1f9de883d50
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util.ts
@@ -0,0 +1,5 @@
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+
+export const buildWorkflowStepCaller = (
+ ref: AgentRunCaller['ref'],
+): AgentRunCaller => ({ type: 'WORKFLOW_STEP', ref });
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
index 1680cd7ff0a..100612bea8d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
@@ -4,7 +4,6 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
-import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
@@ -20,7 +19,6 @@ import { AiAgentWorkflowAction } from './ai-agent.workflow-action';
WorkflowExecutionContextModule,
ApplicationModule,
AiAgentExecutionModule,
- AgentHistoryModule,
TypeOrmModule.forFeature([AgentEntity]),
WorkflowRunModule,
UserWorkspaceModule,
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.ts
index 60d905b11ae..f9e0ca0cf6b 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
@@ -11,12 +11,12 @@ import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
-import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const';
-import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -28,11 +28,13 @@ import {
import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
+import { buildWorkflowStepCaller } from 'src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util';
import { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';
import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
import { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util';
import { APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant';
import { WORKFLOW_AGENT_WAIT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant';
+import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
import { createWorkflowAgentWaitTools } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util';
import { buildWaitOutcomeToolOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-wait-outcome-tool-output.util';
import { findAgentStepWait } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util';
@@ -52,11 +54,11 @@ export class AiAgentWorkflowAction implements WorkflowAction {
private readonly logger = new Logger(AiAgentWorkflowAction.name);
constructor(
- private readonly aiAgentExecutionService: AgentAsyncExecutorService,
+ private readonly agentRunnerService: AgentRunnerService,
+ private readonly agentCallerConversationService: AgentCallerConversationService,
private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,
private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
- private readonly conversationReaderService: AgentConversationReaderService,
@InjectWorkspaceScopedRepository(AgentEntity)
private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
) {}
@@ -83,21 +85,16 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const { agentId, prompt, humanInputInstructions } = step.settings.input;
const workspaceId = runInfo.workspaceId;
- const workflowStep = {
- workflowRunId: runInfo.workflowRunId,
- stepId: currentStepId,
- };
- const { workspaceMemberId: recipientWorkspaceMemberId, conversation } =
- resolveInput(
- {
- workspaceMemberId: step.settings.input.workspaceMemberId,
- conversation: step.settings.input.conversation,
- },
- context,
- ) as Pick<
- WorkflowAiAgentActionInput,
- 'workspaceMemberId' | 'conversation'
- >;
+ const {
+ workspaceMemberId: recipientWorkspaceMemberId,
+ conversation: conversationSettings,
+ } = resolveInput(
+ {
+ workspaceMemberId: step.settings.input.workspaceMemberId,
+ conversation: step.settings.input.conversation,
+ },
+ context,
+ ) as Pick<WorkflowAiAgentActionInput, 'workspaceMemberId' | 'conversation'>;
// a variable can resolve to any value, so anything but a member id or nothing is refused
if (
@@ -150,83 +147,59 @@ export class AiAgentWorkflowAction implements WorkflowAction {
? executionContext.authContext.userWorkspaceId
: null;
- const resolvedPrompt = resolveInput(prompt, context) as string;
+ const resolvedPrompt = resolveInput(prompt, context) as string | undefined;
// a resumed step continues where it paused, any other opens the conversation its key names
- const conversationThread = isDefined(resumedThreadId)
- ? {
- threadId: resumedThreadId,
- isResumed: true,
- priorMessages: await this.conversationReaderService.loadMessages({
- workspaceId,
- threadId: resumedThreadId,
- }),
- }
- : {
- ...(await this.workflowAgentConversationService.openConversation({
- runInfo,
- stepId: currentStepId,
- title: step.name,
- recipientWorkspaceMemberId: isNonEmptyString(
- recipientWorkspaceMemberId,
- )
- ? recipientWorkspaceMemberId
- : null,
- threadKey: resolveConversationThreadKey({
- conversation,
- defaultScope: 'STEP',
- workflowRunId: runInfo.workflowRunId,
- stepExecutionKey: buildStepExecutionKey({
- stepId: currentStepId,
- steps,
- context,
- }),
+ const conversation = isDefined(resumedThreadId)
+ ? { threadId: resumedThreadId, isCreated: false }
+ : await this.workflowAgentConversationService.openConversation({
+ runInfo,
+ stepId: currentStepId,
+ title: step.name,
+ recipientWorkspaceMemberId: isNonEmptyString(
+ recipientWorkspaceMemberId,
+ )
+ ? recipientWorkspaceMemberId
+ : null,
+ threadKey: resolveConversationThreadKey({
+ conversation: conversationSettings,
+ defaultScope: 'STEP',
+ workflowRunId: runInfo.workflowRunId,
+ stepExecutionKey: buildStepExecutionKey({
+ stepId: currentStepId,
+ steps,
+ context,
}),
- })),
- isResumed: false,
- };
-
- // A record of the step, not its outcome, so a write failure must not fail the step
- const recordConversation = async <TResult>(
- record: () => Promise<TResult>,
- ): Promise<TResult | null> => {
- try {
- return await record();
- } catch (error) {
- this.logger.warn(
- `Failed to record the conversation for workflowRun=${runInfo.workflowRunId} step=${currentStepId}: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
-
- return null;
- }
- };
-
- const turnId = await recordConversation(() =>
- this.workflowAgentConversationService.openTurn({
- runInfo,
- threadId: conversationThread.threadId,
- agentId: agent?.id ?? null,
- prompt: conversationThread.isResumed ? null : resolvedPrompt,
- initiatorUserWorkspaceId: userWorkspaceId,
- }),
- );
+ }),
+ });
const trimmedHumanInputInstructions = humanInputInstructions?.trim();
const canAskForHumanInput = isNonEmptyString(trimmedHumanInputInstructions);
- const startedAtMs = Date.now();
-
- let executionResult: AgentExecutionResult;
+ // a resumed run continues from its answer, which is already the last message
+ const messages =
+ isDefined(resumedThreadId) || !isDefined(resolvedPrompt)
+ ? []
+ : [{ role: 'user' as const, content: resolvedPrompt }];
- try {
- executionResult = await this.aiAgentExecutionService.executeAgent({
+ const { outcome, summary } = await this.agentRunnerService.run({
+ workspaceId,
+ conversation,
+ caller: buildWorkflowStepCaller({
+ workflowRunId: runInfo.workflowRunId,
+ stepId: currentStepId,
+ }),
+ turn: {
+ title: step.name,
+ senderUserWorkspaceId: userWorkspaceId,
+ senderApplicationId: null,
+ messages,
+ resolveCreatedBy: () =>
+ this.workflowAgentConversationService.findTurnCreatedBy(runInfo),
+ },
+ execution: {
agent,
- messages: conversationThread.isResumed
- ? []
- : [{ role: 'user', content: resolvedPrompt }],
- priorMessages: conversationThread.priorMessages,
+ messages,
baseSystemPrompt: canAskForHumanInput
? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}\n\n${WORKFLOW_AGENT_HUMAN_INPUT_PROMPT}\n\n${trimmedHumanInputInstructions}`
: `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}`,
@@ -257,74 +230,41 @@ export class AiAgentWorkflowAction implements WorkflowAction {
APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES,
}
: {}),
- });
- } catch (error) {
- if (isDefined(turnId)) {
- await recordConversation(() =>
- this.workflowAgentConversationService.failTurn({
- workspaceId,
- turnId,
- error,
- }),
- );
- }
-
- throw error;
- }
-
- const durationMs = Date.now() - startedAtMs;
-
- const recordedConversation = isDefined(turnId)
- ? await recordConversation(() =>
- this.workflowAgentConversationService.closeTurn({
- workspaceId,
- threadId: conversationThread.threadId,
- turnId,
- workflowStep,
- title: step.name,
- agentId: agent?.id ?? null,
- executionResult,
- }),
- )
- : null;
+ },
+ });
await this.persistStepLog({
workflowRunId: runInfo.workflowRunId,
workspaceId,
stepId: currentStepId,
- executionResult,
- durationMs,
+ summary,
previousStepLog,
});
- if (executionResult.hasNoMoreAvailableCredits) {
- return {
- error: 'Agent stopped: no more available credits.',
- };
- }
-
- if (executionResult.isPaused) {
- if (recordedConversation?.isAwaitingAnswer) {
+ switch (outcome.status) {
+ case 'NO_CREDITS':
+ return {
+ error: 'Agent stopped: no more available credits.',
+ };
+ case 'AWAITING_ANSWER':
return { wait: { type: 'ANSWER' } };
- }
+ case 'PAUSED': {
+ const wait = findAgentStepWait(outcome.pausedToolResults);
- const wait = findAgentStepWait(executionResult.steps);
+ // Resuming continues the conversation, so without it the run would wait forever
+ if (isDefined(wait) && outcome.isResumable) {
+ return { wait };
+ }
- // Resuming continues the conversation, so without it the run would wait forever
- if (isDefined(wait) && isDefined(recordedConversation)) {
- return { wait };
+ return {
+ error: isDefined(wait)
+ ? 'Agent paused to wait but its conversation could not be recorded.'
+ : 'Agent asked a question that could not be recorded.',
+ };
}
-
- return {
- error: isDefined(wait)
- ? 'Agent paused to wait but its conversation could not be recorded.'
- : 'Agent asked a question that could not be recorded.',
- };
+ case 'COMPLETED':
+ return { result: outcome.result };
}
-
- return {
- result: executionResult.result,
- };
}
async resolveWait({
@@ -342,13 +282,14 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
- await this.workflowAgentConversationService.recordWaitOutcome({
+ await this.agentCallerConversationService.recordWaitOutcome({
workspaceId: runInfo.workspaceId,
threadId,
- workflowStep: {
+ caller: buildWorkflowStepCaller({
workflowRunId: runInfo.workflowRunId,
stepId: step.id,
- },
+ }),
+ toolNames: WORKFLOW_AGENT_WAIT_TOOL_NAMES,
toolOutput: buildWaitOutcomeToolOutput(outcome),
});
@@ -359,18 +300,16 @@ export class AiAgentWorkflowAction implements WorkflowAction {
workflowRunId,
workspaceId,
stepId,
- executionResult,
- durationMs,
+ summary,
previousStepLog,
}: {
workflowRunId: string;
workspaceId: string;
stepId: string;
- executionResult: AgentExecutionResult;
- durationMs: number;
+ summary: AgentRunSummary;
previousStepLog?: WorkflowRunStepLog;
}): Promise<void> {
- const stepLog = buildAiAgentStepLog({ executionResult, durationMs });
+ const stepLog = buildAiAgentStepLog(summary);
try {
await this.workflowRunStepLogService.setStepLog({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
index b54f89569bb..5aec8b8c8d4 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
@@ -1,7 +1,5 @@
-import {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
+import { FieldActorSource } from 'twenty-shared/types';
+
import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
const RUN_INFO = { workspaceId: 'workspace-id', workflowRunId: 'run-id' };
@@ -10,7 +8,6 @@ const SENDER = {
workflowId: 'workflow-id',
workflowName: 'New deals',
};
-const PRIOR_MESSAGES = [{ id: 'message-id', role: 'assistant', parts: [] }];
const OPEN_ARGS = {
runInfo: RUN_INFO,
@@ -19,196 +16,104 @@ const OPEN_ARGS = {
threadKey: 'run-id:step-id',
};
-const buildService = ({
- creatorWorkspaceMemberId = 'creator-id' as string | null,
- isCreated = true,
-} = {}) => {
- const messagePartRepository = { update: jest.fn() };
- const messageRepository = { find: jest.fn().mockResolvedValue([]) };
- const agentInboxService = {
- openThread: jest.fn().mockImplementation(({ workspaceMemberId }) =>
- Promise.resolve({
- thread: { id: `thread-for-${workspaceMemberId ?? 'nobody'}` },
- isCreated,
- }),
- ),
- };
- const conversationReaderService = {
- loadMessages: jest.fn().mockResolvedValue(PRIOR_MESSAGES),
+const buildService = () => {
+ const agentCallerConversationService = {
+ openConversation: jest.fn().mockResolvedValue({
+ status: 'OPENED',
+ threadId: 'thread-id',
+ isCreated: true,
+ }),
};
const workflowRunWorkspaceService = {
setStepThreadId: jest.fn().mockResolvedValue(undefined),
};
const workflowRunRecordShareService = {
- findCreatorWorkspaceMemberId: jest
- .fn()
- .mockResolvedValue(creatorWorkspaceMemberId),
+ findCreatorWorkspaceMemberId: jest.fn().mockResolvedValue('creator-id'),
};
const service = new WorkflowAgentConversationWorkspaceService(
- messageRepository as never,
- messagePartRepository as never,
- agentInboxService as never,
- conversationReaderService as never,
- {} as never,
- {} as never,
+ agentCallerConversationService as never,
{
findRunSenderOrThrow: jest.fn().mockResolvedValue(SENDER),
} as never,
workflowRunWorkspaceService as never,
workflowRunRecordShareService as never,
- {} as never,
);
return {
service,
- agentInboxService,
- conversationReaderService,
- messageRepository,
- messagePartRepository,
+ agentCallerConversationService,
workflowRunWorkspaceService,
+ workflowRunRecordShareService,
};
};
describe('WorkflowAgentConversationWorkspaceService', () => {
describe('openConversation', () => {
- it('opens the conversation with the recipient the step names, filed under done', async () => {
- const { service, agentInboxService, workflowRunWorkspaceService } =
- buildService();
+ it('opens the conversation with the recipient the step names and points the step at it', async () => {
+ const {
+ service,
+ agentCallerConversationService,
+ workflowRunWorkspaceService,
+ workflowRunRecordShareService,
+ } = buildService();
- const conversation = await service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: 'recipient-id',
- });
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({ threadId: 'thread-id', isCreated: true });
- expect(conversation).toEqual({
- threadId: 'thread-for-recipient-id',
- priorMessages: [],
- });
- expect(agentInboxService.openThread).toHaveBeenCalledWith({
+ expect(
+ agentCallerConversationService.openConversation,
+ ).toHaveBeenCalledWith({
workspaceId: 'workspace-id',
sender: SENDER,
- workspaceMemberId: 'recipient-id',
- threadKey: 'run-id:step-id',
title: 'Draft the quote',
- isArchivedOnCreate: true,
+ threadKey: 'run-id:step-id',
+ fallbackThreadKey: 'run-id:step-id:run-id:step-id',
+ recipientWorkspaceMemberId: 'recipient-id',
+ fallbackRecipientWorkspaceMemberId: null,
});
+ expect(
+ workflowRunRecordShareService.findCreatorWorkspaceMemberId,
+ ).not.toHaveBeenCalled();
expect(workflowRunWorkspaceService.setStepThreadId).toHaveBeenCalledWith({
stepId: 'step-id',
- threadId: 'thread-for-recipient-id',
+ threadId: 'thread-id',
workflowRunId: 'run-id',
workspaceId: 'workspace-id',
});
});
it("falls back to the workflow creator's inbox when the step names no recipient", async () => {
- const { service } = buildService();
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: null,
- }),
- ).resolves.toMatchObject({ threadId: 'thread-for-creator-id' });
- });
-
- it('keeps a conversation no inbox receives when the creator cannot have it', async () => {
- const { service, agentInboxService } = buildService();
-
- agentInboxService.openThread.mockRejectedValueOnce(
- new AiException(
- 'Thread owner is no longer a workspace member',
- AiExceptionCode.THREAD_NOT_FOUND,
- ),
- );
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: null,
- }),
- ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
- });
-
- it('keeps a conversation no inbox receives for a workflow without a member creator', async () => {
- const { service } = buildService({ creatorWorkspaceMemberId: null });
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: null,
- }),
- ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
- });
-
- it('fails when the named recipient cannot have the conversation', async () => {
- const { service, agentInboxService } = buildService();
-
- agentInboxService.openThread.mockRejectedValueOnce(
- new AiException(
- 'Thread owner is no longer a workspace member',
- AiExceptionCode.THREAD_NOT_FOUND,
- ),
- );
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: 'recipient-id',
- }),
- ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_NOT_FOUND });
- });
+ const { service, agentCallerConversationService } = buildService();
- it('starts its own conversation when the recipient deleted the one its key names', async () => {
- const { service, agentInboxService } = buildService();
-
- agentInboxService.openThread.mockResolvedValueOnce({
- thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
- isCreated: false,
+ await service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
});
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: 'recipient-id',
+ expect(
+ agentCallerConversationService.openConversation,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ recipientWorkspaceMemberId: null,
+ fallbackRecipientWorkspaceMemberId: 'creator-id',
}),
- ).resolves.toEqual({
- threadId: 'thread-for-recipient-id',
- priorMessages: [],
- });
- expect(agentInboxService.openThread).toHaveBeenLastCalledWith(
- expect.objectContaining({ threadKey: 'run-id:step-id:run-id:step-id' }),
);
});
- it('starts its own conversation while the one its key names waits on another answer', async () => {
- const { service, agentInboxService } = buildService();
-
- agentInboxService.openThread.mockResolvedValueOnce({
- thread: {
- id: 'waiting-thread-id',
- pendingQuestionMessageId: 'question-message-id',
- },
- isCreated: false,
- });
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: 'recipient-id',
- }),
- ).resolves.toEqual({
- threadId: 'thread-for-recipient-id',
- priorMessages: [],
- });
- });
-
- it('fails when the recipient also deleted the conversation this execution started', async () => {
- const { service, agentInboxService } = buildService();
+ it('fails when the recipient deleted the conversation', async () => {
+ const {
+ service,
+ agentCallerConversationService,
+ workflowRunWorkspaceService,
+ } = buildService();
- agentInboxService.openThread.mockResolvedValue({
- thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
- isCreated: false,
+ agentCallerConversationService.openConversation.mockResolvedValue({
+ status: 'DELETED',
});
await expect(
@@ -217,103 +122,22 @@ describe('WorkflowAgentConversationWorkspaceService', () => {
recipientWorkspaceMemberId: 'recipient-id',
}),
).rejects.toThrow('The recipient deleted this conversation');
- });
-
- it('continues from what an existing conversation holds', async () => {
- const { service, conversationReaderService } = buildService({
- isCreated: false,
- });
-
- await expect(
- service.openConversation({
- ...OPEN_ARGS,
- recipientWorkspaceMemberId: 'recipient-id',
- }),
- ).resolves.toEqual({
- threadId: 'thread-for-recipient-id',
- priorMessages: PRIOR_MESSAGES,
- });
- expect(conversationReaderService.loadMessages).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- threadId: 'thread-for-recipient-id',
- });
+ expect(
+ workflowRunWorkspaceService.setStepThreadId,
+ ).not.toHaveBeenCalled();
});
});
- describe('recordWaitOutcome', () => {
- const waitPart = (id: string, workflowStep: Record<string, string>) => ({
- id,
- toolName: 'wait_for_duration',
- toolOutput: { result: { status: 'pending' }, workflowStep },
- });
-
- it("settles the step's own wait, not another run's waiting in the same conversation", async () => {
- const { service, messageRepository, messagePartRepository } =
- buildService();
-
- messageRepository.find.mockResolvedValue([
- {
- parts: [
- waitPart('other-run-part', {
- workflowRunId: 'other-run-id',
- stepId: 'step-id',
- }),
- ],
- },
- {
- parts: [
- waitPart('other-step-part', {
- workflowRunId: 'run-id',
- stepId: 'other-step-id',
- }),
- ],
- },
- {
- parts: [
- waitPart('own-part', {
- workflowRunId: 'run-id',
- stepId: 'step-id',
- }),
- ],
- },
- ]);
+ describe('findTurnCreatedBy', () => {
+ it('attributes turns to the workflow', async () => {
+ const { service } = buildService();
- await service.recordWaitOutcome({
- workspaceId: 'workspace-id',
- threadId: 'thread-id',
- workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
- toolOutput: { success: true },
+ await expect(service.findTurnCreatedBy(RUN_INFO)).resolves.toEqual({
+ source: FieldActorSource.WORKFLOW,
+ name: 'New deals',
+ workspaceMemberId: null,
+ context: {},
});
-
- expect(messagePartRepository.update).toHaveBeenCalledWith(
- 'workspace-id',
- { id: 'own-part' },
- { toolOutput: { success: true } },
- );
- });
-
- it('refuses to settle a wait the step never posted', async () => {
- const { service, messageRepository } = buildService();
-
- messageRepository.find.mockResolvedValue([
- {
- parts: [
- waitPart('other-run-part', {
- workflowRunId: 'other-run-id',
- stepId: 'step-id',
- }),
- ],
- },
- ]);
-
- await expect(
- service.recordWaitOutcome({
- workspaceId: 'workspace-id',
- threadId: 'thread-id',
- workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
- toolOutput: { success: true },
- }),
- ).rejects.toMatchObject({ code: AiExceptionCode.TOOL_CALL_NOT_FOUND });
});
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index 5f390d6ff7d..af1caca237f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -1,75 +1,28 @@
-import { Injectable, Logger } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
-import { type ExtendedUIMessage } from 'twenty-shared/ai';
-import { FieldActorSource } from 'twenty-shared/types';
+import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
-import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-history/utils/is-awaiting-pausing-tool-output.util';
-import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
-import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
-import { type ToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-history/types/tool-call-workflow-step.type';
-import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
-import { readToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-workflow-step.util';
-import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
-import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
-import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
-import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
-import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
-import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
-import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
-import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
-import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
-import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
-import {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
+import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
-import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-const RECENT_MESSAGES_TO_SEARCH_FOR_WAIT = 50;
-
-export type OpenedConversation = {
- threadId: string;
- // what the conversation held before this execution, which the agent continues from
- priorMessages: ExtendedUIMessage[];
-};
-
-export type RecordedConversation = {
- threadId: string;
- isAwaitingAnswer: boolean;
-};
-
-// Every execution records its conversation through the inbox, with the step's
-// recipient or else the workflow's creator. A conversation the execution opens is
-// filed under done, and only comes back to the inbox when the agent needs them.
+// A step's conversation goes to the step's recipient or else the workflow's
+// creator, and the step points at it as soon as it is open
@Injectable()
export class WorkflowAgentConversationWorkspaceService {
- private readonly logger = new Logger(
- WorkflowAgentConversationWorkspaceService.name,
- );
-
constructor(
- @InjectAgentHistoryRepository('agentMessage')
- private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
- private readonly agentInboxService: AgentInboxService,
- private readonly conversationReaderService: AgentConversationReaderService,
- private readonly conversationWriterService: AgentConversationWriterService,
- private readonly threadService: AgentChatThreadService,
+ private readonly agentCallerConversationService: AgentCallerConversationService,
private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
- private readonly turnRecorderService: AgentTurnRecorderService,
) {}
async openConversation({
@@ -84,42 +37,34 @@ export class WorkflowAgentConversationWorkspaceService {
title: string;
recipientWorkspaceMemberId: string | null;
threadKey: string;
- }): Promise<OpenedConversation> {
+ }): Promise<AgentRunConversation> {
const { workspaceId, workflowRunId } = runInfo;
const sender =
await this.workflowRunInboxSenderService.findRunSenderOrThrow(runInfo);
- const openThreadUnderKey = (key: string) => {
- const openThread = (workspaceMemberId: string | null) =>
- this.agentInboxService.openThread({
+
+ // a workflow without a member creator, such as one an application installs, keeps a
+ // conversation no inbox receives
+ const fallbackRecipientWorkspaceMemberId = isDefined(
+ recipientWorkspaceMemberId,
+ )
+ ? null
+ : await this.workflowRunRecordShareService.findCreatorWorkspaceMemberId({
workspaceId,
- sender,
- workspaceMemberId,
- threadKey: key,
- title,
- isArchivedOnCreate: true,
+ coreWorkflowId: sender.workflowId,
});
- return isDefined(recipientWorkspaceMemberId)
- ? openThread(recipientWorkspaceMemberId)
- : this.openThreadWithCreator({
- workspaceId,
- coreWorkflowId: sender.workflowId,
- openThread,
- });
- };
-
- const keyedConversation = await openThreadUnderKey(threadKey);
-
- // a conversation the recipient deleted is not written to again, and one already waiting on an answer
- // has no room for another question, so this execution starts its own
- const isKeyedConversationUnavailable =
- isDefined(keyedConversation.thread.deletedAt) ||
- isDefined(keyedConversation.thread.pendingQuestionMessageId);
- const { thread, isCreated } = isKeyedConversationUnavailable
- ? await openThreadUnderKey(`${threadKey}:${workflowRunId}:${stepId}`)
- : keyedConversation;
+ const openedConversation =
+ await this.agentCallerConversationService.openConversation({
+ workspaceId,
+ sender,
+ title,
+ threadKey,
+ fallbackThreadKey: `${threadKey}:${workflowRunId}:${stepId}`,
+ recipientWorkspaceMemberId,
+ fallbackRecipientWorkspaceMemberId,
+ });
- if (isDefined(thread.deletedAt)) {
+ if (openedConversation.status === 'DELETED') {
throw new WorkflowStepExecutorException(
'The recipient deleted this conversation',
WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
@@ -128,274 +73,26 @@ export class WorkflowAgentConversationWorkspaceService {
await this.workflowRunWorkspaceService.setStepThreadId({
stepId,
- threadId: thread.id,
+ threadId: openedConversation.threadId,
workflowRunId,
workspaceId,
});
return {
- threadId: thread.id,
- priorMessages: isCreated
- ? []
- : await this.conversationReaderService.loadMessages({
- workspaceId,
- threadId: thread.id,
- }),
+ threadId: openedConversation.threadId,
+ isCreated: openedConversation.isCreated,
};
}
- // The turn is written before the agent runs, so a run in progress or one that
- // fails is on record. A resumed step adds no prompt: the answer is already the
- // last message
- async openTurn({
- runInfo,
- threadId,
- agentId,
- prompt,
- initiatorUserWorkspaceId,
- }: {
- runInfo: WorkflowRunInfo;
- threadId: string;
- agentId: string | null;
- prompt: string | null;
- initiatorUserWorkspaceId: string | null;
- }): Promise<string> {
- const { workspaceId } = runInfo;
+ async findTurnCreatedBy(runInfo: WorkflowRunInfo): Promise<ActorMetadata> {
const sender =
await this.workflowRunInboxSenderService.findRunSenderOrThrow(runInfo);
- return this.conversationWriterService.runInTransaction(
- workspaceId,
- async (scope) => {
- const turnId = await this.conversationWriterService.insertTurn({
- workspaceId,
- threadId,
- agentId,
- status: AgentTurnStatus.RUNNING,
- createdBy: {
- source: FieldActorSource.WORKFLOW,
- name: sender.workflowName,
- workspaceMemberId: null,
- context: {},
- },
- scope,
- });
-
- if (isDefined(prompt)) {
- await this.conversationWriterService.insertMessage({
- workspaceId,
- threadId,
- turnId,
- role: AgentMessageRole.USER,
- agentId: null,
- senderUserWorkspaceId: initiatorUserWorkspaceId,
- parts: [{ type: 'text', text: prompt }],
- scope,
- });
- }
-
- return turnId;
- },
- );
- }
-
- async closeTurn({
- workspaceId,
- threadId,
- turnId,
- workflowStep,
- title,
- agentId,
- executionResult,
- }: {
- workspaceId: string;
- threadId: string;
- turnId: string;
- workflowStep: ToolCallWorkflowStep;
- title: string;
- agentId: string | null;
- executionResult: RecordableAgentExecution;
- }): Promise<RecordedConversation> {
- const turn = { workspaceId, threadId, turnId, execution: executionResult };
-
- const isAwaitingAnswer = await this.recordReply({
- workspaceId,
- threadId,
- turnId,
- workflowStep,
- title,
- agentId,
- executionResult,
- }).catch(async (error: unknown) => {
- await this.turnRecorderService.finishExecutedTurn({
- ...turn,
- error: mapErrorToStreamError(error),
- });
-
- throw error;
- });
-
- await this.turnRecorderService.finishExecutedTurn({
- ...turn,
- isAwaitingAnswer,
- });
-
- return { threadId, isAwaitingAnswer };
- }
-
- async failTurn({
- workspaceId,
- turnId,
- error,
- }: {
- workspaceId: string;
- turnId: string;
- error: unknown;
- }): Promise<void> {
- await this.turnRecorderService.finish({
- workspaceId,
- turnId,
- status: AgentTurnStatus.FAILED,
- error: mapErrorToStreamError(error),
- });
- }
-
- // The wait call stays pending in the conversation until its wait resolves, then carries the outcome
- async recordWaitOutcome({
- workspaceId,
- threadId,
- workflowStep,
- toolOutput,
- }: {
- workspaceId: string;
- threadId: string;
- workflowStep: ToolCallWorkflowStep;
- toolOutput: Record<string, unknown>;
- }): Promise<void> {
- // messages can follow the call while it waits, so the latest one may not carry it
- const recentMessages = await this.messageRepository.find(workspaceId, {
- where: { threadId },
- order: { createdAt: 'DESC' },
- take: RECENT_MESSAGES_TO_SEARCH_FOR_WAIT,
- relations: ['parts'],
- });
-
- const waitPart = recentMessages
- .flatMap((message) => message.parts ?? [])
- .find((part) => {
- const partWorkflowStep = readToolCallWorkflowStep(part.toolOutput);
-
- return (
- isDefined(part.toolName) &&
- WORKFLOW_AGENT_WAIT_TOOL_NAMES.includes(part.toolName) &&
- isAwaitingPausingToolOutput(part.toolOutput) &&
- partWorkflowStep?.workflowRunId === workflowStep.workflowRunId &&
- partWorkflowStep.stepId === workflowStep.stepId
- );
- });
-
- if (!isDefined(waitPart)) {
- throw new AiException(
- 'The waiting call could not be found in the conversation',
- AiExceptionCode.TOOL_CALL_NOT_FOUND,
- );
- }
-
- await this.messagePartRepository.update(
- workspaceId,
- { id: waitPart.id },
- { toolOutput },
- );
- }
-
- // a workflow without a member creator, such as one an application installs, or whose
- // creator cannot use AI, keeps a conversation no inbox receives
- private async openThreadWithCreator({
- workspaceId,
- coreWorkflowId,
- openThread,
- }: {
- workspaceId: string;
- coreWorkflowId: string;
- openThread: (
- workspaceMemberId: string | null,
- ) => ReturnType<AgentInboxService['openThread']>;
- }): ReturnType<AgentInboxService['openThread']> {
- const creatorWorkspaceMemberId =
- await this.workflowRunRecordShareService.findCreatorWorkspaceMemberId({
- workspaceId,
- coreWorkflowId,
- });
-
- if (!isDefined(creatorWorkspaceMemberId)) {
- return openThread(null);
- }
-
- try {
- return await openThread(creatorWorkspaceMemberId);
- } catch (error) {
- if (
- error instanceof AiException &&
- error.code === AiExceptionCode.THREAD_NOT_FOUND
- ) {
- return openThread(null);
- }
-
- throw error;
- }
- }
-
- private async recordReply({
- workspaceId,
- threadId,
- turnId,
- workflowStep,
- title,
- agentId,
- executionResult,
- }: {
- workspaceId: string;
- threadId: string;
- turnId: string;
- workflowStep: ToolCallWorkflowStep;
- title: string;
- agentId: string | null;
- executionResult: RecordableAgentExecution;
- }): Promise<boolean> {
- const { isAwaitingAnswer, replyParts } =
- await this.conversationWriterService.insertExecutionReply({
- workspaceId,
- threadId,
- turnId,
- agentId,
- execution: executionResult,
- workflowStep,
- });
-
- if (isAwaitingAnswer) {
- await this.recordWaitingActivity({
- workspaceId,
- threadId,
- text: findLastMessageText(replyParts) ?? title,
- });
- }
-
- return isAwaitingAnswer;
- }
-
- // the waiting call is already saved and can be answered from the conversation, so a
- // failure to bring it back to the inbox must not fail the step
- private async recordWaitingActivity(args: {
- workspaceId: string;
- threadId: string;
- text: string;
- }): Promise<void> {
- await this.threadService
- .recordThreadActivity(args)
- .catch((error: unknown) =>
- this.logger.warn(
- `Could not record waiting activity on thread ${args.threadId}: ${error instanceof Error ? error.message : String(error)}`,
- ),
- );
+ return {
+ source: FieldActorSource.WORKFLOW,
+ name: sender.workflowName,
+ workspaceMemberId: null,
+ context: {},
+ };
}
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
index 4c26b4fe61d..51199a4cc4b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
@@ -1,91 +1,30 @@
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';
-jest.mock(
- 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util',
- () => ({
- mapAiStepsToToolCallLogs: jest.fn().mockReturnValue([
- {
- toolName: 'web_search',
- toolCallId: 'call-1',
- state: 'success',
- },
- ]),
- }),
-);
-
-const baseExecutionResult: AgentExecutionResult = {
- result: { answer: 'hello' },
- usage: {
- inputTokens: 100,
- outputTokens: 50,
- totalTokens: 150,
- inputTokenDetails: { cacheReadTokens: 20 },
- outputTokenDetails: { reasoningTokens: 10 },
- } as AgentExecutionResult['usage'],
- cacheCreationTokens: 5,
- nativeWebSearchCallCount: 2,
- hasNoMoreAvailableCredits: false,
- isPaused: false,
+const SUMMARY: AgentRunSummary = {
modelId: 'claude-sonnet-4',
- totalCostInDollars: 0.012,
- creditsUsedMicro: 12_000,
- turnUsage: {
+ usage: {
inputTokens: 100,
outputTokens: 50,
+ reasoningTokens: 10,
cacheReadTokens: 20,
cacheCreationTokens: 5,
- inputCredits: 0,
- outputCredits: 0,
+ totalTokens: 150,
},
- steps: [],
+ cost: { totalCostInDollars: 0.012, creditsUsedMicro: 12_000 },
+ nativeWebSearchCallCount: 2,
+ toolCalls: [
+ { toolName: 'web_search', toolCallId: 'call-1', state: 'success' },
+ ],
+ durationMs: 1234,
};
describe('buildAiAgentStepLog', () => {
- it('builds an AI_AGENT step log with usage, cost, and tool calls', () => {
- const stepLog = buildAiAgentStepLog({
- executionResult: baseExecutionResult,
- durationMs: 1234,
+ it('logs the run summary as the AI_AGENT step details', () => {
+ expect(buildAiAgentStepLog(SUMMARY)).toEqual({
+ details: { type: 'AI_AGENT', ...SUMMARY },
+ entries: [],
+ sizeBytes: 0,
});
-
- if (stepLog.details.type !== 'AI_AGENT') {
- throw new Error('Expected AI_AGENT details');
- }
-
- expect(stepLog.details.modelId).toBe('claude-sonnet-4');
- expect(stepLog.details.durationMs).toBe(1234);
- expect(stepLog.details.usage).toEqual({
- inputTokens: 100,
- outputTokens: 50,
- reasoningTokens: 10,
- cacheReadTokens: 20,
- cacheCreationTokens: 5,
- totalTokens: 150,
- });
- expect(stepLog.details.cost).toEqual({
- totalCostInDollars: 0.012,
- creditsUsedMicro: 12_000,
- });
- expect(stepLog.details.nativeWebSearchCallCount).toBe(2);
- expect(stepLog.details.toolCalls).toHaveLength(1);
- expect(stepLog.entries).toEqual([]);
- });
-
- it('falls back to zero tokens when the provider did not report usage', () => {
- const stepLog = buildAiAgentStepLog({
- executionResult: {
- ...baseExecutionResult,
- usage: {} as AgentExecutionResult['usage'],
- },
- durationMs: 100,
- });
-
- if (stepLog.details.type !== 'AI_AGENT') {
- throw new Error('Expected AI_AGENT details');
- }
-
- expect(stepLog.details.usage.inputTokens).toBe(0);
- expect(stepLog.details.usage.outputTokens).toBe(0);
- expect(stepLog.details.usage.totalTokens).toBe(0);
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts
index e7c9c110f92..1c6fe497b87 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts
@@ -2,41 +2,39 @@ import { findAgentStepWait } from 'src/modules/workflow/workflow-executor/workfl
const WAIT = { type: 'EVENT', eventName: 'company.updated' };
-const stepWithResults = (
- ...toolResults: { toolName: string; output: unknown }[]
-) => ({ toolResults });
-
describe('findAgentStepWait', () => {
- it('finds the wait an execution ended on', () => {
+ it('finds the wait a run paused on', () => {
expect(
findAgentStepWait([
- stepWithResults({
+ {
toolName: 'wait_for_event',
output: { success: true, result: { status: 'pending', wait: WAIT } },
- }),
+ },
]),
).toEqual(WAIT);
});
- it('ignores a wait call made in an earlier step', () => {
+ it('ignores pending calls of tools that are not waits', () => {
expect(
findAgentStepWait([
- stepWithResults({
- toolName: 'wait_for_event',
+ {
+ toolName: 'ask_question',
output: { success: true, result: { status: 'pending', wait: WAIT } },
- }),
- stepWithResults({ toolName: 'search', output: {} }),
+ },
]),
).toBeUndefined();
});
- it('ignores pending calls of tools that are not waits', () => {
+ it('ignores a wait call that no longer waits', () => {
expect(
findAgentStepWait([
- stepWithResults({
- toolName: 'ask_question',
- output: { success: true, result: { status: 'pending', wait: WAIT } },
- }),
+ {
+ toolName: 'wait_for_event',
+ output: {
+ success: true,
+ result: { status: 'completed', wait: WAIT },
+ },
+ },
]),
).toBeUndefined();
});
@@ -44,10 +42,10 @@ describe('findAgentStepWait', () => {
it('ignores a wait call whose wait cannot be read', () => {
expect(
findAgentStepWait([
- stepWithResults({
+ {
toolName: 'wait_for_duration',
output: { success: true, result: { status: 'pending' } },
- }),
+ },
]),
).toBeUndefined();
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
index dbff0a239e3..066338cebe4 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
@@ -1,42 +1,11 @@
-import {
- type AiAgentStepLogDetails,
- type WorkflowRunStepLog,
-} from 'twenty-shared/workflow';
+import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
-import { mapAiStepsToToolCallLogs } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/map-ai-steps-to-tool-call-logs.util';
+import { type AgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-summary.type';
-export const buildAiAgentStepLog = ({
- executionResult,
- durationMs,
-}: {
- executionResult: AgentExecutionResult;
- durationMs: number;
-}): WorkflowRunStepLog => {
- const details: AiAgentStepLogDetails = {
- type: 'AI_AGENT',
- modelId: executionResult.modelId,
- usage: {
- inputTokens: executionResult.usage.inputTokens ?? 0,
- outputTokens: executionResult.usage.outputTokens ?? 0,
- reasoningTokens:
- executionResult.usage.outputTokenDetails?.reasoningTokens,
- cacheReadTokens: executionResult.usage.inputTokenDetails?.cacheReadTokens,
- cacheCreationTokens: executionResult.cacheCreationTokens,
- totalTokens: executionResult.usage.totalTokens ?? 0,
- },
- cost: {
- totalCostInDollars: executionResult.totalCostInDollars,
- creditsUsedMicro: executionResult.creditsUsedMicro,
- },
- nativeWebSearchCallCount: executionResult.nativeWebSearchCallCount,
- toolCalls: mapAiStepsToToolCallLogs(executionResult.steps),
- durationMs,
- };
-
- return {
- details,
- entries: [],
- sizeBytes: 0,
- };
-};
+export const buildAiAgentStepLog = (
+ summary: AgentRunSummary,
+): WorkflowRunStepLog => ({
+ details: { type: 'AI_AGENT', ...summary },
+ entries: [],
+ sizeBytes: 0,
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts
index 316c3d4a820..ffd540398ab 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts
@@ -4,16 +4,15 @@ import {
workflowStepWaitSchema,
} from 'twenty-shared/workflow';
+import { type AgentRunPausedToolResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-paused-tool-result.type';
import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-history/utils/is-awaiting-pausing-tool-output.util';
import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
-// The wait an execution paused on, when it ended on a wait tool call
+// The wait a run paused on, when it paused on a wait tool call
export const findAgentStepWait = (
- steps: { toolResults: { toolName: string; output: unknown }[] }[],
+ pausedToolResults: AgentRunPausedToolResult[],
): WorkflowStepWait | undefined => {
- const lastStepToolResults = steps[steps.length - 1]?.toolResults ?? [];
-
- for (const { toolName, output } of lastStepToolResults) {
+ for (const { toolName, output } of pausedToolResults) {
if (
!WORKFLOW_AGENT_WAIT_TOOL_NAMES.includes(toolName) ||
!isAwaitingPausingToolOutput(output) ||
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
index f15a32b021e..972d4707c3f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
@@ -1,21 +1,17 @@
import { Module } from '@nestjs/common';
import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
-import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
-import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
-import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
import { WorkflowRunInboxSenderModule } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module';
import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@Module({
imports: [
- AgentChatThreadModule,
- AgentHistoryModule,
+ AiAgentExecutionModule,
WorkflowRunInboxSenderModule,
WorkflowRunModule,
WorkflowRunRecordShareModule,
- WorkspaceCacheModule,
],
providers: [WorkflowAgentConversationWorkspaceService],
exports: [WorkflowAgentConversationWorkspaceService],
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
index 87588c6f80c..7ab876cffc4 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
@@ -1,18 +1,8 @@
import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
-import { IsNull } from 'typeorm';
-import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-const QUESTIONS = [
- {
- header: 'Plan',
- question: 'Which plan?',
- options: [{ label: 'Pro' }, { label: 'Team' }],
- },
-];
-
describe('WorkflowRunWorkspaceService conversations', () => {
const buildService = ({
status = WorkflowRunStatus.RUNNING,
@@ -21,57 +11,17 @@ describe('WorkflowRunWorkspaceService conversations', () => {
threadId: 'thread-id',
} as Record<string, unknown>,
} = {}) => {
- const threadRepository = {
- find: jest
- .fn()
- .mockResolvedValue([
- { id: 'thread-id', pendingQuestionMessageId: 'message-id' },
- ]),
- update: jest.fn().mockResolvedValue({ affected: 1 }),
- };
- const messagePartRepository = {
- find: jest.fn().mockResolvedValue([
- {
- id: 'part-id',
- messageId: 'message-id',
- toolName: 'ask_question',
- toolInput: QUESTIONS[0],
- toolOutput: {
- result: { question: QUESTIONS[0], status: 'pending' },
- workflowStep: {
- workflowRunId: 'workflow-run-id',
- stepId: 'step-id',
- },
- },
- },
- ]),
- writePart: jest.fn(),
- query: jest.fn(),
+ const agentCallerConversationService = {
+ cancelAwaitingConversations: jest.fn().mockResolvedValue(undefined),
};
- const turnRecorderService = {
- endWaitingTurn: jest.fn().mockResolvedValue(undefined),
- };
- const threadRecordEventService = {
- emitPendingQuestionCleared: jest.fn().mockResolvedValue(undefined),
- };
-
- messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>
- run({
- table: (name: string) => name,
- manager: { query: messagePartRepository.writePart },
- }),
- );
const service = new WorkflowRunWorkspaceService(
{} as never,
{} as never,
{ incrementCounterForEvent: jest.fn() } as never,
{} as never,
- threadRepository as never,
- messagePartRepository as never,
{ cancelRunWaits: jest.fn().mockResolvedValue(undefined) } as never,
- turnRecorderService as never,
- threadRecordEventService as never,
+ agentCallerConversationService as never,
);
// The run lock serializes these methods with every other step write.
@@ -111,10 +61,7 @@ describe('WorkflowRunWorkspaceService conversations', () => {
service,
step,
workflowRun,
- threadRepository,
- messagePartRepository,
- turnRecorderService,
- threadRecordEventService,
+ agentCallerConversationService,
updateWorkflowRun,
};
};
@@ -295,104 +242,30 @@ describe('WorkflowRunWorkspaceService conversations', () => {
status: WorkflowRunStatus.STOPPED,
});
- it('stops its conversations waiting and closes their calls as skipped', async () => {
- const {
- service,
- threadRepository,
- messagePartRepository,
- turnRecorderService,
- } = buildService();
-
- await endRun(service);
-
- expect(threadRepository.update).toHaveBeenCalledWith(
- 'workspace-id',
- {
- id: 'thread-id',
- pendingQuestionMessageId: 'message-id',
- activeStreamId: IsNull(),
- },
- { pendingQuestionMessageId: null },
- );
- expect(turnRecorderService.endWaitingTurn).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- messageId: 'message-id',
- status: AgentTurnStatus.CANCELLED,
- });
- const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] =
- messagePartRepository.writePart.mock.calls;
-
- expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);
- expect({
- partId,
- result: JSON.parse(closedToolOutput).result,
- expectedStatus,
- }).toEqual({
- partId: 'part-id',
- result: { question: QUESTIONS[0], status: 'skipped' },
- expectedStatus: 'pending',
- });
- });
-
- it('tells open chat lists the conversation no longer waits on an answer', async () => {
- const { service, threadRecordEventService } = buildService();
+ it('closes the calls its conversations wait on', async () => {
+ const { service, agentCallerConversationService } = buildService();
await endRun(service);
expect(
- threadRecordEventService.emitPendingQuestionCleared,
+ agentCallerConversationService.cancelAwaitingConversations,
).toHaveBeenCalledWith({
workspaceId: 'workspace-id',
- threadId: 'thread-id',
- messageId: 'message-id',
- });
- });
-
- it('leaves open a call another run posted in a conversation they share', async () => {
- const { service, threadRepository, messagePartRepository } =
- buildService();
-
- messagePartRepository.find.mockResolvedValue([
- {
- id: 'part-id',
- messageId: 'message-id',
- toolName: 'ask_question',
- toolInput: QUESTIONS[0],
- toolOutput: {
- result: { question: QUESTIONS[0], status: 'pending' },
- workflowStep: { workflowRunId: 'other-run-id', stepId: 'step-id' },
- },
+ threadIds: ['thread-id'],
+ caller: {
+ type: 'WORKFLOW_STEP',
+ ref: { workflowRunId: 'workflow-run-id' },
},
- ]);
-
- await endRun(service);
-
- expect(threadRepository.update).not.toHaveBeenCalled();
- expect(messagePartRepository.writePart).not.toHaveBeenCalled();
- });
-
- it('leaves a conversation to the answer holding its claim', async () => {
- const {
- service,
- threadRepository,
- messagePartRepository,
- threadRecordEventService,
- } = buildService();
-
- threadRepository.update.mockResolvedValue({ affected: 0 });
-
- await endRun(service);
-
- expect(messagePartRepository.writePart).not.toHaveBeenCalled();
- expect(
- threadRecordEventService.emitPendingQuestionCleared,
- ).not.toHaveBeenCalled();
+ });
});
it('still ends the run when its conversations cannot be closed', async () => {
- const { service, threadRepository, updateWorkflowRun } = buildService();
+ const { service, agentCallerConversationService, updateWorkflowRun } =
+ buildService();
- threadRepository.find.mockRejectedValue(new Error('db down'));
+ agentCallerConversationService.cancelAwaitingConversations.mockRejectedValue(
+ new Error('db down'),
+ );
await endRun(service);
@@ -400,13 +273,15 @@ describe('WorkflowRunWorkspaceService conversations', () => {
});
it('leaves conversations alone for a run that never had one', async () => {
- const { service, threadRepository } = buildService({
+ const { service, agentCallerConversationService } = buildService({
stepInfo: { status: StepStatus.SUCCESS },
});
await endRun(service);
- expect(threadRepository.find).not.toHaveBeenCalled();
+ expect(
+ agentCallerConversationService.cancelAwaitingConversations,
+ ).not.toHaveBeenCalled();
});
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
index e4db70590d9..05de962ca37 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
@@ -5,8 +5,7 @@ import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.m
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';
-import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
-import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
+import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { DeleteWorkflowRunsCommand } from 'src/modules/workflow/workflow-runner/workflow-run/command/delete-workflow-runs.command';
@@ -23,8 +22,7 @@ import { WorkflowStepWaitModule } from 'src/modules/workflow/workflow-wait/workf
WorkspaceIteratorModule,
FeatureFlagModule,
WorkflowRunRecordShareModule,
- AgentHistoryModule,
- AgentChatThreadLifecycleModule,
+ AiAgentExecutionModule,
WorkflowStepWaitModule,
],
providers: [
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index c23e7d3bb0c..1f73d1d89d6 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -3,7 +3,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { type ActorMetadata } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';
-import { In, IsNull, Not } from 'typeorm';
import { v4 } from 'uuid';
import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator';
@@ -11,15 +10,10 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
+import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { PermissionsException } from 'src/engine/metadata-modules/permissions/permissions.exception';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
-import { readToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-history/utils/read-tool-call-workflow-step.util';
-import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';
import {
WorkflowRunStatus,
type WorkflowRunState,
@@ -37,9 +31,6 @@ import {
WorkflowRunException,
WorkflowRunExceptionCode,
} from 'src/modules/workflow/workflow-runner/exceptions/workflow-run.exception';
-import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
-import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
-import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
@Injectable()
export class WorkflowRunWorkspaceService {
@@ -50,13 +41,8 @@ export class WorkflowRunWorkspaceService {
private readonly recordPositionService: RecordPositionService,
private readonly metricsService: MetricsService,
private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
- @InjectAgentHistoryRepository('agentChatThread')
- private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
- private readonly turnRecorderService: AgentTurnRecorderService,
- private readonly threadRecordEventService: AgentChatThreadRecordEventService,
+ private readonly agentCallerConversationService: AgentCallerConversationService,
) {}
async createCoreWorkflowRun({
@@ -235,15 +221,17 @@ export class WorkflowRunWorkspaceService {
// An ended run cannot consume answers, so close the calls its conversations wait on.
// Best effort: a failure only leaves a call that looks waiting.
if (stepThreadIds.length > 0) {
- await this.closeWaitingConversations({
- workflowRunId,
- workspaceId,
- stepThreadIds,
- }).catch((error: unknown) => {
- this.logger.error(
- `Failed to close the conversations of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
- );
- });
+ await this.agentCallerConversationService
+ .cancelAwaitingConversations({
+ workspaceId,
+ threadIds: stepThreadIds,
+ caller: { type: 'WORKFLOW_STEP', ref: { workflowRunId } },
+ })
+ .catch((error: unknown) => {
+ this.logger.error(
+ `Failed to close the conversations of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
}
const metricKey =
@@ -750,109 +738,6 @@ export class WorkflowRunWorkspaceService {
}, authContext);
}
- private async closeWaitingConversations({
- workflowRunId,
- workspaceId,
- stepThreadIds,
- }: {
- workflowRunId: string;
- workspaceId: string;
- stepThreadIds: string[];
- }): Promise<void> {
- // An answer holding a conversation's claim closes its calls itself once it finds the run over
- const stepThreads = await this.threadRepository.find(workspaceId, {
- where: {
- id: In(stepThreadIds),
- pendingQuestionMessageId: Not(IsNull()),
- activeStreamId: IsNull(),
- },
- select: ['id', 'pendingQuestionMessageId'],
- });
-
- const waitingThreads = await this.filterThreadsWaitingOnRun({
- threads: stepThreads,
- workflowRunId,
- workspaceId,
- });
-
- for (const { id, pendingQuestionMessageId } of waitingThreads) {
- if (!isDefined(pendingQuestionMessageId)) {
- continue;
- }
-
- const { affected } = await this.threadRepository.update(
- workspaceId,
- { id, pendingQuestionMessageId, activeStreamId: IsNull() },
- { pendingQuestionMessageId: null },
- );
-
- if (affected === 0) {
- continue;
- }
-
- await this.threadRecordEventService.emitPendingQuestionCleared({
- workspaceId,
- threadId: id,
- messageId: pendingQuestionMessageId,
- });
-
- // the question is already cleared, so its calls must close before anything else can fail
- await closeOpenToolParts({
- messagePartRepository: this.messagePartRepository,
- messageId: pendingQuestionMessageId,
- workspaceId,
- });
-
- await this.turnRecorderService.endWaitingTurn({
- workspaceId,
- messageId: pendingQuestionMessageId,
- status: AgentTurnStatus.CANCELLED,
- });
- }
- }
-
- // the member may have moved on to another question in their conversation, which the run must not close
- private async filterThreadsWaitingOnRun<
- TThread extends { pendingQuestionMessageId: string | null },
- >({
- threads,
- workflowRunId,
- workspaceId,
- }: {
- threads: TThread[];
- workflowRunId: string;
- workspaceId: string;
- }): Promise<TThread[]> {
- const pendingMessageIds = threads
- .map((thread) => thread.pendingQuestionMessageId)
- .filter(isDefined);
-
- if (pendingMessageIds.length === 0) {
- return [];
- }
-
- const pendingParts = await this.messagePartRepository.find(workspaceId, {
- where: { messageId: In(pendingMessageIds) },
- select: ['messageId', 'toolOutput'],
- });
-
- const messageIdsWaitingOnRun = new Set(
- pendingParts
- .filter(
- (part) =>
- readToolCallWorkflowStep(part.toolOutput)?.workflowRunId ===
- workflowRunId,
- )
- .map((part) => part.messageId),
- );
-
- return threads.filter(
- (thread) =>
- isDefined(thread.pendingQuestionMessageId) &&
- messageIdsWaitingOnRun.has(thread.pendingQuestionMessageId),
- );
- }
-
private getInitState(
workflowVersion: Pick<WorkflowVersionWorkspaceEntity, 'trigger' | 'steps'>,
triggerPayload: object,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
index f34abfdacd7..25eac120c81 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
@@ -22,6 +22,7 @@ import { type UserWorkspaceService } from 'src/engine/core-modules/user-workspac
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import { type AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { type WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
@@ -824,22 +825,36 @@ describe('core workflow visibility (e2e)', () => {
threadKey: `${workflowRunId}:trigger`,
}));
- const turnId = await conversationService.openTurn({
- runInfo: { workspaceId: SEED_APPLE_WORKSPACE_ID, workflowRunId },
+ const runConversationService =
+ getAppProviderByClassName<AgentRunConversationService>(
+ 'AgentRunConversationService',
+ );
+
+ const turnId = await runConversationService.openTurn({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
threadId,
+ title: 'Summarize the lead',
agentId: null,
- prompt: 'Summarize the lead',
- initiatorUserWorkspaceId: null,
+ senderUserWorkspaceId: null,
+ senderApplicationId: null,
+ messages: [{ role: 'user', content: 'Summarize the lead' }],
+ createdBy: await conversationService.findTurnCreatedBy({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId,
+ }),
});
- await conversationService.closeTurn({
+ await runConversationService.closeTurn({
workspaceId: SEED_APPLE_WORKSPACE_ID,
threadId,
turnId,
- workflowStep: { workflowRunId, stepId: 'trigger' },
+ caller: {
+ type: 'WORKFLOW_STEP',
+ ref: { workflowRunId, stepId: 'trigger' },
+ },
title: 'Summarize the lead',
agentId: null,
- executionResult: {
+ execution: {
steps: [
{ content: [{ type: 'text', text: 'A warm lead.' }] },
] as AgentExecutionResult['steps'],