The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(ai): let runAgent continue a conversation by thread key (#27135)
Félix Malfaitb85da0006738
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 10db5aecddb..8891e9b7ccf 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -1121,6 +1121,22 @@ type BillingCustomer {hasPaymentMethod: Boolean}+type EnterpriseLicenseInfoDTO {+ isValid: Boolean!+ licensee: String+ expiresAt: DateTime+ subscriptionId: String+}++type EnterpriseSubscriptionStatusDTO {+ status: String!+ licensee: String+ expiresAt: DateTime+ cancelAt: DateTime+ currentPeriodEnd: DateTime+ isCancellationScheduled: Boolean!+}+type SdkClientChecksums {core: Stringmetadata: String!@@ -1617,22 +1633,6 @@ enum LogicFunctionExecutionStatus {ERROR}-type EnterpriseLicenseInfoDTO {- isValid: Boolean!- licensee: String- expiresAt: DateTime- subscriptionId: String-}--type EnterpriseSubscriptionStatusDTO {- status: String!- licensee: String- expiresAt: DateTime- cancelAt: DateTime- currentPeriodEnd: DateTime- isCancellationScheduled: Boolean!-}-type UsageQuotaDefinition {resourceType: UsageResourceType!limitKind: String!@@ -3391,6 +3391,7 @@ type RunAgentResult {result: JSONerror: Stringsuccess: Boolean!+ threadId: UUID}type ChannelSyncSuccess {@@ -5551,9 +5552,12 @@ input UpdateWebhookInputUpdates {input RunAgentInput {agentUniversalIdentifier: String!- prompt: String+ prompt: String @deprecated(reason: "Use input instead.")runAsWorkspaceMemberId: UUID- messages: [RunAgentMessageInput!]+ messages: [RunAgentMessageInput!] @deprecated(reason: "Use input instead.")+ input: [RunAgentMessageInput!]+ additionalInstructions: String+ thread: RunAgentThreadInput}input RunAgentMessageInput {@@ -5572,6 +5576,11 @@ input RunAgentMessageAttachmentInput {filename: String}+input RunAgentThreadInput {+ key: String!+ title: String+}+input UpdateMessageFolderInput {id: UUID!update: UpdateMessageFolderInputUpdates!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex a444b0fd169..40f46edbd85 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -818,6 +818,24 @@ export interface BillingCustomer {__typename: 'BillingCustomer'}+export interface EnterpriseLicenseInfoDTO {+ isValid: Scalars['Boolean']+ licensee?: Scalars['String']+ expiresAt?: Scalars['DateTime']+ subscriptionId?: Scalars['String']+ __typename: 'EnterpriseLicenseInfoDTO'+}++export interface EnterpriseSubscriptionStatusDTO {+ status: Scalars['String']+ licensee?: Scalars['String']+ expiresAt?: Scalars['DateTime']+ cancelAt?: Scalars['DateTime']+ currentPeriodEnd?: Scalars['DateTime']+ isCancellationScheduled: Scalars['Boolean']+ __typename: 'EnterpriseSubscriptionStatusDTO'+}+export interface SdkClientChecksums {core?: Scalars['String']metadata: Scalars['String']@@ -1249,24 +1267,6 @@ export interface LogicFunctionExecutionResult {/** Status of the logic function execution */export type LogicFunctionExecutionStatus = 'IDLE' | 'SUCCESS' | 'ERROR'-export interface EnterpriseLicenseInfoDTO {- isValid: Scalars['Boolean']- licensee?: Scalars['String']- expiresAt?: Scalars['DateTime']- subscriptionId?: Scalars['String']- __typename: 'EnterpriseLicenseInfoDTO'-}--export interface EnterpriseSubscriptionStatusDTO {- status: Scalars['String']- licensee?: Scalars['String']- expiresAt?: Scalars['DateTime']- cancelAt?: Scalars['DateTime']- currentPeriodEnd?: Scalars['DateTime']- isCancellationScheduled: Scalars['Boolean']- __typename: 'EnterpriseSubscriptionStatusDTO'-}-export interface UsageQuotaDefinition {resourceType: UsageResourceTypelimitKind: Scalars['String']@@ -2933,6 +2933,7 @@ export interface RunAgentResult {result?: Scalars['JSON']error?: Scalars['String']success: Scalars['Boolean']+ threadId?: Scalars['UUID']__typename: 'RunAgentResult'}@@ -4628,6 +4629,26 @@ export interface BillingCustomerGenqlSelection{__scalar?: boolean | number}+export interface EnterpriseLicenseInfoDTOGenqlSelection{+ isValid?: boolean | number+ licensee?: boolean | number+ expiresAt?: boolean | number+ subscriptionId?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface EnterpriseSubscriptionStatusDTOGenqlSelection{+ status?: boolean | number+ licensee?: boolean | number+ expiresAt?: boolean | number+ cancelAt?: boolean | number+ currentPeriodEnd?: boolean | number+ isCancellationScheduled?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}+export interface SdkClientChecksumsGenqlSelection{core?: boolean | numbermetadata?: boolean | number@@ -5095,26 +5116,6 @@ export interface LogicFunctionExecutionResultGenqlSelection{__scalar?: boolean | number}-export interface EnterpriseLicenseInfoDTOGenqlSelection{- isValid?: boolean | number- licensee?: boolean | number- expiresAt?: boolean | number- subscriptionId?: boolean | number- __typename?: boolean | number- __scalar?: boolean | number-}--export interface EnterpriseSubscriptionStatusDTOGenqlSelection{- status?: boolean | number- licensee?: boolean | number- expiresAt?: boolean | number- cancelAt?: boolean | number- currentPeriodEnd?: boolean | number- isCancellationScheduled?: boolean | number- __typename?: boolean | number- __scalar?: boolean | number-}-export interface UsageQuotaDefinitionGenqlSelection{resourceType?: boolean | numberlimitKind?: boolean | number@@ -6861,6 +6862,7 @@ export interface RunAgentResultGenqlSelection{result?: boolean | numbererror?: boolean | numbersuccess?: boolean | number+ threadId?: boolean | number__typename?: boolean | number__scalar?: boolean | number}@@ -8182,12 +8184,14 @@ 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)}+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']}@@ -8659,6 +8663,22 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel+ const EnterpriseLicenseInfoDTO_possibleTypes: string[] = ['EnterpriseLicenseInfoDTO']+ export const isEnterpriseLicenseInfoDTO = (obj?: { __typename?: any } | null): obj is EnterpriseLicenseInfoDTO => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseLicenseInfoDTO"')+ return EnterpriseLicenseInfoDTO_possibleTypes.includes(obj.__typename)+ }++++ const EnterpriseSubscriptionStatusDTO_possibleTypes: string[] = ['EnterpriseSubscriptionStatusDTO']+ export const isEnterpriseSubscriptionStatusDTO = (obj?: { __typename?: any } | null): obj is EnterpriseSubscriptionStatusDTO => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseSubscriptionStatusDTO"')+ return EnterpriseSubscriptionStatusDTO_possibleTypes.includes(obj.__typename)+ }+++const SdkClientChecksums_possibleTypes: string[] = ['SdkClientChecksums']export const isSdkClientChecksums = (obj?: { __typename?: any } | null): obj is SdkClientChecksums => {if (!obj?.__typename) throw new Error('__typename is missing in "isSdkClientChecksums"')@@ -9011,22 +9031,6 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel- const EnterpriseLicenseInfoDTO_possibleTypes: string[] = ['EnterpriseLicenseInfoDTO']- export const isEnterpriseLicenseInfoDTO = (obj?: { __typename?: any } | null): obj is EnterpriseLicenseInfoDTO => {- if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseLicenseInfoDTO"')- return EnterpriseLicenseInfoDTO_possibleTypes.includes(obj.__typename)- }---- const EnterpriseSubscriptionStatusDTO_possibleTypes: string[] = ['EnterpriseSubscriptionStatusDTO']- export const isEnterpriseSubscriptionStatusDTO = (obj?: { __typename?: any } | null): obj is EnterpriseSubscriptionStatusDTO => {- if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseSubscriptionStatusDTO"')- return EnterpriseSubscriptionStatusDTO_possibleTypes.includes(obj.__typename)- }---const UsageQuotaDefinition_possibleTypes: string[] = ['UsageQuotaDefinition']export const isUsageQuotaDefinition = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinition => {if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinition"')diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 6cfd93f631a..9daca693832 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -43,19 +43,19 @@ export default {85,87,95,- 102,- 105,+ 104,107,- 111,- 112,- 115,- 116,+ 109,+ 113,+ 114,+ 117,118,- 121,- 122,- 134,- 149,- 153,+ 120,+ 123,+ 124,+ 136,+ 151,+ 155,157,158,161,@@ -111,7 +111,7 @@ export default {454,574,581,- 608+ 609],"types": {"BillingProductDTO": {@@ -2142,6 +2142,46 @@ export default {1]},+ "EnterpriseLicenseInfoDTO": {+ "isValid": [+ 8+ ],+ "licensee": [+ 1+ ],+ "expiresAt": [+ 4+ ],+ "subscriptionId": [+ 1+ ],+ "__typename": [+ 1+ ]+ },+ "EnterpriseSubscriptionStatusDTO": {+ "status": [+ 1+ ],+ "licensee": [+ 1+ ],+ "expiresAt": [+ 4+ ],+ "cancelAt": [+ 4+ ],+ "currentPeriodEnd": [+ 4+ ],+ "isCancellationScheduled": [+ 8+ ],+ "__typename": [+ 1+ ]+ },"SdkClientChecksums": {"core": [1@@ -2212,19 +2252,19 @@ export default {1],"type": [- 102+ 104],"objectMetadataId": [3],"gridPosition": [- 100+ 102],"position": [- 103+ 105],"configuration": [- 109+ 111],"conditionalDisplay": [9@@ -2254,13 +2294,13 @@ export default {"WidgetType": {},"PageLayoutWidgetPosition": {"on_PageLayoutWidgetGridPosition": [- 104+ 106],"on_PageLayoutWidgetVerticalListPosition": [- 106+ 108],"on_PageLayoutWidgetCanvasPosition": [- 108+ 110],"__typename": [1@@ -2268,7 +2308,7 @@ export default {},"PageLayoutWidgetGridPosition": {"layoutMode": [- 105+ 107],"row": [31@@ -2289,13 +2329,13 @@ export default {"PageLayoutTabLayoutMode": {},"PageLayoutWidgetVerticalListPosition": {"layoutMode": [- 105+ 107],"index": [31],"heightBehavior": [- 107+ 109],"__typename": [1@@ -2304,7 +2344,7 @@ export default {"PageLayoutWidgetVerticalListHeightBehavior": {},"PageLayoutWidgetCanvasPosition": {"layoutMode": [- 105+ 107],"__typename": [1@@ -2312,91 +2352,91 @@ export default {},"WidgetConfiguration": {"on_AggregateChartConfiguration": [- 110+ 112],"on_StandaloneRichTextConfiguration": [- 113+ 115],"on_PieChartConfiguration": [- 114+ 116],"on_LineChartConfiguration": [- 117+ 119],"on_IframeConfiguration": [- 119+ 121],"on_BarChartConfiguration": [- 120+ 122],"on_CalendarConfiguration": [- 123+ 125],"on_FrontComponentConfiguration": [- 124+ 126],"on_EmailsConfiguration": [- 125+ 127],"on_EmailThreadConfiguration": [- 126+ 128],"on_CallRecordingSummaryConfiguration": [- 127+ 129],"on_CallRecordingTranscriptConfiguration": [- 128+ 130],"on_ChatThreadsConfiguration": [- 129+ 131],"on_ChatConfiguration": [- 130+ 132],"on_MessageCampaignBodyConfiguration": [- 131+ 133],"on_MessageCampaignDetailsConfiguration": [- 132+ 134],"on_FieldConfiguration": [- 133+ 135],"on_FieldRichTextConfiguration": [- 135+ 137],"on_FieldsConfiguration": [- 136+ 138],"on_FormFieldConfiguration": [- 137+ 139],"on_FilesConfiguration": [- 138+ 140],"on_NotesConfiguration": [- 139+ 141],"on_TasksConfiguration": [- 140+ 142],"on_TimelineConfiguration": [- 141+ 143],"on_ViewConfiguration": [- 142+ 144],"on_RecordTableConfiguration": [- 143+ 145],"on_WorkflowConfiguration": [- 144+ 146],"on_WorkflowRunConfiguration": [- 145+ 147],"on_WorkflowVersionConfiguration": [- 146+ 148],"__typename": [1@@ -2404,7 +2444,7 @@ export default {},"AggregateChartConfiguration": {"configurationType": [- 111+ 113],"aggregateFieldMetadataId": [3@@ -2419,7 +2459,7 @@ export default {8],"numberFormat": [- 112+ 114],"description": [1@@ -2440,7 +2480,7 @@ export default {1],"ratioAggregateConfig": [- 98+ 100],"__typename": [1@@ -2450,10 +2490,10 @@ export default {"ChartNumberFormat": {},"StandaloneRichTextConfiguration": {"configurationType": [- 111+ 113],"body": [- 99+ 101],"__typename": [1@@ -2461,7 +2501,7 @@ export default {},"PieChartConfiguration": {"configurationType": [- 111+ 113],"aggregateFieldMetadataId": [3@@ -2476,10 +2516,10 @@ export default {1],"dateGranularity": [- 115+ 117],"orderBy": [- 116+ 118],"manualSortOrder": [1@@ -2497,7 +2537,7 @@ export default {8],"numberFormat": [- 112+ 114],"splitMultiValueFields": [8@@ -2525,7 +2565,7 @@ export default {"GraphOrderBy": {},"LineChartConfiguration": {"configurationType": [- 111+ 113],"aggregateFieldMetadataId": [3@@ -2540,10 +2580,10 @@ export default {1],"primaryAxisDateGranularity": [- 115+ 117],"primaryAxisOrderBy": [- 116+ 118],"primaryAxisManualSortOrder": [1@@ -2555,10 +2595,10 @@ export default {1],"secondaryAxisGroupByDateGranularity": [- 115+ 117],"secondaryAxisOrderBy": [- 116+ 118],"secondaryAxisManualSortOrder": [1@@ -2570,7 +2610,7 @@ export default {8],"axisNameDisplay": [- 118+ 120],"displayDataLabel": [8@@ -2579,7 +2619,7 @@ export default {8],"numberFormat": [- 112+ 114],"rangeMin": [15@@ -2615,7 +2655,7 @@ export default {"AxisNameDisplay": {},"IframeConfiguration": {"configurationType": [- 111+ 113],"url": [1@@ -2626,7 +2666,7 @@ export default {},"BarChartConfiguration": {"configurationType": [- 111+ 113],"aggregateFieldMetadataId": [3@@ -2641,10 +2681,10 @@ export default {1],"primaryAxisDateGranularity": [- 115+ 117],"primaryAxisOrderBy": [- 116+ 118],"primaryAxisManualSortOrder": [1@@ -2656,10 +2696,10 @@ export default {1],"secondaryAxisGroupByDateGranularity": [- 115+ 117],"secondaryAxisOrderBy": [- 116+ 118],"secondaryAxisManualSortOrder": [1@@ -2671,7 +2711,7 @@ export default {8],"axisNameDisplay": [- 118+ 120],"displayDataLabel": [8@@ -2680,7 +2720,7 @@ export default {8],"numberFormat": [- 112+ 114],"rangeMin": [15@@ -2698,10 +2738,10 @@ export default {9],"groupMode": [- 121+ 123],"layout": [- 122+ 124],"isCumulative": [8@@ -2720,7 +2760,7 @@ export default {"BarChartLayout": {},"CalendarConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2728,7 +2768,7 @@ export default {},"FrontComponentConfiguration": {"configurationType": [- 111+ 113],"frontComponentId": [3@@ -2742,7 +2782,7 @@ export default {},"EmailsConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2750,7 +2790,7 @@ export default {},"EmailThreadConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2758,7 +2798,7 @@ export default {},"CallRecordingSummaryConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2766,7 +2806,7 @@ export default {},"CallRecordingTranscriptConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2774,7 +2814,7 @@ export default {},"ChatThreadsConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2782,7 +2822,7 @@ export default {},"ChatConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2790,7 +2830,7 @@ export default {},"MessageCampaignBodyConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2798,7 +2838,7 @@ export default {},"MessageCampaignDetailsConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2806,13 +2846,13 @@ export default {},"FieldConfiguration": {"configurationType": [- 111+ 113],"fieldMetadataId": [1],"fieldDisplayMode": [- 134+ 136],"viewId": [1@@ -2830,7 +2870,7 @@ export default {"FieldDisplayMode": {},"FieldRichTextConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2838,7 +2878,7 @@ export default {},"FieldsConfiguration": {"configurationType": [- 111+ 113],"viewId": [1@@ -2855,7 +2895,7 @@ export default {},"FormFieldConfiguration": {"configurationType": [- 111+ 113],"fieldMetadataId": [1@@ -2866,7 +2906,7 @@ export default {},"FilesConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2874,7 +2914,7 @@ export default {},"NotesConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2882,7 +2922,7 @@ export default {},"TasksConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2890,7 +2930,7 @@ export default {},"TimelineConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2898,7 +2938,7 @@ export default {},"ViewConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2906,7 +2946,7 @@ export default {},"RecordTableConfiguration": {"configurationType": [- 111+ 113],"viewId": [1@@ -2923,7 +2963,7 @@ export default {},"WorkflowConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2931,7 +2971,7 @@ export default {},"WorkflowRunConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2939,7 +2979,7 @@ export default {},"WorkflowVersionConfiguration": {"configurationType": [- 111+ 113],"__typename": [1@@ -2968,13 +3008,13 @@ export default {3],"widgets": [- 101+ 103],"icon": [1],"layoutMode": [- 105+ 107],"createdAt": [4@@ -3003,13 +3043,13 @@ export default {1],"type": [- 149+ 151],"objectMetadataId": [3],"tabs": [- 147+ 149],"defaultTabToFocusOnMobileAndSidePanelId": [3@@ -3068,7 +3108,7 @@ export default {1],"oauth": [- 150+ 152],"logoUrl": [1@@ -3088,7 +3128,7 @@ export default {15],"status": [- 153+ 155],"error": [9@@ -3098,46 +3138,6 @@ export default {]},"LogicFunctionExecutionStatus": {},- "EnterpriseLicenseInfoDTO": {- "isValid": [- 8- ],- "licensee": [- 1- ],- "expiresAt": [- 4- ],- "subscriptionId": [- 1- ],- "__typename": [- 1- ]- },- "EnterpriseSubscriptionStatusDTO": {- "status": [- 1- ],- "licensee": [- 1- ],- "expiresAt": [- 4- ],- "cancelAt": [- 4- ],- "currentPeriodEnd": [- 4- ],- "isCancellationScheduled": [- 8- ],- "__typename": [- 1- ]- },"UsageQuotaDefinition": {"resourceType": [157@@ -6584,6 +6584,9 @@ export default {"success": [8],+ "threadId": [+ 3+ ],"__typename": [1]@@ -6653,10 +6656,10 @@ export default {8],"layout": [- 122+ 124],"groupMode": [- 121+ 123],"hasTooManyGroups": [8@@ -7571,10 +7574,10 @@ export default {}],"enterpriseSubscriptionStatus": [- 155+ 98],"applicationSdkClientChecksums": [- 97,+ 99,{"applicationId": [3,@@ -7610,7 +7613,7 @@ export default {}],"getPageLayoutWidgets": [- 101,+ 103,{"pageLayoutTabId": [1,@@ -7619,7 +7622,7 @@ export default {}],"getPageLayoutWidget": [- 101,+ 103,{"id": [1,@@ -7628,7 +7631,7 @@ export default {}],"getPageLayoutTabs": [- 147,+ 149,{"pageLayoutId": [1,@@ -7637,7 +7640,7 @@ export default {}],"getPageLayoutTab": [- 147,+ 149,{"id": [1,@@ -7646,18 +7649,18 @@ export default {}],"getPageLayouts": [- 148,+ 150,{"objectMetadataId": [1],"pageLayoutType": [- 149+ 151]}],"getPageLayout": [- 148,+ 150,{"id": [1,@@ -7863,7 +7866,7 @@ export default {200],"applicationConnectionProviders": [- 151,+ 153,{"applicationId": [3,@@ -8970,10 +8973,10 @@ export default {8],"releaseEnterpriseServerBinding": [- 154+ 97],"setEnterpriseKey": [- 154,+ 97,{"enterpriseKey": [1,@@ -9058,7 +9061,7 @@ export default {}],"createPageLayoutWidget": [- 101,+ 103,{"input": [457,@@ -9067,7 +9070,7 @@ export default {}],"updatePageLayoutWidget": [- 101,+ 103,{"id": [1,@@ -9089,7 +9092,7 @@ export default {}],"createPageLayoutTab": [- 147,+ 149,{"input": [459,@@ -9098,7 +9101,7 @@ export default {}],"updatePageLayoutTab": [- 147,+ 149,{"id": [1,@@ -9120,7 +9123,7 @@ export default {}],"createPageLayout": [- 148,+ 150,{"input": [461,@@ -9129,7 +9132,7 @@ export default {}],"updatePageLayout": [- 148,+ 150,{"id": [1,@@ -9151,7 +9154,7 @@ export default {}],"updatePageLayoutWithTabsAndWidgets": [- 148,+ 150,{"id": [1,@@ -9164,7 +9167,7 @@ export default {}],"resetPageLayoutToDefault": [- 148,+ 150,{"id": [1,@@ -9173,7 +9176,7 @@ export default {}],"resetPageLayoutWidgetToDefault": [- 101,+ 103,{"id": [1,@@ -9182,7 +9185,7 @@ export default {}],"resetPageLayoutTabToDefault": [- 147,+ 149,{"id": [1,@@ -9522,7 +9525,7 @@ export default {}],"executeOneLogicFunction": [- 152,+ 154,{"input": [510,@@ -10515,7 +10518,7 @@ export default {411,{"input": [- 583,+ 584,"UpdateMessageFolderInput!"]}@@ -10524,7 +10527,7 @@ export default {411,{"input": [- 585,+ 586,"UpdateMessageFoldersInput!"]}@@ -10533,7 +10536,7 @@ export default {406,{"input": [- 586,+ 587,"UpdateCalendarChannelInput!"]}@@ -10542,7 +10545,7 @@ export default {404,{"input": [- 588,+ 589,"SetAppKeyValueInput!"]}@@ -10563,7 +10566,7 @@ export default {402,{"input": [- 589,+ 590,"EnqueueJobInput!"]}@@ -10572,7 +10575,7 @@ export default {403,{"input": [- 590,+ 591,"EnqueueJobsInput!"]}@@ -10581,7 +10584,7 @@ export default {8,{"input": [- 592,+ 593,"ReportAppConnectionAuthFailureInput!"]}@@ -10611,7 +10614,7 @@ export default {1],"fileAttachments": [- 593,+ 594,"[FileAttachmentInput!]"]}@@ -10710,7 +10713,7 @@ export default {390,{"input": [- 594,+ 595,"SendInboxMessageInput!"]}@@ -10719,7 +10722,7 @@ export default {381,{"input": [- 595,+ 596,"CreateSkillInput!"]}@@ -10728,7 +10731,7 @@ export default {381,{"input": [- 596,+ 597,"UpdateSkillInput!"]}@@ -10786,7 +10789,7 @@ export default {418,{"input": [- 597,+ 598,"CreateValidationRuleInput!"]}@@ -10795,7 +10798,7 @@ export default {418,{"input": [- 598,+ 599,"UpdateValidationRuleInput!"]}@@ -10813,7 +10816,7 @@ export default {417,{"input": [- 600,+ 601,"UpdateTimelineActivityTypeInput!"]}@@ -10831,7 +10834,7 @@ export default {299,{"input": [- 601,+ 602,"GetAuthorizationUrlForSSOInput!"]}@@ -10997,7 +11000,7 @@ export default {302,{"input": [- 602+ 603]}],@@ -11205,7 +11208,7 @@ export default {8,{"input": [- 603,+ 604,"UpdateWorkspaceMemberSettingsInput!"]}@@ -11239,7 +11242,7 @@ export default {250,{"input": [- 604,+ 605,"SetupOIDCSsoInput!"]}@@ -11248,7 +11251,7 @@ export default {250,{"input": [- 605,+ 606,"SetupSAMLSsoInput!"]}@@ -11257,7 +11260,7 @@ export default {246,{"input": [- 606,+ 607,"DeleteSsoInput!"]}@@ -11266,7 +11269,7 @@ export default {247,{"input": [- 607,+ 608,"EditSsoInput!"]}@@ -11295,7 +11298,7 @@ export default {394,{"type": [- 608,+ 609,"AnalyticsType!"],"name": [@@ -11338,7 +11341,7 @@ export default {371,{"input": [- 609,+ 610,"CreateCalendarEventInput!"]}@@ -11347,7 +11350,7 @@ export default {393,{"input": [- 610,+ 611,"SendEmailInput!"]}@@ -11369,7 +11372,7 @@ export default {"String!"],"connectionParameters": [- 612,+ 613,"EmailAccountConnectionParameters!"],"id": [@@ -11381,7 +11384,7 @@ export default {210,{"input": [- 614,+ 615,"UpdateLabPublicFeatureFlagInput!"]}@@ -11474,7 +11477,7 @@ export default {"String!"],"files": [- 615,+ 616,"[ApplicationFileUploadRequestInput!]!"]}@@ -11686,7 +11689,7 @@ export default {1],"type": [- 102+ 104],"objectMetadataId": [3@@ -11709,7 +11712,7 @@ export default {1],"type": [- 102+ 104],"objectMetadataId": [3@@ -11741,7 +11744,7 @@ export default {3],"layoutMode": [- 105+ 107],"__typename": [1@@ -11758,7 +11761,7 @@ export default {1],"layoutMode": [- 105+ 107],"__typename": [1@@ -11769,7 +11772,7 @@ export default {1],"type": [- 149+ 151],"objectMetadataId": [3@@ -11783,7 +11786,7 @@ export default {1],"type": [- 149+ 151],"objectMetadataId": [3@@ -11797,7 +11800,7 @@ export default {1],"type": [- 149+ 151],"objectMetadataId": [3@@ -11826,7 +11829,7 @@ export default {1],"layoutMode": [- 105+ 107],"widgets": [465@@ -11846,7 +11849,7 @@ export default {1],"type": [- 102+ 104],"objectMetadataId": [3@@ -14040,6 +14043,15 @@ export default {"messages": [580],+ "input": [+ 580+ ],+ "additionalInstructions": [+ 1+ ],+ "thread": [+ 583+ ],"__typename": [1]@@ -14070,12 +14082,23 @@ export default {1]},+ "RunAgentThreadInput": {+ "key": [+ 1+ ],+ "title": [+ 1+ ],+ "__typename": [+ 1+ ]+ },"UpdateMessageFolderInput": {"id": [3],"update": [- 584+ 585],"__typename": [1@@ -14094,7 +14117,7 @@ export default {3],"update": [- 584+ 585],"__typename": [1@@ -14105,7 +14128,7 @@ export default {3],"update": [- 587+ 588],"__typename": [1@@ -14170,7 +14193,7 @@ export default {9],"jobs": [- 591+ 592],"retryLimit": [31@@ -14321,7 +14344,7 @@ export default {3],"update": [- 599+ 600],"__typename": [1@@ -14533,7 +14556,7 @@ export default {1],"files": [- 611+ 612],"__typename": [1@@ -14555,13 +14578,13 @@ export default {1],"IMAP": [- 613+ 614],"SMTP": [- 613+ 614],"CALDAV": [- 613+ 614],"__typename": [1@@ -14626,7 +14649,7 @@ export default {291,{"input": [- 617,+ 618,"LogicFunctionLogsInput!"]}@@ -14657,7 +14680,7 @@ export default {398,{"input": [- 618,+ 619,"CreateRecordExportInput!"]}diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdxindex bfe35b10250..d92eb8becd7 100644--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx@@ -103,38 +103,22 @@ Schema notes:`runAgent()` lets a logic function run one of your app's agents (with itsskills and tools). Identify the agent by the `universalIdentifier` you passed-to `defineAgent()`. Pass either a `prompt` string or a `messages` conversation-history — not both:+to `defineAgent()`, and pass what you want it to work on as `input`:```ts src/logic-functions/run-enricher.tsimport { runAgent } from 'twenty-sdk/logic-function';const { result, error, success } = await runAgent({agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',- prompt: 'Enrich House Ad <recordId>: fill empty fields from its listing URL.',-});-```--For multi-turn bots (Slack, Discord, Teams, …), pass thread history as-`messages` instead of a single `prompt`:--```ts src/logic-functions/reply-in-thread.ts-import { runAgent } from 'twenty-sdk/logic-function';--const { result, error, success } = await runAgent({- agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',- messages: [- { role: 'user', content: 'Who owns Acme?' },- { role: 'assistant', content: 'Sarah owns the Acme account.' },- { role: 'user', content: 'What was the last touchpoint?' },- ],+ input: 'Enrich House Ad <recordId>: fill empty fields from its listing URL.',});```Key points:-- Provide **exactly one** of `prompt` (string) or `messages` (1 to 100 entries- of `{ role: 'user' | 'assistant', content: string }`). A `user` message can- also carry file attachments — see below.+- `input` is a string, or a list of 1 to 100 messages+ (`{ role: 'user' | 'assistant', content: string }`). A `user` message can+ also carry file attachments (see below). To hold a conversation, pass a+ `thread` rather than replaying earlier turns yourself.- The agent runs **synchronously** and can read/update records itself via itsown tools — `runAgent()` resolves once the run completes.- An app can only run its own agents.@@ -175,7 +159,7 @@ uploaded into the `agent-chat` folder:```ts src/logic-functions/describe-screenshot.tsconst { result } = await runAgent({agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',- messages: [+ input: [{role: 'user',content: 'What does this error screen say?',@@ -195,6 +179,37 @@ alongside `AI`. `filename` is optional and only labels the file for the model.`agent-chat` folder. Anything else fails the call instead of quietlyanswering without the file.+### Continuing a conversation++Pass a `thread` and Twenty keeps the conversation for you: each call sends only+the new input, and the agent sees the earlier turns, including what its tools+returned. Use any stable identifier from your side as the key, such as a Slack+channel and thread timestamp:++```ts src/logic-functions/reply-in-thread.ts+const { result, threadId } = await runAgent({+ agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',+ input: 'What was the last touchpoint?',+ additionalInstructions: 'Answer in Slack markdown.',+ thread: { key: `${channelId}:${threadTs}`, title: 'Acme renewal' },+});+```++- Keys are scoped to your app and agent, so two apps never share a+ conversation. Only app access tokens can pass a `thread`.+- `input` may only hold `user` messages: the conversation already holds the+ agent's replies.+- `additionalInstructions` are given to the model for this call only and are not+ stored, which suits per-request guidance such as formatting rules or a+ deadline. They work without a `thread` too.+- A turn is stored once the run succeeds. A failed run leaves the conversation+ as it was.+- Calls on the same thread run one at a time: a second call waits for the+ first to finish, so each one sees the turns before it.+- When turns run as different members (see below), each one only sees the text+ of the others' turns, never their tool results, since those were read with+ someone else's permissions.+### Running on behalf of a workspace memberPass `runAsWorkspaceMemberId` when the run is triggered by a person — a chat@@ -204,7 +219,7 @@ instead of as the app:```ts src/logic-functions/answer-question.tsconst { result } = await runAgent({agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',- prompt: 'How many open opportunities do we have?',+ input: 'How many open opportunities do we have?',runAsWorkspaceMemberId: '20202020-0687-4c41-b707-ed1bfca972a7',});```diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 161a35c3fa2..05a4c933986 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -6131,10 +6131,11 @@ export enum RowLevelPermissionPredicateOperand {}export type RunAgentInput = {+ additionalInstructions?: InputMaybe<Scalars['String']['input']>;agentUniversalIdentifier: Scalars['String']['input'];- messages?: InputMaybe<Array<RunAgentMessageInput>>;- prompt?: InputMaybe<Scalars['String']['input']>;+ input?: InputMaybe<Array<RunAgentMessageInput>>;runAsWorkspaceMemberId?: InputMaybe<Scalars['UUID']['input']>;+ thread?: InputMaybe<RunAgentThreadInput>;};export type RunAgentMessageAttachmentInput = {@@ -6158,6 +6159,12 @@ export type RunAgentResult = {error?: Maybe<Scalars['String']['output']>;result?: Maybe<Scalars['JSON']['output']>;success: Scalars['Boolean']['output'];+ threadId?: Maybe<Scalars['UUID']['output']>;+};++export type RunAgentThreadInput = {+ key: Scalars['String']['input'];+ title?: InputMaybe<Scalars['String']['input']>;};export type SsoConnection = {diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.tsindex d1b2a15f399..3f5253b1b28 100644--- a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts@@ -30,6 +30,7 @@ describe('runAgent', () => {result: { response: 'done' },error: null,success: true,+ threadId: null,};fetchSpy.mockResolvedValue(@@ -68,6 +69,44 @@ describe('runAgent', () => {});});+ it('sends a string input as a single user message, with its thread', async () => {+ fetchSpy.mockResolvedValue(+ new Response(+ JSON.stringify({+ data: {+ runAgent: {+ result: { response: 'done' },+ error: null,+ success: true,+ threadId: 'thread-id',+ },+ },+ }),+ { status: 200 },+ ),+ );++ const result = await runAgent({+ agentUniversalIdentifier: 'agent-uid',+ input: 'What was the last touchpoint?',+ additionalInstructions: 'Answer in Slack markdown.',+ thread: { key: 'C123:1700000000.000100', title: 'Acme renewal' },+ });++ expect(result.threadId).toBe('thread-id');++ const sentBody = JSON.parse(fetchSpy.mock.calls[0][1]?.body as string);++ expect(sentBody.variables).toEqual({+ input: {+ agentUniversalIdentifier: 'agent-uid',+ input: [{ role: 'user', content: 'What was the last touchpoint?' }],+ additionalInstructions: 'Answer in Slack markdown.',+ thread: { key: 'C123:1700000000.000100', title: 'Acme renewal' },+ },+ });+ });+it('POSTs messages when provided instead of prompt', async () => {const payload = {result: { response: 'done' },diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.tsindex 84308ef7bfe..fbf86ae8d42 100644--- a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts@@ -2,6 +2,7 @@ import {type RunAgentInput,type RunAgentResult,} from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';@@ -11,19 +12,33 @@ const RUN_AGENT_MUTATION = `resulterrorsuccess+ threadId}}`;-export const runAgent = async (- input: RunAgentInput,-): Promise<RunAgentResult> => {+export const runAgent = async ({+ input,+ ...rest+}: RunAgentInput): Promise<RunAgentResult> => {+ const variables = {+ input: isDefined(input)+ ? {+ ...rest,+ input:+ typeof input === 'string'+ ? [{ role: 'user', content: input }]+ : input,+ }+ : rest,+ };+const { runAgent: result } = await postGraphqlRequest<- { input: RunAgentInput },+ typeof variables,{ runAgent: RunAgentResult }>({query: RUN_AGENT_MUTATION,- variables: { input },+ variables,caller: 'runAgent',});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.tsindex 7e10242fba1..9b2396a38db 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@@ -4,6 +4,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { ApplicationLookupModule } from 'src/engine/core-modules/application/application-lookup/application-lookup.module';import { BillingModule } from 'src/engine/core-modules/billing/billing.module';+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';import { FileUrlModule } from 'src/engine/core-modules/file/file-url/file-url.module';@@ -16,6 +17,7 @@ import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agimport { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-billing.module';import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';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';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';@@ -29,16 +31,19 @@ import { AgentMessagePartResolver } from './resolvers/agent-message-part.resolveimport { AgentRunResolver } from './resolvers/agent-run.resolver';import { AgentActorContextService } from './services/agent-actor-context.service';import { AgentAsyncExecutorService } from './services/agent-async-executor.service';+import { AgentRunConversationService } from './services/agent-run-conversation.service';import { AgentRunService } from './services/agent-run.service';import { RunAgentAttachmentService } from './services/run-agent-attachment.service';@Module({imports: [+ AgentHistoryModule,AiBillingModule,AiModelsModule,AiAgentModule,ApplicationLookupModule,BillingModule,+ CacheLockModule,FileUrlModule,WorkspaceDomainsModule,MetricsModule,@@ -64,6 +69,7 @@ import { RunAgentAttachmentService } from './services/run-agent-attachment.serviAgentMessagePartResolver,AgentMessageResolver,AgentRunResolver,+ AgentRunConversationService,AgentRunService,RunAgentAttachmentService,provideWorkspaceScopedRepository(RoleTargetEntity),diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-id-namespace.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-id-namespace.const.tsnew file mode 100644index 00000000000..3e80725d203--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-id-namespace.const.ts@@ -0,0 +1,2 @@+export const AGENT_RUN_THREAD_ID_NAMESPACE =+ 'efa281f3-a348-4fde-9485-814fb5d7175a';diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-lock.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-lock.const.tsnew file mode 100644index 00000000000..7a8901767df--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-lock.const.ts@@ -0,0 +1,3 @@+export const AGENT_RUN_THREAD_LOCK_TTL_MS = 900_000;++export const AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS = 500;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.tsindex 3f673c43b2e..52721db4c9b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts@@ -3,6 +3,8 @@ import { Field, ObjectType } from '@nestjs/graphql';import GraphQLJSON from 'graphql-type-json';import { type RunAgentResult } from 'twenty-shared/application';+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';+@ObjectType('RunAgentResult')export class RunAgentResultDTO implements RunAgentResult {@Field(() => GraphQLJSON, { nullable: true })@@ -13,4 +15,7 @@ export class RunAgentResultDTO implements RunAgentResult {@Field()success: boolean;++ @Field(() => UUIDScalarType, { nullable: true })+ threadId: string | null;}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-thread.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-thread.input.tsnew file mode 100644index 00000000000..d68176f82cc--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-thread.input.ts@@ -0,0 +1,18 @@+import { Field, InputType } from '@nestjs/graphql';++import { IsNotEmpty, IsOptional, IsString } from 'class-validator';+import { type RunAgentThread } from 'twenty-shared/application';++@InputType('RunAgentThreadInput')+export class RunAgentThreadInputDTO implements RunAgentThread {+ @IsString()+ @IsNotEmpty()+ @Field()+ key: string;++ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @Field({ nullable: true })+ title?: string;+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent.input.tsindex 400a537d093..84e4db17601 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent.input.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent.input.ts@@ -13,6 +13,7 @@ import {} from 'class-validator';import { RunAgentMessageInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input';+import { RunAgentThreadInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-thread.input';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';@@ -26,7 +27,7 @@ export class RunAgentInputDTO {@IsOptional()@IsString()@IsNotEmpty()- @Field({ nullable: true })+ @Field({ nullable: true, deprecationReason: 'Use input instead.' })prompt?: string;@IsUUID()@@ -40,6 +41,30 @@ export class RunAgentInputDTO {@ArrayMaxSize(100)@ValidateNested({ each: true })@Type(() => RunAgentMessageInputDTO)- @Field(() => [RunAgentMessageInputDTO], { nullable: true })+ @Field(() => [RunAgentMessageInputDTO], {+ nullable: true,+ deprecationReason: 'Use input instead.',+ })messages?: RunAgentMessageInputDTO[];++ @IsOptional()+ @IsArray()+ @ArrayNotEmpty()+ @ArrayMaxSize(100)+ @ValidateNested({ each: true })+ @Type(() => RunAgentMessageInputDTO)+ @Field(() => [RunAgentMessageInputDTO], { nullable: true })+ input?: RunAgentMessageInputDTO[];++ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @Field({ nullable: true })+ additionalInstructions?: string;++ @IsOptional()+ @ValidateNested()+ @Type(() => RunAgentThreadInputDTO)+ @Field(() => RunAgentThreadInputDTO, { nullable: true })+ thread?: RunAgentThreadInputDTO;}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.tsnew file mode 100644index 00000000000..7cbe4b12b62--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts@@ -0,0 +1,234 @@+import { Logger } from '@nestjs/common';++import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';+import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';++const WORKSPACE = { id: 'workspace-id' } as never;+const APPLICATION = { id: 'application-id' };+const AGENT = {+ id: 'agent-id',+ label: 'Slack Assistant',+ applicationId: APPLICATION.id,+ universalIdentifier: 'slack-assistant',+};+const RUN_AS_USER_WORKSPACE_ID = 'user-workspace-id';+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 = {+ recordTurn: jest.fn().mockResolvedValue(undefined),+ withThreadLock: jest.fn(({ work }) => work()),+ };+ const conversationReaderService = {+ loadMessages: jest.fn().mockResolvedValue(PRIOR_MESSAGES),+ };+ const agentActorContextService = {+ buildRunAsWorkspaceMemberContext: jest.fn().mockResolvedValue({+ actorContext: {},+ authContext: { userWorkspaceId: RUN_AS_USER_WORKSPACE_ID },+ roleId: 'role-id',+ }),+ };++ const service = new AgentRunService(+ agentActorContextService as never,+ agentAsyncExecutorService as never,+ agentRunConversationService 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,+ };+};++const run = (+ service: AgentRunService,+ input: Record<string, unknown>,+ { isCalledByApplication = true }: { isCalledByApplication?: boolean } = {},+) =>+ service.run({+ workspace: WORKSPACE,+ requestUserWorkspaceId: null,+ requestWorkspaceMemberId: null,+ callerApplication: isCalledByApplication+ ? (APPLICATION as never)+ : undefined,+ input: { agentUniversalIdentifier: AGENT.universalIdentifier, ...input },+ });++const userInput = (content: string) => [{ role: 'user', content }];++describe('AgentRunService', () => {+ it('runs without a conversation when no thread is given', async () => {+ const {+ service,+ agentAsyncExecutorService,+ agentRunConversationService,+ conversationReaderService,+ } = buildService();++ const result = await run(service, {+ input: userInput('Who is our biggest customer?'),+ });++ expect(result).toEqual({+ result: { response: 'Acme is your biggest customer' },+ error: null,+ success: true,+ threadId: null,+ });+ expect(conversationReaderService.loadMessages).not.toHaveBeenCalled();+ expect(agentRunConversationService.recordTurn).not.toHaveBeenCalled();+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ priorMessages: [] }),+ );+ });++ it('keeps accepting a prompt', async () => {+ const { service, agentAsyncExecutorService } = buildService();++ await run(service, { prompt: 'Who is our biggest customer?' });++ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: 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 threadId = buildAgentRunThreadId({+ applicationId: APPLICATION.id,+ agentId: AGENT.id,+ threadKey: 'C123:1700000000.000100',+ });++ const result = await run(service, {+ input: userInput('And the second one?'),+ thread: { key: 'C123:1700000000.000100' },+ runAsWorkspaceMemberId: 'workspace-member-id',+ });++ const actor = { type: 'user', userWorkspaceId: RUN_AS_USER_WORKSPACE_ID };++ 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(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ priorMessages: PRIOR_MESSAGES }),+ );+ expect(agentRunConversationService.recordTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ threadId,+ title: AGENT.label,+ actor,+ messages: userInput('And the second one?'),+ execution: executionResult,+ }),+ );+ });++ it('gives the additional instructions to the model without recording them', async () => {+ const { service, agentAsyncExecutorService, agentRunConversationService } =+ buildService();++ await run(service, {+ input: userInput('And the second one?'),+ thread: { key: 'thread', title: 'Acme renewal' },+ additionalInstructions: 'Answer in Slack markdown',+ });++ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: userInput('Answer in Slack markdown\n\nAnd the second one?'),+ }),+ );+ expect(agentRunConversationService.recordTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Acme renewal',+ messages: userInput('And the second one?'),+ actor: { type: 'application', applicationId: APPLICATION.id },+ }),+ );+ });++ it('still returns the reply when the turn cannot be recorded', async () => {+ const { service, agentRunConversationService } = buildService();++ jest.spyOn(Logger.prototype, 'error').mockImplementation();+ agentRunConversationService.recordTurn.mockRejectedValue(+ new Error('write failed'),+ );++ const result = await run(service, {+ input: userInput('And the second one?'),+ thread: { key: 'thread' },+ });++ expect(result.success).toBe(true);+ });++ it('refuses a thread without an application token', async () => {+ const { service } = buildService();++ await expect(+ run(+ service,+ { input: userInput('Hello'), thread: { key: 'thread' } },+ { isCalledByApplication: false },+ ),+ ).rejects.toMatchObject({ code: AiExceptionCode.RUN_AGENT_NOT_ALLOWED });+ });++ it('refuses a thread with a blank key', async () => {+ const { service, agentAsyncExecutorService } = buildService();++ await expect(+ run(service, { input: userInput('Hello'), thread: { key: ' ' } }),+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });+ expect(agentAsyncExecutorService.executeAgent).not.toHaveBeenCalled();+ });++ it('refuses assistant messages sent to a thread', async () => {+ const { service } = buildService();++ await expect(+ run(service, {+ thread: { key: 'thread' },+ input: [+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: 'Hi' },+ ],+ }),+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.tsindex ed51a3f8b3d..26d2642f952 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts@@ -2,10 +2,10 @@ import { Injectable, Logger } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import {+ convertToModelMessages,generateText,jsonSchema,type LanguageModelUsage,- type ModelMessage,Output,isStepCount,type StepResult,@@ -14,6 +14,7 @@ import {import { type RunAgentMessage } from 'twenty-shared/application';import {AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ type ExtendedUIMessage,PROPOSE_TOOL_CALL_TOOL_NAME,} from 'twenty-shared/ai';import { type ActorMetadata } from 'twenty-shared/types';@@ -74,6 +75,7 @@ import {} from 'src/engine/metadata-modules/ai/ai-billing/utils/extract-cache-creation-tokens.util';import { mergeLanguageModelUsage } from 'src/engine/metadata-modules/ai/ai-billing/utils/merge-language-model-usage.util';import { getCallLevelProviderOptions } from 'src/engine/metadata-modules/ai/ai-chat/utils/provider-options.util';+import { replaceUnsupportedFileParts } from 'src/engine/metadata-modules/ai/ai-chat/utils/replace-unsupported-file-parts.util';import { createProposeToolCallTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-tool-call.tool';import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';import { buildAiTelemetry } from 'src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util';@@ -352,14 +354,14 @@ export class AgentAsyncExecutorService {runAsRoleId,operationType = UsageOperationType.AI_WORKFLOW_TOKEN,toolLoadingStrategy = 'preload',- priorModelMessages = [],+ priorMessages = [],pausingTools = {},canProposeToolCalls = false,}: {agent: AgentEntity | null;messages: RunAgentMessage[];// a continued conversation, with the tool calls and results plain run messages cannot carry- priorModelMessages?: ModelMessage[];+ priorMessages?: ExtendedUIMessage[];pausingTools?: ToolSet;// offers propose_tool_call over the registry tools the agent can call itself, or emails without an agentcanProposeToolCalls?: boolean;@@ -372,7 +374,7 @@ export class AgentAsyncExecutorService {operationType?: UsageOperationType;toolLoadingStrategy?: AgentToolLoadingStrategy;}): Promise<AgentExecutionResult> {- if (!isNonEmptyArray(messages) && !isNonEmptyArray(priorModelMessages)) {+ if (!isNonEmptyArray(messages) && !isNonEmptyArray(priorMessages)) {throw new AiException('Provide at least one message to run an agent',AiExceptionCode.INVALID_AGENT_INPUT,@@ -477,13 +479,19 @@ export class AgentAsyncExecutorService {let hasNoMoreAvailableCredits = false;+ const modalities = this.aiModelRegistryService.getModelConfig(+ registeredModel.modelId,+ )?.modalities;++ const priorModelMessages = await convertToModelMessages(+ replaceUnsupportedFileParts(priorMessages, modalities, false),+ );+const modelMessages =await this.runAgentAttachmentService.buildModelMessagesOrThrow({messages,workspaceId,- modalities: this.aiModelRegistryService.getModelConfig(- registeredModel.modelId,- )?.modalities,+ modalities,});// an agent proposes its own tools; a step without an agent has none, so it proposes only emailsdiff --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.tsnew file mode 100644index 00000000000..bc3dd2c6b82--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts@@ -0,0 +1,143 @@+import { Injectable } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';+import {+ type ExtendedFileUIPart,+ type ExtendedUIMessagePart,+} from 'twenty-shared/ai';+import { type RunAgentMessage } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import {+ AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,+ AGENT_RUN_THREAD_LOCK_TTL_MS,+} from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-lock.const';+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+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 { 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 AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';+import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';++@Injectable()+export class AgentRunConversationService {+ constructor(+ @InjectAgentHistoryRepository('agentChatThread')+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,+ private readonly conversationWriterService: AgentConversationWriterService,+ private readonly cacheLockService: CacheLockService,+ ) {}++ withThreadLock<TResult>({+ workspaceId,+ threadId,+ work,+ }: {+ workspaceId: string;+ threadId: string;+ work: () => Promise<TResult>;+ }): Promise<TResult> {+ return this.cacheLockService.withLock(+ work,+ `agent-run-thread:${workspaceId}:${threadId}`,+ {+ ttl: AGENT_RUN_THREAD_LOCK_TTL_MS,+ ms: AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,+ maxRetries:+ AGENT_RUN_THREAD_LOCK_TTL_MS /+ AGENT_RUN_THREAD_LOCK_RETRY_INTERVAL_MS,+ },+ );+ }++ async recordTurn({+ workspaceId,+ threadId,+ title,+ agentId,+ applicationId,+ actor,+ messages,+ startedAt,+ execution,+ }: {+ workspaceId: string;+ threadId: string;+ title: string;+ agentId: string;+ applicationId: string;+ actor: AgentConversationActor;+ messages: RunAgentMessage[];+ startedAt: Date;+ execution: RecordableAgentExecution;+ }): Promise<void> {+ const existingThread = await this.threadRepository.findOne(workspaceId, {+ where: { id: threadId },+ select: ['id'],+ });++ await this.conversationWriterService.runInTransaction(+ workspaceId,+ async (scope) => {+ if (!isDefined(existingThread)) {+ await scope.insert('agentChatThread', { id: threadId, title });+ }++ const turnId = await this.conversationWriterService.insertTurn({+ workspaceId,+ threadId,+ agentId,+ scope,+ });++ for (const message of messages) {+ await this.conversationWriterService.insertMessage({+ workspaceId,+ threadId,+ turnId,+ role: AgentMessageRole.USER,+ agentId: null,+ senderUserWorkspaceId:+ actor.type === 'user' ? actor.userWorkspaceId : null,+ senderApplicationId: applicationId,+ processedAt: startedAt,+ parts: this.buildUserMessageParts(message),+ scope,+ });+ }++ await this.conversationWriterService.insertExecutionReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ execution,+ scope,+ });+ },+ );+ }++ private buildUserMessageParts(+ message: RunAgentMessage,+ ): ExtendedUIMessagePart[] {+ const fileParts = (message.attachments ?? []).map(+ (attachment): ExtendedFileUIPart => ({+ type: 'file',+ mediaType: '',+ filename: attachment.filename,+ url: '',+ fileId: attachment.fileId,+ }),+ );++ return [+ ...(isNonEmptyString(message.content)+ ? [{ type: 'text' as const, text: message.content }]+ : []),+ ...fileParts,+ ];+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.tsindex 9d081ac8dda..41625f06cad 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@@ -4,8 +4,9 @@ import { isNonEmptyString } from '@sniptt/guards';import {type RunAgentMessage,type RunAgentResult,+ type RunAgentThread,} from 'twenty-shared/application';-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { isDefined } from 'twenty-shared/utils';import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';@@ -14,9 +15,15 @@ import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-opimport { 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 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,@@ -27,8 +34,11 @@ import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scopetype RunAgentServiceInput = {agentUniversalIdentifier: string;+ input?: RunAgentMessage[] | null;prompt?: string | null;messages?: RunAgentMessage[] | null;+ additionalInstructions?: string | null;+ thread?: RunAgentThread | null;runAsWorkspaceMemberId?: string;};@@ -39,7 +49,9 @@ export class AgentRunService {constructor(private readonly agentActorContextService: AgentActorContextService,private readonly agentAsyncExecutorService: AgentAsyncExecutorService,+ private readonly agentRunConversationService: AgentRunConversationService,private readonly applicationLookupService: ApplicationLookupService,+ private readonly conversationReaderService: AgentConversationReaderService,@InjectWorkspaceScopedRepository(AgentEntity)private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,) {}@@ -57,19 +69,24 @@ export class AgentRunService {callerApplication?: FlatApplication;input: RunAgentServiceInput;}): Promise<RunAgentResult> {- const prompt = input.prompt;+ const messages = resolveRunAgentMessagesOrThrow({+ input: input.input,+ prompt: input.prompt,+ messages: input.messages,+ });- // GraphQL cannot express XOR; enforce exactly one of prompt or messages- if (isNonEmptyArray(input.messages) === isNonEmptyString(prompt)) {+ if (isDefined(input.thread) && !isNonEmptyString(input.thread.key.trim())) {throw new AiException(- 'Provide exactly one of prompt or messages',+ 'thread.key must not be empty',AiExceptionCode.INVALID_AGENT_INPUT,);}- const messages: RunAgentMessage[] = isNonEmptyString(prompt)- ? [{ role: 'user', content: prompt }]- : (input.messages ?? []);+ const thread = input.thread ?? null;++ if (isDefined(thread)) {+ this.assertCanContinueConversation({ callerApplication, messages });+ }const agent = await this.agentRepository.findOne(workspace.id, {where: {@@ -119,11 +136,48 @@ export class AgentRunService {application,};- try {+ const actor: AgentConversationActor = isDefined(runAsContext)+ ? {+ type: 'user',+ userWorkspaceId: runAsContext.authContext.userWorkspaceId,+ }+ : { type: 'application', applicationId: application.id };++ const threadTitle = isNonEmptyString(thread?.title)+ ? thread.title+ : agent.label;++ const threadId = isDefined(thread)+ ? buildAgentRunThreadId({+ applicationId: application.id,+ agentId: agent.id,+ threadKey: thread.key,+ })+ : null;++ const executionMessages = isNonEmptyString(input.additionalInstructions)+ ? addAdditionalInstructionsToLastRunAgentMessage({+ messages,+ additionalInstructions: input.additionalInstructions,+ })+ : messages;++ const runTurn = async (): Promise<RunAgentResult> => {+ const priorMessages = isDefined(threadId)+ ? await this.conversationReaderService.loadMessages({+ workspaceId: workspace.id,+ threadId,+ actor,+ })+ : [];++ const startedAt = new Date();+const executionResult = await withDedicatedAiTrace(() =>this.agentAsyncExecutorService.executeAgent({agent,- messages,+ messages: executionMessages,+ priorMessages,baseSystemPrompt: AGENT_RUN_BASE_SYSTEM_PROMPT,actorContext: runAsContext?.actorContext,authContext,@@ -141,14 +195,47 @@ export class AgentRunService {result: null,error: 'Agent stopped: no more available credits.',success: false,+ threadId,};}+ if (isDefined(threadId)) {+ await this.agentRunConversationService+ .recordTurn({+ workspaceId: workspace.id,+ threadId,+ title: threadTitle,+ agentId: agent.id,+ applicationId: application.id,+ actor,+ messages,+ startedAt,+ execution: executionResult,+ })+ .catch((error: unknown) =>+ this.logger.error(+ `Failed to record the turn of ${input.agentUniversalIdentifier} in thread ${threadId}`,+ error instanceof Error ? error.stack : error,+ ),+ );+ }+return {result: executionResult.result,error: null,success: true,+ threadId,};+ };++ try {+ return isDefined(threadId)+ ? await this.agentRunConversationService.withThreadLock({+ workspaceId: workspace.id,+ threadId,+ work: runTurn,+ })+ : await runTurn();} catch (error) {if (error instanceof AiException &&@@ -166,10 +253,33 @@ export class AgentRunService {result: null,error: 'Agent execution failed.',success: false,+ threadId,};}}+ private assertCanContinueConversation({+ callerApplication,+ messages,+ }: {+ callerApplication?: FlatApplication;+ messages: RunAgentMessage[];+ }): void {+ if (!isDefined(callerApplication)) {+ throw new AiException(+ 'Continuing a conversation requires an application access token',+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,+ );+ }++ if (messages.some((message) => message.role !== 'user')) {+ throw new AiException(+ 'A conversation already holds its replies, so only user messages can be sent to it',+ AiExceptionCode.INVALID_AGENT_INPUT,+ );+ }+ }+private async resolveRunAsContext({runAsWorkspaceMemberId,callerApplication,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/add-additional-instructions-to-last-run-agent-message.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/add-additional-instructions-to-last-run-agent-message.util.spec.tsnew file mode 100644index 00000000000..67af6304d28--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/add-additional-instructions-to-last-run-agent-message.util.spec.ts@@ -0,0 +1,34 @@+import { addAdditionalInstructionsToLastRunAgentMessage } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util';++describe('addAdditionalInstructionsToLastRunAgentMessage', () => {+ it('should put the instructions before the content of the last message only', () => {+ expect(+ addAdditionalInstructionsToLastRunAgentMessage({+ messages: [+ { role: 'user', content: 'Who owns Acme?' },+ { role: 'user', content: 'And the last touchpoint?' },+ ],+ additionalInstructions: 'Answer in Slack markdown.',+ }),+ ).toEqual([+ { role: 'user', content: 'Who owns Acme?' },+ {+ role: 'user',+ content: 'Answer in Slack markdown.\n\nAnd the last touchpoint?',+ },+ ]);+ });++ it('should use the instructions as the content of a message that only carries files', () => {+ const attachments = [{ fileId: 'file-id', filename: 'deck.pdf' }];++ expect(+ addAdditionalInstructionsToLastRunAgentMessage({+ messages: [{ role: 'user', content: '', attachments }],+ additionalInstructions: 'Answer in Slack markdown.',+ }),+ ).toEqual([+ { role: 'user', content: 'Answer in Slack markdown.', attachments },+ ]);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-thread-id.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-thread-id.util.spec.tsnew file mode 100644index 00000000000..c9e02b7dfa9--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-thread-id.util.spec.ts@@ -0,0 +1,39 @@+import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';++const applicationId = '20202020-1c25-4d02-bf25-6aeccf7ea419';+const agentId = '20202020-9e3b-46d4-a556-88b9ddc2b034';+const threadKey = 'C123:1700000000.000100';++describe('buildAgentRunThreadId', () => {+ it('should derive the same thread id for the same key', () => {+ expect(buildAgentRunThreadId({ applicationId, agentId, threadKey })).toBe(+ buildAgentRunThreadId({ applicationId, agentId, threadKey }),+ );+ });++ it('should give each application, agent and key its own thread id', () => {+ const threadId = buildAgentRunThreadId({+ applicationId,+ agentId,+ threadKey,+ });++ expect(+ buildAgentRunThreadId({+ applicationId: '20202020-3d15-4f4d-a9b6-1fd1d0a8b5c0',+ agentId,+ threadKey,+ }),+ ).not.toBe(threadId);+ expect(+ buildAgentRunThreadId({+ applicationId,+ agentId: '20202020-7a6f-4b2e-9c33-2f1e6b7c8d90',+ threadKey,+ }),+ ).not.toBe(threadId);+ expect(+ buildAgentRunThreadId({ applicationId, agentId, threadKey: 'C123:2' }),+ ).not.toBe(threadId);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-run-agent-messages-or-throw.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-run-agent-messages-or-throw.util.spec.tsnew file mode 100644index 00000000000..19347ec636f--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-run-agent-messages-or-throw.util.spec.ts@@ -0,0 +1,73 @@+import { resolveRunAgentMessagesOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util';+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';++describe('resolveRunAgentMessagesOrThrow', () => {+ it('should return the input messages', () => {+ const input = [{ role: 'user' as const, content: 'Who owns Acme?' }];++ expect(resolveRunAgentMessagesOrThrow({ input })).toEqual(input);+ });++ it('should keep accepting a prompt as a single user message', () => {+ expect(+ resolveRunAgentMessagesOrThrow({ prompt: 'Who owns Acme?' }),+ ).toEqual([{ role: 'user', content: 'Who owns Acme?' }]);+ });++ it('should keep accepting messages', () => {+ const messages = [+ { role: 'user' as const, content: 'Who owns Acme?' },+ { role: 'assistant' as const, content: 'Sarah.' },+ { role: 'user' as const, content: 'And the last touchpoint?' },+ ];++ expect(resolveRunAgentMessagesOrThrow({ messages })).toEqual(messages);+ });++ it('should keep accepting blank turns in legacy messages', () => {+ const messages = [+ { role: 'user' as const, content: 'Who owns Acme?' },+ { role: 'assistant' as const, content: '' },+ ];++ expect(resolveRunAgentMessagesOrThrow({ messages })).toEqual(messages);+ });++ it('should accept an input message that only carries files', () => {+ const input = [+ {+ role: 'user' as const,+ content: '',+ attachments: [{ fileId: 'file-id' }],+ },+ ];++ expect(resolveRunAgentMessagesOrThrow({ input })).toEqual(input);+ });++ it.each([+ ['nothing', {}],+ [+ 'an empty input next to a prompt',+ { input: [], prompt: 'Who owns Acme?' },+ ],+ [+ 'input and prompt',+ {+ input: [{ role: 'user' as const, content: 'Hello' }],+ prompt: 'Hello',+ },+ ],+ ['an empty input', { input: [] }],+ [+ 'a blank input message',+ { input: [{ role: 'user' as const, content: ' ' }] },+ ],+ ['an empty prompt', { prompt: '' }],+ ['empty messages', { messages: [] }],+ ])('should refuse %s', (_, sources) => {+ expect(() => resolveRunAgentMessagesOrThrow(sources)).toThrow(+ expect.objectContaining({ code: AiExceptionCode.INVALID_AGENT_INPUT }),+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.tsnew file mode 100644index 00000000000..f5607698322--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/add-additional-instructions-to-last-run-agent-message.util.ts@@ -0,0 +1,20 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type RunAgentMessage } from 'twenty-shared/application';++export const addAdditionalInstructionsToLastRunAgentMessage = ({+ messages,+ additionalInstructions,+}: {+ messages: RunAgentMessage[];+ additionalInstructions: string;+}): RunAgentMessage[] =>+ messages.map((message, index) =>+ index === messages.length - 1+ ? {+ ...message,+ content: isNonEmptyString(message.content)+ ? `${additionalInstructions}\n\n${message.content}`+ : additionalInstructions,+ }+ : message,+ );diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util.tsnew file mode 100644index 00000000000..c9bb55cceda--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util.ts@@ -0,0 +1,14 @@+import { v5 } from 'uuid';++import { AGENT_RUN_THREAD_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-thread-id-namespace.const';++export const buildAgentRunThreadId = ({+ applicationId,+ agentId,+ threadKey,+}: {+ applicationId: string;+ agentId: string;+ threadKey: string;+}): string =>+ v5(`${applicationId}:${agentId}:${threadKey}`, AGENT_RUN_THREAD_ID_NAMESPACE);diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.tsnew file mode 100644index 00000000000..764fe46f96c--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts@@ -0,0 +1,61 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type RunAgentMessage } from 'twenty-shared/application';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';++import {+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';++const isBlankMessage = (message: RunAgentMessage): boolean =>+ !isNonEmptyString(message.content.trim()) &&+ !isNonEmptyArray(message.attachments);++// GraphQL cannot express XOR+export const resolveRunAgentMessagesOrThrow = ({+ input,+ prompt,+ messages,+}: {+ input?: RunAgentMessage[] | null;+ prompt?: string | null;+ messages?: RunAgentMessage[] | null;+}): RunAgentMessage[] => {+ if ([input, prompt, messages].filter(isDefined).length !== 1) {+ throw new AiException(+ 'Provide exactly one of input, prompt or messages',+ AiExceptionCode.INVALID_AGENT_INPUT,+ );+ }++ if (isDefined(prompt)) {+ if (!isNonEmptyString(prompt)) {+ throw new AiException(+ 'prompt must not be empty',+ AiExceptionCode.INVALID_AGENT_INPUT,+ );+ }++ return [{ role: 'user', content: prompt }];+ }++ if (isDefined(messages)) {+ if (!isNonEmptyArray(messages)) {+ throw new AiException(+ 'messages must not be empty',+ AiExceptionCode.INVALID_AGENT_INPUT,+ );+ }++ return messages;+ }++ if (!isNonEmptyArray(input) || input.some(isBlankMessage)) {+ throw new AiException(+ 'input must hold messages with content or attachments',+ AiExceptionCode.INVALID_AGENT_INPUT,+ );+ }++ return input;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.tsindex 2d604c0c939..ccbaced6f45 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts@@ -1,5 +1,7 @@import { AGENT_HISTORY_OBJECT_NAMES } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-history-object-names.constant';import { Module } from '@nestjs/common';+import { FileUrlModule } from 'src/engine/core-modules/file/file-url/file-url.module';+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 { AgentHistoryTransactionService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service';import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';@@ -18,14 +20,17 @@ const REPOSITORY_PROVIDERS = AGENT_HISTORY_OBJECT_NAMES.map((objectName) => ({}));@Module({+ imports: [FileUrlModule],providers: [AgentHistoryWorkspaceStorageService,AgentHistoryTransactionService,+ AgentConversationReaderService,AgentConversationWriterService,...REPOSITORY_PROVIDERS,],exports: [AgentHistoryWorkspaceStorageService,+ AgentConversationReaderService,AgentConversationWriterService,...REPOSITORY_PROVIDERS,],diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.tsnew file mode 100644index 00000000000..72dd16b5243--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts@@ -0,0 +1,213 @@+import { FileFolder } from 'twenty-shared/types';++import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';++const WORKSPACE_ID = 'workspace-id';+const THREAD_ID = 'thread-id';+const APPLICATION_ID = 'application-id';+const MEMBER_A = 'user-workspace-a';+const MEMBER_B = 'user-workspace-b';++const buildTurn = ({+ turnId,+ senderUserWorkspaceId,+ question,+ answer,+}: {+ turnId: string;+ senderUserWorkspaceId: string | null;+ question: string;+ answer: string;+}) => [+ {+ id: `${turnId}-user`,+ turnId,+ role: 'user',+ senderUserWorkspaceId,+ senderApplicationId: APPLICATION_ID,+ parts: [{ type: 'text', textContent: question }],+ },+ {+ id: `${turnId}-assistant`,+ turnId,+ role: 'assistant',+ senderUserWorkspaceId: null,+ senderApplicationId: null,+ parts: [+ {+ type: 'tool-find_companies',+ toolCallId: `${turnId}-call`,+ toolInput: {},+ toolOutput: { records: [{ name: 'Private Co' }] },+ state: 'output-available',+ },+ { type: 'text', textContent: answer },+ ],+ },+];++const buildService = (messages: unknown[]) => {+ const messageRepository = { find: jest.fn().mockResolvedValue(messages) };+ const fileUrlService = {+ signFileByIdUrl: jest+ .fn()+ .mockImplementation(({ fileId }) => `https://files/${fileId}`),+ };++ const service = new AgentConversationReaderService(+ messageRepository as never,+ fileUrlService as never,+ );++ return { service, messageRepository, fileUrlService };+};++const buildFileMessage = ({+ turnId,+ senderUserWorkspaceId,+}: {+ turnId: string;+ senderUserWorkspaceId: string;+}) => ({+ id: `${turnId}-user`,+ turnId,+ role: 'user',+ senderUserWorkspaceId,+ senderApplicationId: APPLICATION_ID,+ parts: [+ { type: 'text', textContent: 'What does this deck say?' },+ {+ type: 'file',+ fileId: 'file-1',+ fileFilename: 'deck.pdf',+ file: { mimeType: 'application/pdf' },+ },+ ],+});++const getPartTypes = (message: { parts: { type: string }[] }) =>+ message.parts.map((part) => part.type);++describe('AgentConversationReaderService', () => {+ it('keeps every part when no actor is given', async () => {+ const { service } = buildService([+ ...buildTurn({+ turnId: 'turn-1',+ senderUserWorkspaceId: MEMBER_A,+ question: 'Who is our biggest customer?',+ answer: 'Private Co',+ }),+ ]);++ const messages = await service.loadMessages({+ workspaceId: WORKSPACE_ID,+ threadId: THREAD_ID,+ });++ expect(getPartTypes(messages[1])).toEqual(['tool-find_companies', 'text']);+ });++ it('reduces turns sent by someone else to their text', async () => {+ const { service } = buildService([+ ...buildTurn({+ turnId: 'turn-1',+ senderUserWorkspaceId: MEMBER_A,+ question: 'Who is our biggest customer?',+ answer: 'Private Co',+ }),+ ...buildTurn({+ turnId: 'turn-2',+ senderUserWorkspaceId: MEMBER_B,+ question: 'And the second one?',+ answer: 'Other Co',+ }),+ ]);++ const messages = await service.loadMessages({+ workspaceId: WORKSPACE_ID,+ threadId: THREAD_ID,+ actor: { type: 'user', userWorkspaceId: MEMBER_B },+ });++ expect(messages.map(getPartTypes)).toEqual([+ ['text'],+ ['text'],+ ['text'],+ ['tool-find_companies', 'text'],+ ]);+ });++ it('treats a member and the application acting alone as different actors', async () => {+ const { service } = buildService([+ ...buildTurn({+ turnId: 'turn-1',+ senderUserWorkspaceId: MEMBER_A,+ question: 'Who is our biggest customer?',+ answer: 'Private Co',+ }),+ ...buildTurn({+ turnId: 'turn-2',+ senderUserWorkspaceId: null,+ question: 'Summarize this thread',+ answer: 'Done',+ }),+ ]);++ const messages = await service.loadMessages({+ workspaceId: WORKSPACE_ID,+ threadId: THREAD_ID,+ actor: { type: 'application', applicationId: APPLICATION_ID },+ });++ expect(messages.map(getPartTypes)).toEqual([+ ['text'],+ ['text'],+ ['text'],+ ['tool-find_companies', 'text'],+ ]);+ });++ it('loads files with their type and signs them for the actor', async () => {+ const { service, messageRepository, fileUrlService } = buildService([+ buildFileMessage({ turnId: 'turn-1', senderUserWorkspaceId: MEMBER_A }),+ ]);++ const messages = await service.loadMessages({+ workspaceId: WORKSPACE_ID,+ threadId: THREAD_ID,+ actor: { type: 'user', userWorkspaceId: MEMBER_A },+ });++ expect(messageRepository.find).toHaveBeenCalledWith(+ WORKSPACE_ID,+ expect.objectContaining({ relations: ['parts', 'parts.file'] }),+ );+ expect(fileUrlService.signFileByIdUrl).toHaveBeenCalledWith({+ fileId: 'file-1',+ workspaceId: WORKSPACE_ID,+ fileFolder: FileFolder.AgentChat,+ });+ expect(messages[0].parts[1]).toEqual({+ type: 'file',+ fileId: 'file-1',+ filename: 'deck.pdf',+ mediaType: 'application/pdf',+ url: 'https://files/file-1',+ });+ });++ it('drops the files of turns sent by someone else without signing them', async () => {+ const { service, fileUrlService } = buildService([+ buildFileMessage({ turnId: 'turn-1', senderUserWorkspaceId: MEMBER_A }),+ ]);++ const messages = await service.loadMessages({+ workspaceId: WORKSPACE_ID,+ threadId: THREAD_ID,+ actor: { type: 'user', userWorkspaceId: MEMBER_B },+ });++ expect(getPartTypes(messages[0])).toEqual(['text']);+ expect(fileUrlService.signFileByIdUrl).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.tsnew file mode 100644index 00000000000..c1d4edf284d--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts@@ -0,0 +1,91 @@+import { Injectable } from '@nestjs/common';++import {+ type ExtendedUIMessage,+ type ExtendedUIMessagePart,+ isExtendedFileUIPart,+} from 'twenty-shared/ai';+import { FileFolder } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';+import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';+import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartsToUIMessageParts';+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 { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';+import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';+import { findTurnIdsActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util';++@Injectable()+export class AgentConversationReaderService {+ constructor(+ @InjectAgentHistoryRepository('agentMessage')+ private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,+ private readonly fileUrlService: FileUrlService,+ ) {}++ async loadMessages({+ workspaceId,+ threadId,+ actor,+ }: {+ workspaceId: string;+ threadId: string;+ actor?: AgentConversationActor;+ }): Promise<ExtendedUIMessage[]> {+ const messages = await this.messageRepository.find(workspaceId, {+ where: { threadId },+ order: {+ processedAt: { order: 'ASC', nulls: 'NULLS LAST' },+ createdAt: 'ASC',+ },+ relations: ['parts', 'parts.file'],+ });++ const turnIdsActedByOthers = isDefined(actor)+ ? findTurnIdsActedByOthers({ messages, actor })+ : new Set<string>();++ return Promise.all(+ messages.map(async (message) => {+ const parts = finalizeDanglingToolParts(+ mapDBPartsToUIMessageParts(message.parts ?? []),+ );+ const isActedByOthers =+ isDefined(message.turnId) && turnIdsActedByOthers.has(message.turnId);++ return {+ id: message.id,+ role: message.role as ExtendedUIMessage['role'],+ parts: isActedByOthers+ ? parts.filter((part) => part.type === 'text')+ : await this.signFileParts({ workspaceId, parts }),+ };+ }),+ );+ }++ private signFileParts({+ workspaceId,+ parts,+ }: {+ workspaceId: string;+ parts: ExtendedUIMessagePart[];+ }): Promise<ExtendedUIMessagePart[]> {+ return Promise.all(+ parts.map(async (part) =>+ isExtendedFileUIPart(part)+ ? {+ ...part,+ url: await this.fileUrlService.signFileByIdUrl({+ fileId: part.fileId,+ workspaceId,+ fileFolder: FileFolder.AgentChat,+ }),+ }+ : part,+ ),+ );+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.tsindex 3a896a0e494..314808d1721 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts@@ -6,12 +6,16 @@ import { type ExtendedUIMessagePart } from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { IsNull } from 'typeorm';-import { type AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';+import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';+import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';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 { AgentHistoryTransactionService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service';+import { type AgentHistoryTransactionScope } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type';+import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';import {AiException,AiExceptionCode,@@ -25,17 +29,34 @@ export class AgentConversationWriterService {private readonly transactionService: AgentHistoryTransactionService,) {}+ runInTransaction<TResult>(+ workspaceId: string,+ work: (scope: AgentHistoryTransactionScope) => Promise<TResult>,+ ): Promise<TResult> {+ return this.transactionService.run(workspaceId, work);+ }+async insertTurn({workspaceId,threadId,agentId,id,+ scope,}: {workspaceId: string;threadId: string;agentId: string | null;id?: string;+ scope?: AgentHistoryTransactionScope;}): Promise<string> {+ if (isDefined(scope)) {+ const turnId = id ?? randomUUID();++ await scope.insert('agentTurn', { id: turnId, threadId, agentId });++ return turnId;+ }+const turnInsertResult = await this.turnRepository.insert(workspaceId, {...(isDefined(id) ? { id } : {}),threadId,@@ -62,6 +83,7 @@ export class AgentConversationWriterService {isAwaitingAnswer,processedAt,parts,+ scope,}: {workspaceId: string;id?: string;@@ -75,11 +97,12 @@ export class AgentConversationWriterService {isAwaitingAnswer?: boolean;processedAt?: Date;parts: ExtendedUIMessagePart[];+ scope?: AgentHistoryTransactionScope;}): Promise<string> {const messageId = id ?? randomUUID();- await this.transactionService.run(workspaceId, async (scope) => {- await scope.insert('agentMessage', {+ const write = async (transactionScope: AgentHistoryTransactionScope) => {+ await transactionScope.insert('agentMessage', {id: messageId,threadId,turnId,@@ -98,14 +121,14 @@ export class AgentConversationWriterService {);if (dbParts.length > 0) {- await scope.insert('agentMessagePart', dbParts);+ await transactionScope.insert('agentMessagePart', dbParts);}if (!isAwaitingAnswer) {return;}- const claimedThreadCount = await scope.update(+ const claimedThreadCount = await transactionScope.update('agentChatThread',{ id: threadId, pendingQuestionMessageId: IsNull() },{ pendingQuestionMessageId: messageId },@@ -117,8 +140,57 @@ export class AgentConversationWriterService {AiExceptionCode.THREAD_AWAITING_ANSWER,);}- });+ };++ if (isDefined(scope)) {+ await write(scope);+ } else {+ await this.transactionService.run(workspaceId, write);+ }return messageId;}++ // One unanswerable call would keep the conversation waiting forever, so it is recorded as not waiting+ async insertExecutionReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ execution,+ scope,+ }: {+ workspaceId: string;+ threadId: string;+ turnId: string;+ agentId: string | null;+ execution: RecordableAgentExecution;+ scope?: AgentHistoryTransactionScope;+ }): Promise<{ isAwaitingAnswer: boolean }> {+ const replyParts = mapAiStepsToUiMessageParts(execution.steps ?? []);++ if (replyParts.length === 0) {+ return { isAwaitingAnswer: false };+ }++ const awaitingParts = findAwaitingPausingToolParts(replyParts);+ const isAwaitingAnswer =+ execution.isPaused === true &&+ awaitingParts.length > 0 &&+ awaitingParts.every(({ isAnswerable }) => isAnswerable);++ await this.insertMessage({+ workspaceId,+ threadId,+ turnId,+ role: AgentMessageRole.ASSISTANT,+ agentId,+ senderUserWorkspaceId: null,+ isAwaitingAnswer,+ parts: replyParts,+ scope,+ });++ return { isAwaitingAnswer };+ }}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.tsnew file mode 100644index 00000000000..a4b4567a65e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.ts@@ -0,0 +1,3 @@+export type AgentConversationActor =+ | { type: 'user'; userWorkspaceId: string }+ | { type: 'application'; applicationId: string };diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type.tsnew file mode 100644index 00000000000..4d01346e3b2--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type.ts@@ -0,0 +1,6 @@+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';++export type RecordableAgentExecution = {+ steps?: Pick<NonNullable<AgentExecutionResult['steps']>[number], 'content'>[];+ isPaused?: boolean;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.tsnew file mode 100644index 00000000000..943d8c409c8--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.ts@@ -0,0 +1,64 @@+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { findTurnIdsActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util';++const APPLICATION_ID = 'application-id';++const userMessage = (+ turnId: string | null,+ senderUserWorkspaceId: string | null,+) => ({+ turnId,+ role: AgentMessageRole.USER,+ senderUserWorkspaceId,+ senderApplicationId: APPLICATION_ID,+});++const assistantMessage = (turnId: string | null) => ({+ turnId,+ role: AgentMessageRole.ASSISTANT,+ senderUserWorkspaceId: null,+ senderApplicationId: null,+});++describe('findTurnIdsActedByOthers', () => {+ it('should keep the turns a member sent and flag the others', () => {+ expect(+ findTurnIdsActedByOthers({+ messages: [+ userMessage('turn-1', 'member-a'),+ assistantMessage('turn-1'),+ userMessage('turn-2', 'member-b'),+ assistantMessage('turn-2'),+ userMessage('turn-3', null),+ assistantMessage('turn-3'),+ ],+ actor: { type: 'user', userWorkspaceId: 'member-a' },+ }),+ ).toEqual(new Set(['turn-2', 'turn-3']));+ });++ it('should keep the turns the application sent on its own', () => {+ expect(+ findTurnIdsActedByOthers({+ messages: [+ userMessage('turn-1', 'member-a'),+ userMessage('turn-2', null),+ ],+ actor: { type: 'application', applicationId: APPLICATION_ID },+ }),+ ).toEqual(new Set(['turn-1']));+ });++ it('should flag turns with no request or a request from someone else', () => {+ expect(+ findTurnIdsActedByOthers({+ messages: [+ assistantMessage('turn-1'),+ userMessage('turn-2', 'member-a'),+ userMessage('turn-2', 'member-b'),+ ],+ actor: { type: 'user', userWorkspaceId: 'member-a' },+ }),+ ).toEqual(new Set(['turn-1', 'turn-2']));+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.tsnew file mode 100644index 00000000000..a4158ac93ae--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.ts@@ -0,0 +1,56 @@+import { isDefined } from 'twenty-shared/utils';++import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';++type AgentMessageSender = Pick<+ AgentMessageWorkspaceEntity,+ 'turnId' | 'role' | 'senderUserWorkspaceId' | 'senderApplicationId'+>;++const isSentByActor = (+ message: AgentMessageSender,+ actor: AgentConversationActor,+): boolean =>+ actor.type === 'user'+ ? message.senderUserWorkspaceId === actor.userWorkspaceId+ : message.senderApplicationId === actor.applicationId &&+ !isDefined(message.senderUserWorkspaceId);++export const findTurnIdsActedByOthers = ({+ messages,+ actor,+}: {+ messages: AgentMessageSender[];+ actor: AgentConversationActor;+}): Set<string> => {+ const turnIds = new Set<string>();+ const turnIdsActedByActor = new Set<string>();+ const turnIdsActedByOthers = new Set<string>();++ for (const message of messages) {+ if (!isDefined(message.turnId)) {+ continue;+ }++ turnIds.add(message.turnId);++ if (message.role !== AgentMessageRole.USER) {+ continue;+ }++ if (isSentByActor(message, actor)) {+ turnIdsActedByActor.add(message.turnId);+ } else {+ turnIdsActedByOthers.add(message.turnId);+ }+ }++ return new Set(+ [...turnIds].filter(+ (turnId) =>+ turnIdsActedByOthers.has(turnId) || !turnIdsActedByActor.has(turnId),+ ),+ );+};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.tsindex 100612bea8d..1680cd7ff0a 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,6 +4,7 @@ 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';@@ -19,6 +20,7 @@ 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.tsindex 62df4465c7f..96c41b9f507 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@@ -15,6 +15,7 @@ import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-ageimport { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.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 { 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';@@ -46,6 +47,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {private readonly workflowExecutionContextService: WorkflowExecutionContextService,private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,+ private readonly conversationReaderService: AgentConversationReaderService,@InjectWorkspaceScopedRepository(AgentEntity)private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,) {}@@ -151,11 +153,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {...(isDefined(resumedThreadId)? {messages: [],- priorModelMessages:- await this.workflowAgentConversationService.loadModelMessages({- workspaceId,- threadId: resumedThreadId,- }),+ priorMessages: await this.conversationReaderService.loadMessages({+ workspaceId,+ threadId: resumedThreadId,+ }),}: { messages: [{ role: 'user', content: resolvedPrompt }] }),baseSystemPrompt: isAskingQuestionsAlloweddiff --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.tsindex 222618cabb6..1de28808576 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,8 +1,6 @@import { Injectable } from '@nestjs/common';-import { convertToModelMessages, type ModelMessage } from 'ai';import {- type ExtendedUIMessage,type ExtendedUIMessagePart,REQUEST_FORM_TOOL_NAME,type RequestFormToolInput,@@ -10,23 +8,13 @@ import {import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';-import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';-import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';-import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';-import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';-import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartsToUIMessageParts';-import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';import { buildRequestFormPendingOutput } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';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 { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';+import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';-export type RecordedExecutionResult = {- steps?: Pick<NonNullable<AgentExecutionResult['steps']>[number], 'content'>[];- isPaused?: boolean;-};-export type RecordedConversation = {threadId: string;isAwaitingAnswer: boolean;@@ -39,8 +27,6 @@ export class WorkflowAgentConversationWorkspaceService {constructor(@InjectAgentHistoryRepository('agentChatThread')private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,- @InjectAgentHistoryRepository('agentMessage')- private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,private readonly conversationWriterService: AgentConversationWriterService,private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,) {}@@ -62,7 +48,7 @@ export class WorkflowAgentConversationWorkspaceService {agentId: string | null;prompt: string;initiatorUserWorkspaceId: string | null;- executionResult: RecordedExecutionResult;+ executionResult: RecordableAgentExecution;}): Promise<RecordedConversation> {const { threadId, turnId } = await this.openConversation({workspaceId,@@ -82,13 +68,14 @@ export class WorkflowAgentConversationWorkspaceService {parts: [{ type: 'text', text: prompt }],});- const isAwaitingAnswer = await this.recordReply({- workspaceId,- threadId,- turnId,- agentId,- executionResult,- });+ const { isAwaitingAnswer } =+ await this.conversationWriterService.insertExecutionReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ execution: executionResult,+ });return { threadId, isAwaitingAnswer };}@@ -145,7 +132,7 @@ export class WorkflowAgentConversationWorkspaceService {workspaceId: string;threadId: string;agentId: string | null;- executionResult: RecordedExecutionResult;+ executionResult: RecordableAgentExecution;}): Promise<RecordedConversation> {const turnId = await this.conversationWriterService.insertTurn({workspaceId,@@ -153,84 +140,18 @@ export class WorkflowAgentConversationWorkspaceService {agentId,});- const isAwaitingAnswer = await this.recordReply({- workspaceId,- threadId,- turnId,- agentId,- executionResult,- });+ const { isAwaitingAnswer } =+ await this.conversationWriterService.insertExecutionReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ execution: executionResult,+ });return { threadId, isAwaitingAnswer };}- async loadModelMessages({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): Promise<ModelMessage[]> {- const messages = await this.messageRepository.find(workspaceId, {- where: { threadId },- order: {- processedAt: { order: 'ASC', nulls: 'NULLS LAST' },- createdAt: 'ASC',- },- relations: ['parts'],- });-- const uiMessages: ExtendedUIMessage[] = messages.map((message) => ({- id: message.id,- role: message.role as ExtendedUIMessage['role'],- parts: finalizeDanglingToolParts(- mapDBPartsToUIMessageParts(message.parts ?? []),- ),- }));-- return convertToModelMessages(uiMessages);- }-- // One unanswerable call would keep the step waiting forever, so the step fails instead- private async recordReply({- workspaceId,- threadId,- turnId,- agentId,- executionResult,- }: {- workspaceId: string;- threadId: string;- turnId: string;- agentId: string | null;- executionResult: RecordedExecutionResult;- }): Promise<boolean> {- const replyParts = mapAiStepsToUiMessageParts(executionResult.steps ?? []);-- if (replyParts.length === 0) {- return false;- }-- const awaitingParts = findAwaitingPausingToolParts(replyParts);- const isAwaitingAnswer =- executionResult.isPaused === true &&- awaitingParts.length > 0 &&- awaitingParts.every(({ isAnswerable }) => isAnswerable);-- await this.conversationWriterService.insertMessage({- workspaceId,- threadId,- turnId,- role: AgentMessageRole.ASSISTANT,- agentId,- senderUserWorkspaceId: null,- isAwaitingAnswer,- parts: replyParts,- });-- return isAwaitingAnswer;- }-private async openConversation({workspaceId,workflowRunId,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.tsindex bad814b5f32..2bcb24a6f99 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts@@ -1262,9 +1262,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const resumedWith = executeAgent.mock.calls[1][0];expect(resumedWith.messages).toEqual([]);- expect(JSON.stringify(resumedWith.priorModelMessages)).toContain(- 'Send it',- );+ expect(JSON.stringify(resumedWith.priorMessages)).toContain('Send it');const { messages, questionPart } = await getConversation(threadId);@@ -1371,7 +1369,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(executeAgent).toHaveBeenCalledTimes(2);expect(- JSON.stringify(executeAgent.mock.calls[1][0].priorModelMessages),+ JSON.stringify(executeAgent.mock.calls[1][0].priorMessages),).not.toContain('"pending"');});diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.tsindex 04bcbdebe61..d61227712e1 100644--- a/packages/twenty-shared/src/application/index.ts+++ b/packages/twenty-shared/src/application/index.ts@@ -204,6 +204,7 @@ export type { RunAgentMessageAttachment } from './runAgentMessageAttachmentType'export type {RunAgentMessageRole,RunAgentMessage,+ RunAgentThread,RunAgentInput,RunAgentResult,} from './runAgentType';diff --git a/packages/twenty-shared/src/application/runAgentType.ts b/packages/twenty-shared/src/application/runAgentType.tsindex 2622d20fd3a..8187b1bcc9e 100644--- a/packages/twenty-shared/src/application/runAgentType.ts+++ b/packages/twenty-shared/src/application/runAgentType.ts@@ -8,16 +8,39 @@ export type RunAgentMessage = {attachments?: RunAgentMessageAttachment[];};+export type RunAgentThread = {+ key: string;+ title?: string;+};+export type RunAgentInput = {agentUniversalIdentifier: string;+ additionalInstructions?: string;+ thread?: RunAgentThread;runAsWorkspaceMemberId?: string;} & (- | { prompt: string; messages?: never }- | { messages: RunAgentMessage[]; prompt?: never }+ | {+ input: string | RunAgentMessage[];+ prompt?: never;+ messages?: never;+ }+ | {+ /** @deprecated Use `input` instead. */+ prompt: string;+ input?: never;+ messages?: never;+ }+ | {+ /** @deprecated Use `input` instead. */+ messages: RunAgentMessage[];+ input?: never;+ prompt?: never;+ });export type RunAgentResult = {result: object | null;error: string | null;success: boolean;+ threadId: string | null;};