Skip to content

The open alternative to Salesforce, designed for AI.

feat: Implement AI Router for Dynamic Agent Selection (#15227)

Abdul Rahman32558673c65e
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 3fc95102089..9002294dd33 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -108,7 +108,6 @@ export type AgentChatMessagePart = {
export type AgentChatThread = {
__typename?: 'AgentChatThread';
- agentId: Scalars['UUID'];
createdAt: Scalars['DateTime'];
id: Scalars['UUID'];
title?: Maybe<Scalars['String']>;
@@ -728,10 +727,6 @@ export type CoreViewSort = {
workspaceId: Scalars['UUID'];
};
-export type CreateAgentChatThreadInput = {
- agentId: Scalars['UUID'];
-};
-
export type CreateAgentHandoffInput = {
description?: InputMaybe<Scalars['String']>;
fromAgentId: Scalars['UUID'];
@@ -1724,10 +1719,10 @@ export type Mutation = {
checkPublicDomainValidRecords?: Maybe<DomainValidRecords>;
checkoutSession: BillingSessionOutput;
computeStepOutputSchema: Scalars['JSON'];
- createAgentChatThread: AgentChatThread;
createAgentHandoff: Scalars['Boolean'];
createApiKey: ApiKey;
createApprovedAccessDomain: ApprovedAccessDomain;
+ createChatThread: AgentChatThread;
createCoreView: CoreView;
createCoreViewField: CoreViewField;
createCoreViewFilter: CoreViewFilter;
@@ -1942,11 +1937,6 @@ export type MutationComputeStepOutputSchemaArgs = {
};
-export type MutationCreateAgentChatThreadArgs = {
- input: CreateAgentChatThreadInput;
-};
-
-
export type MutationCreateAgentHandoffArgs = {
input: CreateAgentHandoffInput;
};
@@ -3106,12 +3096,12 @@ export type PublishServerlessFunctionInput = {
export type Query = {
__typename?: 'Query';
- agentChatMessages: Array<AgentChatMessage>;
- agentChatThread: AgentChatThread;
- agentChatThreads: Array<AgentChatThread>;
apiKey?: Maybe<ApiKey>;
apiKeys: Array<ApiKey>;
billingPortalSession: BillingSessionOutput;
+ chatMessages: Array<AgentChatMessage>;
+ chatThread: AgentChatThread;
+ chatThreads: Array<AgentChatThread>;
checkUserExists: CheckUserExistOutput;
checkWorkspaceInviteHashIsValid: WorkspaceInviteHashValidOutput;
currentUser: User;
@@ -3193,28 +3183,23 @@ export type Query = {
};
-export type QueryAgentChatMessagesArgs = {
- threadId: Scalars['UUID'];
-};
-
-
-export type QueryAgentChatThreadArgs = {
- id: Scalars['UUID'];
+export type QueryApiKeyArgs = {
+ input: GetApiKeyInput;
};
-export type QueryAgentChatThreadsArgs = {
- agentId: Scalars['UUID'];
+export type QueryBillingPortalSessionArgs = {
+ returnUrlPath?: InputMaybe<Scalars['String']>;
};
-export type QueryApiKeyArgs = {
- input: GetApiKeyInput;
+export type QueryChatMessagesArgs = {
+ threadId: Scalars['UUID'];
};
-export type QueryBillingPortalSessionArgs = {
- returnUrlPath?: InputMaybe<Scalars['String']>;
+export type QueryChatThreadArgs = {
+ id: Scalars['UUID'];
};
@@ -4346,6 +4331,7 @@ export type UpdateWorkspaceInput = {
isPublicInviteLinkEnabled?: InputMaybe<Scalars['Boolean']>;
isTwoFactorAuthenticationEnforced?: InputMaybe<Scalars['Boolean']>;
logo?: InputMaybe<Scalars['String']>;
+ routerModel?: InputMaybe<Scalars['String']>;
subdomain?: InputMaybe<Scalars['String']>;
trashRetentionDays?: InputMaybe<Scalars['Float']>;
};
@@ -4649,7 +4635,6 @@ export type Workspace = {
customDomain?: Maybe<Scalars['String']>;
databaseSchema: Scalars['String'];
databaseUrl: Scalars['String'];
- defaultAgent?: Maybe<Agent>;
defaultRole?: Maybe<Role>;
deletedAt?: Maybe<Scalars['DateTime']>;
displayName?: Maybe<Scalars['String']>;
@@ -4665,6 +4650,7 @@ export type Workspace = {
isTwoFactorAuthenticationEnforced: Scalars['Boolean'];
logo?: Maybe<Scalars['String']>;
metadataVersion: Scalars['Float'];
+ routerModel: Scalars['String'];
subdomain: Scalars['String'];
trashRetentionDays: Scalars['Float'];
updatedAt: Scalars['DateTime'];
@@ -4788,13 +4774,6 @@ export type AssignRoleToAgentMutationVariables = Exact<{
export type AssignRoleToAgentMutation = { __typename?: 'Mutation', assignRoleToAgent: boolean };
-export type CreateAgentChatThreadMutationVariables = Exact<{
- input: CreateAgentChatThreadInput;
-}>;
-
-
-export type CreateAgentChatThreadMutation = { __typename?: 'Mutation', createAgentChatThread: { __typename?: 'AgentChatThread', id: string, agentId: string, title?: string | null, createdAt: string, updatedAt: string } };
-
export type CreateAgentHandoffMutationVariables = Exact<{
input: CreateAgentHandoffInput;
}>;
@@ -4802,6 +4781,11 @@ export type CreateAgentHandoffMutationVariables = Exact<{
export type CreateAgentHandoffMutation = { __typename?: 'Mutation', createAgentHandoff: boolean };
+export type CreateChatThreadMutationVariables = Exact<{ [key: string]: never; }>;
+
+
+export type CreateChatThreadMutation = { __typename?: 'Mutation', createChatThread: { __typename?: 'AgentChatThread', id: string, title?: string | null, createdAt: string, updatedAt: string } };
+
export type CreateOneAgentMutationVariables = Exact<{
input: CreateAgentInput;
}>;
@@ -4863,19 +4847,17 @@ export type FindOneAgentQueryVariables = Exact<{
export type FindOneAgentQuery = { __typename?: 'Query', findOneAgent: { __typename?: 'Agent', id: string, name: string, label: string, description?: string | null, icon?: string | null, prompt: string, modelId: string, responseFormat?: any | null, roleId?: string | null, isCustom: boolean, modelConfiguration?: any | null, applicationId?: string | null, createdAt: string, updatedAt: string } };
-export type GetAgentChatMessagesQueryVariables = Exact<{
+export type GetChatMessagesQueryVariables = Exact<{
threadId: Scalars['UUID'];
}>;
-export type GetAgentChatMessagesQuery = { __typename?: 'Query', agentChatMessages: Array<{ __typename?: 'AgentChatMessage', id: string, threadId: string, role: string, createdAt: string, parts: Array<{ __typename?: 'AgentChatMessagePart', id: string, messageId: string, orderIndex: number, type: string, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, state?: string | null, errorMessage?: string | null, errorDetails?: any | null, sourceUrlSourceId?: string | null, sourceUrlUrl?: string | null, sourceUrlTitle?: string | null, sourceDocumentSourceId?: string | null, sourceDocumentMediaType?: string | null, sourceDocumentTitle?: string | null, sourceDocumentFilename?: string | null, fileMediaType?: string | null, fileFilename?: string | null, fileUrl?: string | null, providerMetadata?: any | null, createdAt: string }> }> };
+export type GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{ __typename?: 'AgentChatMessage', id: string, threadId: string, role: string, createdAt: string, parts: Array<{ __typename?: 'AgentChatMessagePart', id: string, messageId: string, orderIndex: number, type: string, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, state?: string | null, errorMessage?: string | null, errorDetails?: any | null, sourceUrlSourceId?: string | null, sourceUrlUrl?: string | null, sourceUrlTitle?: string | null, sourceDocumentSourceId?: string | null, sourceDocumentMediaType?: string | null, sourceDocumentTitle?: string | null, sourceDocumentFilename?: string | null, fileMediaType?: string | null, fileFilename?: string | null, fileUrl?: string | null, providerMetadata?: any | null, createdAt: string }> }> };
-export type GetAgentChatThreadsQueryVariables = Exact<{
- agentId: Scalars['UUID'];
-}>;
+export type GetChatThreadsQueryVariables = Exact<{ [key: string]: never; }>;
-export type GetAgentChatThreadsQuery = { __typename?: 'Query', agentChatThreads: Array<{ __typename?: 'AgentChatThread', id: string, agentId: string, title?: string | null, createdAt: string, updatedAt: string }> };
+export type GetChatThreadsQuery = { __typename?: 'Query', chatThreads: Array<{ __typename?: 'AgentChatThread', id: string, title?: string | null, createdAt: string, updatedAt: string }> };
export type TrackAnalyticsMutationVariables = Exact<{
type: AnalyticsType;
@@ -5808,7 +5790,7 @@ export type BillingSubscriptionFragmentFragment = { __typename?: 'BillingSubscri
export type CurrentBillingSubscriptionFragmentFragment = { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItemDTO', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null };
-export type UserQueryFragmentFragment = { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodDTO', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, subdomain: string, hasValidEnterpriseKey: boolean, customDomain?: string | null, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlagDTO', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItemDTO', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null, defaultAgent?: { __typename?: 'Agent', id: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
+export type UserQueryFragmentFragment = { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodDTO', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, subdomain: string, hasValidEnterpriseKey: boolean, customDomain?: string | null, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, routerModel: string, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlagDTO', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItemDTO', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
export type WorkspaceUrlsFragmentFragment = { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null };
@@ -5827,7 +5809,7 @@ export type UploadProfilePictureMutation = { __typename?: 'Mutation', uploadProf
export type GetCurrentUserQueryVariables = Exact<{ [key: string]: never; }>;
-export type GetCurrentUserQuery = { __typename?: 'Query', currentUser: { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodDTO', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, subdomain: string, hasValidEnterpriseKey: boolean, customDomain?: string | null, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlagDTO', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItemDTO', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null, defaultAgent?: { __typename?: 'Agent', id: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
+export type GetCurrentUserQuery = { __typename?: 'Query', currentUser: { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodDTO', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, subdomain: string, hasValidEnterpriseKey: boolean, customDomain?: string | null, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, routerModel: string, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlagDTO', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItemDTO', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
export type ViewFieldFragmentFragment = { __typename?: 'CoreViewField', id: string, fieldMetadataId: string, viewId: string, isVisible: boolean, position: number, size: number, aggregateOperation?: AggregateOperations | null, createdAt: string, updatedAt: string, deletedAt?: string | null };
@@ -6792,9 +6774,7 @@ export const UserQueryFragmentFragmentDoc = gql`
defaultRole {
...RoleFragment
}
- defaultAgent {
- id
- }
+ routerModel
isTwoFactorAuthenticationEnforced
trashRetentionDays
}
@@ -6946,74 +6926,72 @@ export function useAssignRoleToAgentMutation(baseOptions?: Apollo.MutationHookOp
export type AssignRoleToAgentMutationHookResult = ReturnType<typeof useAssignRoleToAgentMutation>;
export type AssignRoleToAgentMutationResult = Apollo.MutationResult<AssignRoleToAgentMutation>;
export type AssignRoleToAgentMutationOptions = Apollo.BaseMutationOptions<AssignRoleToAgentMutation, AssignRoleToAgentMutationVariables>;
-export const CreateAgentChatThreadDocument = gql`
- mutation CreateAgentChatThread($input: CreateAgentChatThreadInput!) {
- createAgentChatThread(input: $input) {
- id
- agentId
- title
- createdAt
- updatedAt
- }
+export const CreateAgentHandoffDocument = gql`
+ mutation CreateAgentHandoff($input: CreateAgentHandoffInput!) {
+ createAgentHandoff(input: $input)
}
`;
-export type CreateAgentChatThreadMutationFn = Apollo.MutationFunction<CreateAgentChatThreadMutation, CreateAgentChatThreadMutationVariables>;
+export type CreateAgentHandoffMutationFn = Apollo.MutationFunction<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>;
/**
- * __useCreateAgentChatThreadMutation__
+ * __useCreateAgentHandoffMutation__
*
- * To run a mutation, you first call `useCreateAgentChatThreadMutation` within a React component and pass it any options that fit your needs.
- * When your component renders, `useCreateAgentChatThreadMutation` returns a tuple that includes:
+ * To run a mutation, you first call `useCreateAgentHandoffMutation` within a React component and pass it any options that fit your needs.
+ * When your component renders, `useCreateAgentHandoffMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
- * const [createAgentChatThreadMutation, { data, loading, error }] = useCreateAgentChatThreadMutation({
+ * const [createAgentHandoffMutation, { data, loading, error }] = useCreateAgentHandoffMutation({
* variables: {
* input: // value for 'input'
* },
* });
*/
-export function useCreateAgentChatThreadMutation(baseOptions?: Apollo.MutationHookOptions<CreateAgentChatThreadMutation, CreateAgentChatThreadMutationVariables>) {
+export function useCreateAgentHandoffMutation(baseOptions?: Apollo.MutationHookOptions<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useMutation<CreateAgentChatThreadMutation, CreateAgentChatThreadMutationVariables>(CreateAgentChatThreadDocument, options);
+ return Apollo.useMutation<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>(CreateAgentHandoffDocument, options);
}
-export type CreateAgentChatThreadMutationHookResult = ReturnType<typeof useCreateAgentChatThreadMutation>;
-export type CreateAgentChatThreadMutationResult = Apollo.MutationResult<CreateAgentChatThreadMutation>;
-export type CreateAgentChatThreadMutationOptions = Apollo.BaseMutationOptions<CreateAgentChatThreadMutation, CreateAgentChatThreadMutationVariables>;
-export const CreateAgentHandoffDocument = gql`
- mutation CreateAgentHandoff($input: CreateAgentHandoffInput!) {
- createAgentHandoff(input: $input)
+export type CreateAgentHandoffMutationHookResult = ReturnType<typeof useCreateAgentHandoffMutation>;
+export type CreateAgentHandoffMutationResult = Apollo.MutationResult<CreateAgentHandoffMutation>;
+export type CreateAgentHandoffMutationOptions = Apollo.BaseMutationOptions<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>;
+export const CreateChatThreadDocument = gql`
+ mutation CreateChatThread {
+ createChatThread {
+ id
+ title
+ createdAt
+ updatedAt
+ }
}
`;
-export type CreateAgentHandoffMutationFn = Apollo.MutationFunction<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>;
+export type CreateChatThreadMutationFn = Apollo.MutationFunction<CreateChatThreadMutation, CreateChatThreadMutationVariables>;
/**
- * __useCreateAgentHandoffMutation__
+ * __useCreateChatThreadMutation__
*
- * To run a mutation, you first call `useCreateAgentHandoffMutation` within a React component and pass it any options that fit your needs.
- * When your component renders, `useCreateAgentHandoffMutation` returns a tuple that includes:
+ * To run a mutation, you first call `useCreateChatThreadMutation` within a React component and pass it any options that fit your needs.
+ * When your component renders, `useCreateChatThreadMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
- * const [createAgentHandoffMutation, { data, loading, error }] = useCreateAgentHandoffMutation({
+ * const [createChatThreadMutation, { data, loading, error }] = useCreateChatThreadMutation({
* variables: {
- * input: // value for 'input'
* },
* });
*/
-export function useCreateAgentHandoffMutation(baseOptions?: Apollo.MutationHookOptions<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>) {
+export function useCreateChatThreadMutation(baseOptions?: Apollo.MutationHookOptions<CreateChatThreadMutation, CreateChatThreadMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useMutation<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>(CreateAgentHandoffDocument, options);
+ return Apollo.useMutation<CreateChatThreadMutation, CreateChatThreadMutationVariables>(CreateChatThreadDocument, options);
}
-export type CreateAgentHandoffMutationHookResult = ReturnType<typeof useCreateAgentHandoffMutation>;
-export type CreateAgentHandoffMutationResult = Apollo.MutationResult<CreateAgentHandoffMutation>;
-export type CreateAgentHandoffMutationOptions = Apollo.BaseMutationOptions<CreateAgentHandoffMutation, CreateAgentHandoffMutationVariables>;
+export type CreateChatThreadMutationHookResult = ReturnType<typeof useCreateChatThreadMutation>;
+export type CreateChatThreadMutationResult = Apollo.MutationResult<CreateChatThreadMutation>;
+export type CreateChatThreadMutationOptions = Apollo.BaseMutationOptions<CreateChatThreadMutation, CreateChatThreadMutationVariables>;
export const CreateOneAgentDocument = gql`
mutation CreateOneAgent($input: CreateAgentInput!) {
createOneAgent(input: $input) {
@@ -7336,9 +7314,9 @@ export function useFindOneAgentLazyQuery(baseOptions?: Apollo.LazyQueryHookOptio
export type FindOneAgentQueryHookResult = ReturnType<typeof useFindOneAgentQuery>;
export type FindOneAgentLazyQueryHookResult = ReturnType<typeof useFindOneAgentLazyQuery>;
export type FindOneAgentQueryResult = Apollo.QueryResult<FindOneAgentQuery, FindOneAgentQueryVariables>;
-export const GetAgentChatMessagesDocument = gql`
- query GetAgentChatMessages($threadId: UUID!) {
- agentChatMessages(threadId: $threadId) {
+export const GetChatMessagesDocument = gql`
+ query GetChatMessages($threadId: UUID!) {
+ chatMessages(threadId: $threadId) {
id
threadId
role
@@ -7375,37 +7353,36 @@ export const GetAgentChatMessagesDocument = gql`
`;
/**
- * __useGetAgentChatMessagesQuery__
+ * __useGetChatMessagesQuery__
*
- * To run a query within a React component, call `useGetAgentChatMessagesQuery` and pass it any options that fit your needs.
- * When your component renders, `useGetAgentChatMessagesQuery` returns an object from Apollo Client that contains loading, error, and data properties
+ * To run a query within a React component, call `useGetChatMessagesQuery` and pass it any options that fit your needs.
+ * When your component renders, `useGetChatMessagesQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
- * const { data, loading, error } = useGetAgentChatMessagesQuery({
+ * const { data, loading, error } = useGetChatMessagesQuery({
* variables: {
* threadId: // value for 'threadId'
* },
* });
*/
-export function useGetAgentChatMessagesQuery(baseOptions: Apollo.QueryHookOptions<GetAgentChatMessagesQuery, GetAgentChatMessagesQueryVariables>) {
+export function useGetChatMessagesQuery(baseOptions: Apollo.QueryHookOptions<GetChatMessagesQuery, GetChatMessagesQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useQuery<GetAgentChatMessagesQuery, GetAgentChatMessagesQueryVariables>(GetAgentChatMessagesDocument, options);
+ return Apollo.useQuery<GetChatMessagesQuery, GetChatMessagesQueryVariables>(GetChatMessagesDocument, options);
}
-export function useGetAgentChatMessagesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetAgentChatMessagesQuery, GetAgentChatMessagesQueryVariables>) {
+export function useGetChatMessagesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetChatMessagesQuery, GetChatMessagesQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useLazyQuery<GetAgentChatMessagesQuery, GetAgentChatMessagesQueryVariables>(GetAgentChatMessagesDocument, options);
+ return Apollo.useLazyQuery<GetChatMessagesQuery, GetChatMessagesQueryVariables>(GetChatMessagesDocument, options);
}
-export type GetAgentChatMessagesQueryHookResult = ReturnType<typeof useGetAgentChatMessagesQuery>;
-export type GetAgentChatMessagesLazyQueryHookResult = ReturnType<typeof useGetAgentChatMessagesLazyQuery>;
-export type GetAgentChatMessagesQueryResult = Apollo.QueryResult<GetAgentChatMessagesQuery, GetAgentChatMessagesQueryVariables>;
-export const GetAgentChatThreadsDocument = gql`
- query GetAgentChatThreads($agentId: UUID!) {
- agentChatThreads(agentId: $agentId) {
+export type GetChatMessagesQueryHookResult = ReturnType<typeof useGetChatMessagesQuery>;
+export type GetChatMessagesLazyQueryHookResult = ReturnType<typeof useGetChatMessagesLazyQuery>;
+export type GetChatMessagesQueryResult = Apollo.QueryResult<GetChatMessagesQuery, GetChatMessagesQueryVariables>;
+export const GetChatThreadsDocument = gql`
+ query GetChatThreads {
+ chatThreads {
id
- agentId
title
createdAt
updatedAt
@@ -7414,32 +7391,31 @@ export const GetAgentChatThreadsDocument = gql`
`;
/**
- * __useGetAgentChatThreadsQuery__
+ * __useGetChatThreadsQuery__
*
- * To run a query within a React component, call `useGetAgentChatThreadsQuery` and pass it any options that fit your needs.
- * When your component renders, `useGetAgentChatThreadsQuery` returns an object from Apollo Client that contains loading, error, and data properties
+ * To run a query within a React component, call `useGetChatThreadsQuery` and pass it any options that fit your needs.
+ * When your component renders, `useGetChatThreadsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
- * const { data, loading, error } = useGetAgentChatThreadsQuery({
+ * const { data, loading, error } = useGetChatThreadsQuery({
* variables: {
- * agentId: // value for 'agentId'
* },
* });
*/
-export function useGetAgentChatThreadsQuery(baseOptions: Apollo.QueryHookOptions<GetAgentChatThreadsQuery, GetAgentChatThreadsQueryVariables>) {
+export function useGetChatThreadsQuery(baseOptions?: Apollo.QueryHookOptions<GetChatThreadsQuery, GetChatThreadsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useQuery<GetAgentChatThreadsQuery, GetAgentChatThreadsQueryVariables>(GetAgentChatThreadsDocument, options);
+ return Apollo.useQuery<GetChatThreadsQuery, GetChatThreadsQueryVariables>(GetChatThreadsDocument, options);
}
-export function useGetAgentChatThreadsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetAgentChatThreadsQuery, GetAgentChatThreadsQueryVariables>) {
+export function useGetChatThreadsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetChatThreadsQuery, GetChatThreadsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
- return Apollo.useLazyQuery<GetAgentChatThreadsQuery, GetAgentChatThreadsQueryVariables>(GetAgentChatThreadsDocument, options);
+ return Apollo.useLazyQuery<GetChatThreadsQuery, GetChatThreadsQueryVariables>(GetChatThreadsDocument, options);
}
-export type GetAgentChatThreadsQueryHookResult = ReturnType<typeof useGetAgentChatThreadsQuery>;
-export type GetAgentChatThreadsLazyQueryHookResult = ReturnType<typeof useGetAgentChatThreadsLazyQuery>;
-export type GetAgentChatThreadsQueryResult = Apollo.QueryResult<GetAgentChatThreadsQuery, GetAgentChatThreadsQueryVariables>;
+export type GetChatThreadsQueryHookResult = ReturnType<typeof useGetChatThreadsQuery>;
+export type GetChatThreadsLazyQueryHookResult = ReturnType<typeof useGetChatThreadsLazyQuery>;
+export type GetChatThreadsQueryResult = Apollo.QueryResult<GetChatThreadsQuery, GetChatThreadsQueryVariables>;
export const TrackAnalyticsDocument = gql`
mutation TrackAnalytics($type: AnalyticsType!, $event: String, $name: String, $properties: JSON) {
trackAnalytics(type: $type, event: $event, name: $name, properties: $properties) {
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 4e2ca072f70..3bac4c43fb9 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -108,7 +108,6 @@ export type AgentChatMessagePart = {
export type AgentChatThread = {
__typename?: 'AgentChatThread';
- agentId: Scalars['UUID'];
createdAt: Scalars['DateTime'];
id: Scalars['UUID'];
title?: Maybe<Scalars['String']>;
@@ -728,10 +727,6 @@ export type CoreViewSort = {
workspaceId: Scalars['UUID'];
};
-export type CreateAgentChatThreadInput = {
- agentId: Scalars['UUID'];
-};
-
export type CreateAgentHandoffInput = {
description?: InputMaybe<Scalars['String']>;
fromAgentId: Scalars['UUID'];
@@ -1681,10 +1676,10 @@ export type Mutation = {
checkPublicDomainValidRecords?: Maybe<DomainValidRecords>;
checkoutSession: BillingSessionOutput;
computeStepOutputSchema: Scalars['JSON'];
- createAgentChatThread: AgentChatThread;
createAgentHandoff: Scalars['Boolean'];
createApiKey: ApiKey;
createApprovedAccessDomain: ApprovedAccessDomain;
+ createChatThread: AgentChatThread;
createCoreView: CoreView;
createCoreViewField: CoreViewField;
createCoreViewFilter: CoreViewFilter;
@@ -1893,11 +1888,6 @@ export type MutationComputeStepOutputSchemaArgs = {
};
-export type MutationCreateAgentChatThreadArgs = {
- input: CreateAgentChatThreadInput;
-};
-
-
export type MutationCreateAgentHandoffArgs = {
input: CreateAgentHandoffInput;
};
@@ -3017,12 +3007,12 @@ export type PublishServerlessFunctionInput = {
export type Query = {
__typename?: 'Query';
- agentChatMessages: Array<AgentChatMessage>;
- agentChatThread: AgentChatThread;
- agentChatThreads: Array<AgentChatThread>;
apiKey?: Maybe<ApiKey>;
apiKeys: Array<ApiKey>;
billingPortalSession: BillingSessionOutput;
+ chatMessages: Array<AgentChatMessage>;
+ chatThread: AgentChatThread;
+ chatThreads: Array<AgentChatThread>;
checkUserExists: CheckUserExistOutput;
checkWorkspaceInviteHashIsValid: WorkspaceInviteHashValidOutput;
currentUser: User;
@@ -3101,28 +3091,23 @@ export type Query = {
};
-export type QueryAgentChatMessagesArgs = {
- threadId: Scalars['UUID'];
-};
-
-
-export type QueryAgentChatThreadArgs = {
- id: Scalars['UUID'];
+export type QueryApiKeyArgs = {
+ input: GetApiKeyInput;
};
-export type QueryAgentChatThreadsArgs = {
- agentId: Scalars['UUID'];
+export type QueryBillingPortalSessionArgs = {
+ returnUrlPath?: InputMaybe<Scalars['String']>;
};
-export type QueryApiKeyArgs = {
- input: GetApiKeyInput;
+export type QueryChatMessagesArgs = {
+ threadId: Scalars['UUID'];
};
-export type QueryBillingPortalSessionArgs = {
- returnUrlPath?: InputMaybe<Scalars['String']>;
+export type QueryChatThreadArgs = {
+ id: Scalars['UUID'];
};
@@ -4184,6 +4169,7 @@ export type UpdateWorkspaceInput = {
isPublicInviteLinkEnabled?: InputMaybe<Scalars['Boolean']>;
isTwoFactorAuthenticationEnforced?: InputMaybe<Scalars['Boolean']>;
logo?: InputMaybe<Scalars['String']>;
+ routerModel?: InputMaybe<Scalars['String']>;
subdomain?: InputMaybe<Scalars['String']>;
trashRetentionDays?: InputMaybe<Scalars['Float']>;
};
@@ -4477,7 +4463,6 @@ export type Workspace = {
customDomain?: Maybe<Scalars['String']>;
databaseSchema: Scalars['String'];
databaseUrl: Scalars['String'];
- defaultAgent?: Maybe<Agent>;
defaultRole?: Maybe<Role>;
deletedAt?: Maybe<Scalars['DateTime']>;
displayName?: Maybe<Scalars['String']>;
@@ -4493,6 +4478,7 @@ export type Workspace = {
isTwoFactorAuthenticationEnforced: Scalars['Boolean'];
logo?: Maybe<Scalars['String']>;
metadataVersion: Scalars['Float'];
+ routerModel: Scalars['String'];
subdomain: Scalars['String'];
trashRetentionDays: Scalars['Float'];
updatedAt: Scalars['DateTime'];
diff --git a/packages/twenty-front/src/modules/ai/components/AIChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AIChatAssistantMessageRenderer.tsx
index c35c0b91b23..5c5680924f1 100644
--- a/packages/twenty-front/src/modules/ai/components/AIChatAssistantMessageRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AIChatAssistantMessageRenderer.tsx
@@ -1,16 +1,13 @@
import { ReasoningSummaryDisplay } from '@/ai/components/ReasoningSummaryDisplay';
+import { RoutingStatusDisplay } from '@/ai/components/RoutingStatusDisplay';
import { IconDotsVertical } from 'twenty-ui/display';
import { LazyMarkdownRenderer } from '@/ai/components/LazyMarkdownRenderer';
import { ToolStepRenderer } from '@/ai/components/ToolStepRenderer';
import { keyframes, useTheme } from '@emotion/react';
import styled from '@emotion/styled';
-import {
- isToolUIPart,
- type UIDataTypes,
- type UIMessagePart,
- type UITools,
-} from 'ai';
+import { isToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
const StyledMessagePartsContainer = styled.div`
display: flex;
@@ -64,14 +61,11 @@ export const AIChatAssistantMessageRenderer = ({
isLastMessageStreaming,
hasError,
}: {
- messageParts: UIMessagePart<UIDataTypes, UITools>[];
+ messageParts: ExtendedUIMessagePart[];
isLastMessageStreaming: boolean;
hasError?: boolean;
}) => {
- const renderMessagePart = (
- part: UIMessagePart<UIDataTypes, UITools>,
- index: number,
- ) => {
+ const renderMessagePart = (part: ExtendedUIMessagePart, index: number) => {
switch (part.type) {
case 'reasoning':
return (
@@ -83,6 +77,8 @@ export const AIChatAssistantMessageRenderer = ({
);
case 'text':
return <LazyMarkdownRenderer key={index} text={part.text} />;
+ case 'data-routing-status':
+ return <RoutingStatusDisplay data={part.data} key={index} />;
default:
{
if (isToolUIPart(part)) {
diff --git a/packages/twenty-front/src/modules/ai/components/AIChatMessage.tsx b/packages/twenty-front/src/modules/ai/components/AIChatMessage.tsx
index bd7acb72395..02b4de3ce2d 100644
--- a/packages/twenty-front/src/modules/ai/components/AIChatMessage.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AIChatMessage.tsx
@@ -9,10 +9,10 @@ import { AgentChatMessageRole } from '@/ai/constants/AgentChatMessageRole';
import { AIChatAssistantMessageRenderer } from '@/ai/components/AIChatAssistantMessageRenderer';
import { AIChatErrorMessage } from '@/ai/components/AIChatErrorMessage';
import { AIChatErrorMessageWithRecordsContext } from '@/ai/components/internal/AIChatErrorMessageWithRecordsContext';
-import { type UIMessageWithMetadata } from '@/ai/types/UIMessageWithMetadata';
import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';
import { LightCopyIconButton } from '@/object-record/record-field/ui/components/LightCopyIconButton';
import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { dateLocaleState } from '~/localization/states/dateLocaleState';
import { beautifyPastDateRelativeToNow } from '~/utils/date-utils';
@@ -51,7 +51,9 @@ const StyledMessageText = styled.div<{ isUser?: boolean }>`
max-width: 100%;
word-wrap: break-word;
overflow-wrap: break-word;
- white-space: pre-wrap;
+ /* Pre-wrap within the whole container turns every newline between block
+ elements into extra spacing; keep normal flow and only pre-wrap code. */
+ white-space: normal;
code {
overflow: auto;
@@ -146,7 +148,7 @@ export const AIChatMessage = ({
isLastMessageStreaming,
error,
}: {
- message: UIMessageWithMetadata;
+ message: ExtendedUIMessage;
isLastMessageStreaming: boolean;
error?: Error | null;
}) => {
@@ -160,6 +162,8 @@ export const AIChatMessage = ({
const showError =
isDefined(error) && message.role === AgentChatMessageRole.ASSISTANT;
+ const fileParts = message.parts.filter((part) => part.type === 'file');
+
return (
<StyledMessageBubble
key={message.id}
@@ -191,13 +195,11 @@ export const AIChatMessage = ({
hasError={showError}
/>
</StyledMessageText>
- {message.parts.length > 0 && (
+ {fileParts.length > 0 && (
<StyledFilesContainer>
- {message.parts
- .filter((part) => part.type === 'file')
- .map((file) => (
- <AgentChatFilePreview key={file.filename} file={file} />
- ))}
+ {fileParts.map((file) => (
+ <AgentChatFilePreview key={file.filename} file={file} />
+ ))}
</StyledFilesContainer>
)}
{showError &&
diff --git a/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx b/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
index 6248bfd3466..362692cfb1a 100644
--- a/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
@@ -59,7 +59,7 @@ const StyledButtonsContainer = styled.div`
gap: ${({ theme }) => theme.spacing(2)};
`;
-export const AIChatTab = ({ agentId }: { agentId: string }) => {
+export const AIChatTab = () => {
const [isDraggingFile, setIsDraggingFile] = useState(false);
const {
@@ -70,14 +70,14 @@ export const AIChatTab = ({ agentId }: { agentId: string }) => {
messages,
isStreaming,
error,
- } = useAgentChat(agentId);
+ } = useAgentChat();
const contextStoreCurrentObjectMetadataItemId = useRecoilComponentValue(
contextStoreCurrentObjectMetadataItemIdComponentState,
);
const { uploadFiles } = useAIChatFileUpload();
- const { createAgentChatThread } = useCreateNewAIChatThread({ agentId });
+ const { createChatThread } = useCreateNewAIChatThread();
const { navigateCommandMenu } = useCommandMenu();
return (
@@ -141,13 +141,13 @@ export const AIChatTab = ({ agentId }: { agentId: string }) => {
variant="secondary"
size="small"
Icon={IconMessageCirclePlus}
- onClick={() => createAgentChatThread()}
+ onClick={() => createChatThread()}
/>
<AgentChatFileUploadButton />
{contextStoreCurrentObjectMetadataItemId ? (
- <SendMessageWithRecordsContextButton agentId={agentId} />
+ <SendMessageWithRecordsContextButton />
) : (
- <SendMessageButton agentId={agentId} />
+ <SendMessageButton />
)}
</StyledButtonsContainer>
</StyledInputArea>
diff --git a/packages/twenty-front/src/modules/ai/components/AIChatThreadsList.tsx b/packages/twenty-front/src/modules/ai/components/AIChatThreadsList.tsx
index 05dfec6ecc9..7b3515172b2 100644
--- a/packages/twenty-front/src/modules/ai/components/AIChatThreadsList.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AIChatThreadsList.tsx
@@ -10,7 +10,7 @@ import { Key } from 'ts-key-enum';
import { capitalize } from 'twenty-shared/utils';
import { Button } from 'twenty-ui/input';
import { getOsControlSymbol } from 'twenty-ui/utilities';
-import { useGetAgentChatThreadsQuery } from '~/generated-metadata/graphql';
+import { useGetChatThreadsQuery } from '~/generated-metadata/graphql';
const StyledContainer = styled.div`
background: ${({ theme }) => theme.background.secondary};
@@ -33,24 +33,21 @@ const StyledButtonsContainer = styled.div`
border-top: 1px solid ${({ theme }) => theme.border.color.medium};
`;
-export const AIChatThreadsList = ({ agentId }: { agentId: string }) => {
- const { createAgentChatThread } = useCreateNewAIChatThread({ agentId });
+export const AIChatThreadsList = () => {
+ const { createChatThread } = useCreateNewAIChatThread();
- const focusId = `${agentId}-threads-list`;
+ const focusId = 'threads-list';
useHotkeysOnFocusedElement({
keys: [`${Key.Control}+${Key.Enter}`, `${Key.Meta}+${Key.Enter}`],
- callback: () => createAgentChatThread(),
+ callback: () => createChatThread(),
focusId,
- dependencies: [createAgentChatThread, agentId],
+ dependencies: [createChatThread],
});
- const { data: { agentChatThreads = [] } = {}, loading } =
- useGetAgentChatThreadsQuery({
- variables: { agentId },
- });
+ const { data: { chatThreads = [] } = {}, loading } = useGetChatThreadsQuery();
- const groupedThreads = groupThreadsByDate(agentChatThreads);
+ const groupedThreads = groupThreadsByDate(chatThreads);
if (loading === true) {
return <AIChatSkeletonLoader />;
@@ -75,7 +72,7 @@ export const AIChatThreadsList = ({ agentId }: { agentId: string }) => {
accent="blue"
size="medium"
title="New chat"
- onClick={() => createAgentChatThread()}
+ onClick={() => createChatThread()}
hotkeys={[getOsControlSymbol(), '⏎']}
/>
</StyledButtonsContainer>
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx
index 45e74526d66..f22d5d9b20d 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx
@@ -1,19 +1,18 @@
import { AgentChatContext } from '@/ai/contexts/AgentChatContext';
import { useAgentChatData } from '@/ai/hooks/useAgentChatData';
import { currentAIChatThreadState } from '@/ai/states/currentAIChatThreadState';
-import { type UIMessageWithMetadata } from '@/ai/types/UIMessageWithMetadata';
import { REST_API_BASE_URL } from '@/apollo/constant/rest-api-base-url';
import { getTokenPair } from '@/apollo/utils/getTokenPair';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { Chat } from '@ai-sdk/react';
import { DefaultChatTransport } from 'ai';
import { Suspense } from 'react';
import { useRecoilValue } from 'recoil';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
import { FeatureFlagKey } from '~/generated/graphql';
const createLoadingChat = () =>
- new Chat<UIMessageWithMetadata>({
+ new Chat<ExtendedUIMessage>({
transport: new DefaultChatTransport({
api: `${REST_API_BASE_URL}/agent-chat/stream`,
headers: () => ({}),
@@ -23,18 +22,16 @@ const createLoadingChat = () =>
});
const AgentChatProviderContent = ({
- agentId,
children,
}: {
- agentId: string;
children: React.ReactNode;
}) => {
- const { uiMessages, isLoading } = useAgentChatData(agentId);
+ const { uiMessages, isLoading } = useAgentChatData();
const currentAIChatThread = useRecoilValue(currentAIChatThreadState);
const chatConfig = isLoading
? createLoadingChat()
- : new Chat<UIMessageWithMetadata>({
+ : new Chat<ExtendedUIMessage>({
transport: new DefaultChatTransport({
api: `${REST_API_BASE_URL}/agent-chat/stream`,
headers: () => ({
@@ -59,11 +56,9 @@ export const AgentChatProvider = ({
}: {
children: React.ReactNode;
}) => {
- const currentWorkspace = useRecoilValue(currentWorkspaceState);
- const agentId = currentWorkspace?.defaultAgent?.id;
const isAiEnabled = useIsFeatureEnabled(FeatureFlagKey.IS_AI_ENABLED);
- if (!isAiEnabled || !agentId) {
+ if (!isAiEnabled) {
return (
<AgentChatContext.Provider
value={{
@@ -89,9 +84,7 @@ export const AgentChatProvider = ({
</AgentChatContext.Provider>
}
>
- <AgentChatProviderContent agentId={agentId}>
- {children}
- </AgentChatProviderContent>
+ <AgentChatProviderContent>{children}</AgentChatProviderContent>
</Suspense>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/RoutingStatusDisplay.tsx b/packages/twenty-front/src/modules/ai/components/RoutingStatusDisplay.tsx
new file mode 100644
index 00000000000..468e55276af
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/RoutingStatusDisplay.tsx
@@ -0,0 +1,60 @@
+import { ShimmeringText } from '@/ai/components/ShimmeringText';
+import { keyframes } from '@emotion/react';
+import styled from '@emotion/styled';
+import { type DataMessagePart } from 'twenty-shared/ai';
+import { IconCpu, IconSparkles } from 'twenty-ui/display';
+
+const pulseAnimation = keyframes`
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+`;
+
+const StyledRoutingContainer = styled.div`
+ align-items: center;
+ background: ${({ theme }) => theme.background.transparent.lighter};
+ border: ${({ theme }) => `1px dashed ${theme.border.color.medium}`};
+ border-radius: ${({ theme }) => theme.border.radius.md};
+ display: flex;
+ font-size: ${({ theme }) => theme.font.size.sm};
+ gap: ${({ theme }) => theme.spacing(2)};
+ margin-bottom: ${({ theme }) => theme.spacing(2)};
+ padding: ${({ theme }) => theme.spacing(2, 3)};
+ width: fit-content;
+`;
+
+const StyledIconContainer = styled.div<{ isLoading: boolean }>`
+ align-items: center;
+ animation: ${({ isLoading }) =>
+ isLoading ? `${pulseAnimation} 2s ease-in-out infinite` : 'none'};
+ color: ${({ theme }) => theme.color.blue};
+ display: flex;
+`;
+
+const StyledText = styled.div`
+ color: ${({ theme }) => theme.font.color.tertiary};
+`;
+
+export const RoutingStatusDisplay = ({
+ data,
+}: {
+ data: DataMessagePart['routing-status'];
+}) => {
+ const isLoading = data.state === 'loading';
+
+ if (data.state === 'error') {
+ return null;
+ }
+
+ return (
+ <StyledRoutingContainer>
+ <StyledIconContainer isLoading={isLoading}>
+ {isLoading ? <IconSparkles size={16} /> : <IconCpu size={16} />}
+ </StyledIconContainer>
+ {isLoading ? (
+ <ShimmeringText>{data.text}</ShimmeringText>
+ ) : (
+ <StyledText>{data.text}</StyledText>
+ )}
+ </StyledRoutingContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/ToolStepRenderer.tsx b/packages/twenty-front/src/modules/ai/components/ToolStepRenderer.tsx
index 12a593e7782..a954e7d07f8 100644
--- a/packages/twenty-front/src/modules/ai/components/ToolStepRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/ToolStepRenderer.tsx
@@ -4,13 +4,17 @@ import { useState } from 'react';
import { IconChevronDown, IconChevronUp } from 'twenty-ui/display';
import { AnimatedExpandableContainer } from 'twenty-ui/layout';
+import { JsonTree } from 'twenty-ui/json-visualizer';
import { ShimmeringText } from '@/ai/components/ShimmeringText';
import { type ToolInput } from '@/ai/types/ToolInput';
import { getToolIcon } from '@/ai/utils/getToolIcon';
import { getToolDisplayMessage } from '@/ai/utils/getWebSearchToolDisplayMessage';
+import { useLingui } from '@lingui/react/macro';
import { type ToolUIPart } from 'ai';
import { isDefined } from 'twenty-shared/utils';
+import { type JsonValue } from 'type-fest';
+import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
const StyledContainer = styled.div`
display: flex;
@@ -53,11 +57,6 @@ const StyledDisplayMessage = styled.span`
font-weight: ${({ theme }) => theme.font.weight.medium};
`;
-const StyledPre = styled.pre`
- margin-top: ${({ theme }) => theme.spacing(1)};
- white-space: pre-wrap;
-`;
-
const StyledIconTextContainer = styled.div`
display: flex;
align-items: center;
@@ -68,6 +67,35 @@ const StyledIconTextContainer = styled.div`
}
`;
+const StyledTabContainer = styled.div`
+ border-bottom: 1px solid ${({ theme }) => theme.border.color.light};
+ display: flex;
+ gap: ${({ theme }) => theme.spacing(3)};
+ margin-bottom: ${({ theme }) => theme.spacing(3)};
+`;
+
+const StyledTab = styled.div<{ isActive: boolean }>`
+ color: ${({ theme, isActive }) =>
+ isActive ? theme.font.color.primary : theme.font.color.tertiary};
+ font-size: ${({ theme }) => theme.font.size.sm};
+ font-weight: ${({ theme, isActive }) =>
+ isActive ? theme.font.weight.medium : theme.font.weight.regular};
+ cursor: pointer;
+ transition: color ${({ theme }) => theme.animation.duration.normal}s;
+ padding-bottom: ${({ theme }) => theme.spacing(2)};
+
+ &:hover {
+ color: ${({ theme }) => theme.font.color.secondary};
+ }
+`;
+
+const StyledJsonContainer = styled.div`
+ max-height: 400px;
+ overflow: auto;
+`;
+
+type TabType = 'output' | 'input';
+
export const ToolStepRenderer = ({
input,
output,
@@ -77,11 +105,16 @@ export const ToolStepRenderer = ({
output: ToolUIPart['output'];
toolName: string;
}) => {
+ const { t } = useLingui();
const theme = useTheme();
+ const { copyToClipboard } = useCopyToClipboard();
const [isExpanded, setIsExpanded] = useState(false);
+ const [activeTab, setActiveTab] = useState<TabType>('output');
const isExpandable = isDefined(output);
+ const isTwoFirstDepths = ({ depth }: { depth: number }) => depth < 2;
+
if (!output) {
return (
<StyledContainer>
@@ -132,7 +165,33 @@ export const ToolStepRenderer = ({
{isExpandable && (
<AnimatedExpandableContainer isExpanded={isExpanded}>
<StyledContentContainer>
- <StyledPre>{JSON.stringify(result, null, 2)}</StyledPre>
+ <StyledTabContainer>
+ <StyledTab
+ isActive={activeTab === 'output'}
+ onClick={() => setActiveTab('output')}
+ >
+ Output
+ </StyledTab>
+ <StyledTab
+ isActive={activeTab === 'input'}
+ onClick={() => setActiveTab('input')}
+ >
+ Input
+ </StyledTab>
+ </StyledTabContainer>
+
+ <StyledJsonContainer>
+ <JsonTree
+ value={(activeTab === 'output' ? result : input) as JsonValue}
+ shouldExpandNodeInitially={isTwoFirstDepths}
+ emptyArrayLabel={t`Empty Array`}
+ emptyObjectLabel={t`Empty Object`}
+ emptyStringLabel={t`[empty string]`}
+ arrowButtonCollapsedLabel={t`Expand`}
+ arrowButtonExpandedLabel={t`Collapse`}
+ onNodeValueClick={copyToClipboard}
+ />
+ </StyledJsonContainer>
</StyledContentContainer>
</AnimatedExpandableContainer>
)}
diff --git a/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx
index cff2d61880e..2e820012d72 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx
@@ -12,13 +12,11 @@ import { Key } from 'ts-key-enum';
import { Button } from 'twenty-ui/input';
export const SendMessageButton = ({
- agentId,
records,
}: {
- agentId: string;
records?: ObjectRecord[];
}) => {
- const { input, isLoading, handleInputChange } = useAgentChat(agentId);
+ const { input, isLoading, handleInputChange } = useAgentChat();
const { chat } = useAgentChatContextOrThrow();
const { buildRequestBody } = useAgentChatRequestBody();
const { sendMessage } = useChat({ chat });
diff --git a/packages/twenty-front/src/modules/ai/components/internal/SendMessageWithRecordsContextButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/SendMessageWithRecordsContextButton.tsx
index 06319f824d1..26e7f777323 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/SendMessageWithRecordsContextButton.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/SendMessageWithRecordsContextButton.tsx
@@ -1,14 +1,10 @@
import { SendMessageButton } from '@/ai/components/internal/SendMessageButton';
import { useFindManyRecordsSelectedInContextStore } from '@/context-store/hooks/useFindManyRecordsSelectedInContextStore';
-export const SendMessageWithRecordsContextButton = ({
- agentId,
-}: {
- agentId: string;
-}) => {
+export const SendMessageWithRecordsContextButton = () => {
const { records } = useFindManyRecordsSelectedInContextStore({
limit: 10,
});
- return <SendMessageButton agentId={agentId} records={records} />;
+ return <SendMessageButton records={records} />;
};
diff --git a/packages/twenty-front/src/modules/ai/contexts/AgentChatContext.ts b/packages/twenty-front/src/modules/ai/contexts/AgentChatContext.ts
index d25a6ee6d93..d5151b78daa 100644
--- a/packages/twenty-front/src/modules/ai/contexts/AgentChatContext.ts
+++ b/packages/twenty-front/src/modules/ai/contexts/AgentChatContext.ts
@@ -1,9 +1,9 @@
-import { type UIMessageWithMetadata } from '@/ai/types/UIMessageWithMetadata';
import { type Chat } from '@ai-sdk/react';
import { createContext } from 'react';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
export type AgentChatContextValue = {
- chat: Chat<UIMessageWithMetadata>;
+ chat: Chat<ExtendedUIMessage>;
isLoadingData: boolean;
};
diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/createAgentChatThread.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/createAgentChatThread.ts
deleted file mode 100644
index 5f9775c54d6..00000000000
--- a/packages/twenty-front/src/modules/ai/graphql/mutations/createAgentChatThread.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { gql } from '@apollo/client';
-
-export const CREATE_AGENT_CHAT_THREAD = gql`
- mutation CreateAgentChatThread($input: CreateAgentChatThreadInput!) {
- createAgentChatThread(input: $input) {
- id
- agentId
- title
- createdAt
- updatedAt
- }
- }
-`;
diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts
new file mode 100644
index 00000000000..4f8b34baca3
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts
@@ -0,0 +1,12 @@
+import { gql } from '@apollo/client';
+
+export const CREATE_CHAT_THREAD = gql`
+ mutation CreateChatThread {
+ createChatThread {
+ id
+ title
+ createdAt
+ updatedAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatThreads.ts
deleted file mode 100644
index d398e8f5f00..00000000000
--- a/packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatThreads.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { gql } from '@apollo/client';
-
-export const GET_AGENT_CHAT_THREADS = gql`
- query GetAgentChatThreads($agentId: UUID!) {
- agentChatThreads(agentId: $agentId) {
- id
- agentId
- title
- createdAt
- updatedAt
- }
- }
-`;
diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatMessages.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts
similarity index 82%
rename from packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatMessages.ts
rename to packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts
index 54152f08934..11bc878af4e 100644
--- a/packages/twenty-front/src/modules/ai/graphql/queries/getAgentChatMessages.ts
+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts
@@ -1,8 +1,8 @@
import { gql } from '@apollo/client';
-export const GET_AGENT_CHAT_MESSAGES = gql`
- query GetAgentChatMessages($threadId: UUID!) {
- agentChatMessages(threadId: $threadId) {
+export const GET_CHAT_MESSAGES = gql`
+ query GetChatMessages($threadId: UUID!) {
+ chatMessages(threadId: $threadId) {
id
threadId
role
diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts
new file mode 100644
index 00000000000..6e259907908
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts
@@ -0,0 +1,12 @@
+import { gql } from '@apollo/client';
+
+export const GET_CHAT_THREADS = gql`
+ query GetChatThreads {
+ chatThreads {
+ id
+ title
+ createdAt
+ updatedAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index 67740632622..93d7410de29 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -6,7 +6,7 @@ import { currentAIChatThreadState } from '@/ai/states/currentAIChatThreadState';
import { useChat } from '@ai-sdk/react';
import { agentChatInputState } from '../states/agentChatInputState';
-export const useAgentChat = (agentId: string) => {
+export const useAgentChat = () => {
const { chat, isLoadingData } = useAgentChatContextOrThrow();
const agentChatSelectedFiles = useRecoilValue(agentChatSelectedFilesState);
@@ -16,7 +16,7 @@ export const useAgentChat = (agentId: string) => {
const [agentChatInput, setAgentChatInput] =
useRecoilState(agentChatInputState);
- const scrollWrapperId = `scroll-wrapper-ai-chat-${agentId}`;
+ const scrollWrapperId = `scroll-wrapper-ai-chat-${currentAIChatThread}`;
const { messages, status, error } = useChat({
chat,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatData.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatData.ts
index d5a30e9d6c1..3a1f6468466 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatData.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatData.ts
@@ -3,31 +3,30 @@ import { mapDBMessagesToUIMessages } from '@/ai/utils/mapDBMessagesToUIMessages'
import { useRecoilState } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import {
- useGetAgentChatMessagesQuery,
- useGetAgentChatThreadsQuery,
+ useGetChatMessagesQuery,
+ useGetChatThreadsQuery,
} from '~/generated-metadata/graphql';
-export const useAgentChatData = (agentId: string) => {
+export const useAgentChatData = () => {
const [currentAIChatThread, setCurrentAIChatThread] = useRecoilState(
currentAIChatThreadState,
);
- const { loading: threadsLoading } = useGetAgentChatThreadsQuery({
- variables: { agentId },
- skip: isDefined(currentAIChatThread) || !isDefined(agentId),
+ const { loading: threadsLoading } = useGetChatThreadsQuery({
+ skip: isDefined(currentAIChatThread),
onCompleted: (data) => {
- if (data.agentChatThreads.length > 0) {
- setCurrentAIChatThread(data.agentChatThreads[0].id);
+ if (data.chatThreads.length > 0) {
+ setCurrentAIChatThread(data.chatThreads[0].id);
}
},
});
- const { loading: messagesLoading, data } = useGetAgentChatMessagesQuery({
+ const { loading: messagesLoading, data } = useGetChatMessagesQuery({
variables: { threadId: currentAIChatThread! },
skip: !isDefined(currentAIChatThread),
});
- const uiMessages = mapDBMessagesToUIMessages(data?.agentChatMessages || []);
+ const uiMessages = mapDBMessagesToUIMessages(data?.chatMessages || []);
const isLoading = messagesLoading || threadsLoading;
return {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateNewAIChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateNewAIChatThread.ts
index 949c49b895a..4c158fc6f9d 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useCreateNewAIChatThread.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateNewAIChatThread.ts
@@ -1,19 +1,18 @@
import { currentAIChatThreadState } from '@/ai/states/currentAIChatThreadState';
import { useOpenAskAIPageInCommandMenu } from '@/command-menu/hooks/useOpenAskAIPageInCommandMenu';
import { useRecoilState } from 'recoil';
-import { useCreateAgentChatThreadMutation } from '~/generated-metadata/graphql';
+import { useCreateChatThreadMutation } from '~/generated-metadata/graphql';
-export const useCreateNewAIChatThread = ({ agentId }: { agentId: string }) => {
+export const useCreateNewAIChatThread = () => {
const [, setCurrentAIChatThread] = useRecoilState(currentAIChatThreadState);
const { openAskAIPage } = useOpenAskAIPageInCommandMenu();
- const [createAgentChatThread] = useCreateAgentChatThreadMutation({
- variables: { input: { agentId } },
+ const [createChatThread] = useCreateChatThreadMutation({
onCompleted: (data) => {
- setCurrentAIChatThread(data.createAgentChatThread.id);
+ setCurrentAIChatThread(data.createChatThread.id);
openAskAIPage();
},
});
- return { createAgentChatThread };
+ return { createChatThread };
};
diff --git a/packages/twenty-front/src/modules/ai/types/UIMessageWithMetadata.ts b/packages/twenty-front/src/modules/ai/types/UIMessageWithMetadata.ts
deleted file mode 100644
index 8634d690ea0..00000000000
--- a/packages/twenty-front/src/modules/ai/types/UIMessageWithMetadata.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type UIMessage } from 'ai';
-
-export type UIMessageWithMetadata = UIMessage & {
- metadata: {
- createdAt: string;
- };
-};
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts
index bfaff6ee3b8..64642250baa 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts
@@ -3,7 +3,6 @@ import { groupThreadsByDate } from '../groupThreadsByDate';
describe('groupThreadsByDate', () => {
const baseThread: Omit<AgentChatThread, 'createdAt' | 'id'> = {
- agentId: 'agent-1',
title: 'Test Thread',
updatedAt: new Date().toISOString(),
};
diff --git a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts b/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts
index 178fef4315d..368bdf53213 100644
--- a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts
+++ b/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts
@@ -1,13 +1,13 @@
-import { type UIMessageWithMetadata } from '@/ai/types/UIMessageWithMetadata';
import { mapDBPartToUIMessagePart } from '@/ai/utils/mapDBPartToUIMessagePart';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
import { type AgentChatMessage } from '~/generated/graphql';
export const mapDBMessagesToUIMessages = (
dbMessages: AgentChatMessage[],
-): UIMessageWithMetadata[] => {
+): ExtendedUIMessage[] => {
return dbMessages.map((dbMessage) => ({
id: dbMessage.id,
- role: dbMessage.role as UIMessageWithMetadata['role'],
+ role: dbMessage.role as ExtendedUIMessage['role'],
parts: dbMessage.parts.map(mapDBPartToUIMessagePart),
metadata: {
createdAt: dbMessage.createdAt,
diff --git a/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts b/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
index b22a1f3980e..72e702c5eb1 100644
--- a/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
+++ b/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
@@ -1,14 +1,10 @@
-import {
- type ReasoningUIPart,
- type ToolUIPart,
- type UIMessagePart,
- type UITool,
-} from 'ai';
+import { type ReasoningUIPart, type ToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
import { type AgentChatMessagePart } from '~/generated/graphql';
export const mapDBPartToUIMessagePart = (
part: AgentChatMessagePart,
-): UIMessagePart<never, Record<string, UITool>> => {
+): ExtendedUIMessagePart => {
switch (part.type) {
case 'text':
return {
@@ -49,6 +45,14 @@ export const mapDBPartToUIMessagePart = (
return {
type: 'step-start',
};
+ case 'data-routing-status':
+ return {
+ type: part.type,
+ data: {
+ text: part.textContent!,
+ state: part.state!,
+ },
+ };
default:
{
if (part.type.includes('tool-') === true) {
diff --git a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
index 4d0bd6dda50..7623e36bd03 100644
--- a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
+++ b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
@@ -58,6 +58,7 @@ const mockWorkspace = {
},
isTwoFactorAuthenticationEnforced: false,
trashRetentionDays: 14,
+ routerModel: 'auto',
};
const createMockOptions = (): Options<any> => ({
diff --git a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
index c6ed80bae26..986e25aa6af 100644
--- a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
+++ b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
@@ -243,14 +243,6 @@ const SettingsIntegrationDatabase = lazy(() =>
),
);
-const SettingsIntegrationMCP = lazy(() =>
- import('~/pages/settings/integrations/SettingsIntegrationMCPPage').then(
- (module) => ({
- default: module.SettingsIntegrationMCPPage,
- }),
- ),
-);
-
const SettingsIntegrationNewDatabaseConnection = lazy(() =>
import(
'~/pages/settings/integrations/SettingsIntegrationNewDatabaseConnection'
@@ -592,10 +584,6 @@ export const SettingsRoutes = ({ isAdminPageEnabled }: SettingsRoutesProps) => (
path={SettingsPath.IntegrationDatabaseConnection}
element={<SettingsIntegrationShowDatabaseConnection />}
/>
- <Route
- path={SettingsPath.IntegrationMCP}
- element={<SettingsIntegrationMCP />}
- />
</Route>
<Route
diff --git a/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts b/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
index de03d7fb375..a08d8daed91 100644
--- a/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
+++ b/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
@@ -25,9 +25,9 @@ export type CurrentWorkspace = Pick<
| 'metadataVersion'
| 'isTwoFactorAuthenticationEnforced'
| 'trashRetentionDays'
+ | 'routerModel'
> & {
defaultRole?: Omit<Role, 'workspaceMembers' | 'agents' | 'apiKeys'> | null;
- defaultAgent?: { id: string } | null;
};
export const currentWorkspaceState = createState<CurrentWorkspace | null>({
diff --git a/packages/twenty-front/src/modules/command-menu/pages/AIChatThreads/components/CommandMenuAIChatThreadsPage.tsx b/packages/twenty-front/src/modules/command-menu/pages/AIChatThreads/components/CommandMenuAIChatThreadsPage.tsx
index c1598d99052..7ebdcefa003 100644
--- a/packages/twenty-front/src/modules/command-menu/pages/AIChatThreads/components/CommandMenuAIChatThreadsPage.tsx
+++ b/packages/twenty-front/src/modules/command-menu/pages/AIChatThreads/components/CommandMenuAIChatThreadsPage.tsx
@@ -1,37 +1,15 @@
import { AIChatThreadsList } from '@/ai/components/AIChatThreadsList';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import styled from '@emotion/styled';
-import { useRecoilValue } from 'recoil';
const StyledContainer = styled.div`
height: 100%;
width: 100%;
`;
-const StyledEmptyState = styled.div`
- align-items: center;
- color: ${({ theme }) => theme.font.color.secondary};
- display: flex;
- font-size: ${({ theme }) => theme.font.size.md};
- height: 100%;
- justify-content: center;
-`;
-
export const CommandMenuAIChatThreadsPage = () => {
- const currentWorkspace = useRecoilValue(currentWorkspaceState);
- const agentId = currentWorkspace?.defaultAgent?.id;
-
- if (!agentId) {
- return (
- <StyledContainer>
- <StyledEmptyState>No AI Agent found.</StyledEmptyState>
- </StyledContainer>
- );
- }
-
return (
<StyledContainer>
- <AIChatThreadsList agentId={agentId} />
+ <AIChatThreadsList />
</StyledContainer>
);
};
diff --git a/packages/twenty-front/src/modules/command-menu/pages/ask-ai/components/CommandMenuAskAIPage.tsx b/packages/twenty-front/src/modules/command-menu/pages/ask-ai/components/CommandMenuAskAIPage.tsx
index 8a1a315c607..006bf4ab77e 100644
--- a/packages/twenty-front/src/modules/command-menu/pages/ask-ai/components/CommandMenuAskAIPage.tsx
+++ b/packages/twenty-front/src/modules/command-menu/pages/ask-ai/components/CommandMenuAskAIPage.tsx
@@ -1,38 +1,15 @@
import { AIChatTab } from '@/ai/components/AIChatTab';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import styled from '@emotion/styled';
-import { t } from '@lingui/core/macro';
-import { useRecoilValue } from 'recoil';
const StyledContainer = styled.div`
height: 100%;
width: 100%;
`;
-const StyledEmptyState = styled.div`
- align-items: center;
- color: ${({ theme }) => theme.font.color.secondary};
- display: flex;
- font-size: ${({ theme }) => theme.font.size.md};
- height: 100%;
- justify-content: center;
-`;
-
export const CommandMenuAskAIPage = () => {
- const currentWorkspace = useRecoilValue(currentWorkspaceState);
- const agentId = currentWorkspace?.defaultAgent?.id;
-
- if (!agentId) {
- return (
- <StyledContainer>
- <StyledEmptyState>{t`No AI Agent found.`}</StyledEmptyState>
- </StyledContainer>
- );
- }
-
return (
<StyledContainer>
- <AIChatTab agentId={agentId} />
+ <AIChatTab />
</StyledContainer>
);
};
diff --git a/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromFieldMetadata.test.ts b/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromFieldMetadata.test.ts
index d57a9164b37..41bb41cd819 100644
--- a/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromFieldMetadata.test.ts
+++ b/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromFieldMetadata.test.ts
@@ -51,6 +51,7 @@ const Wrapper = getJestMetadataAndApolloMocksAndActionMenuWrapper({
],
isTwoFactorAuthenticationEnforced: false,
trashRetentionDays: 14,
+ routerModel: 'auto',
});
},
});
diff --git a/packages/twenty-front/src/modules/settings/integrations/constants/SettingsIntegrationMcp.ts b/packages/twenty-front/src/modules/settings/integrations/constants/SettingsIntegrationMcp.ts
deleted file mode 100644
index 44b8e52ea4a..00000000000
--- a/packages/twenty-front/src/modules/settings/integrations/constants/SettingsIntegrationMcp.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type SettingsIntegrationCategory } from '@/settings/integrations/types/SettingsIntegrationCategory';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath } from 'twenty-shared/utils';
-
-export const SETTINGS_INTEGRATION_AI_CATEGORY: SettingsIntegrationCategory = {
- key: 'ai',
- title: 'With AI',
- hyperlink: null,
- integrations: [
- {
- from: {
- key: 'mcp',
- image: '/images/integrations/mcp.svg',
- },
- type: 'Add',
- text: 'Connect MCP Client',
- link: getSettingsPath(SettingsPath.IntegrationMCP),
- },
- ],
-};
diff --git a/packages/twenty-front/src/modules/settings/integrations/hooks/useSettingsIntegrationCategories.ts b/packages/twenty-front/src/modules/settings/integrations/hooks/useSettingsIntegrationCategories.ts
index e9ef6f23626..9fab3ca0218 100644
--- a/packages/twenty-front/src/modules/settings/integrations/hooks/useSettingsIntegrationCategories.ts
+++ b/packages/twenty-front/src/modules/settings/integrations/hooks/useSettingsIntegrationCategories.ts
@@ -1,5 +1,4 @@
import { MOCK_REMOTE_DATABASES } from '@/settings/integrations/constants/MockRemoteDatabases';
-import { SETTINGS_INTEGRATION_AI_CATEGORY } from '@/settings/integrations/constants/SettingsIntegrationMcp';
import { SETTINGS_INTEGRATION_REQUEST_CATEGORY } from '@/settings/integrations/constants/SettingsIntegrationRequest';
import { SETTINGS_INTEGRATION_ZAPIER_CATEGORY } from '@/settings/integrations/constants/SettingsIntegrationZapier';
import { type SettingsIntegrationCategory } from '@/settings/integrations/types/SettingsIntegrationCategory';
@@ -30,10 +29,6 @@ export const useSettingsIntegrationCategories =
({ name }) => name === 'stripe',
)?.isActive;
- const isAiIntegrationEnabled = useIsFeatureEnabled(
- FeatureFlagKey.IS_AI_ENABLED,
- );
-
const allIntegrations = getSettingsIntegrationAll({
isAirtableIntegrationEnabled,
isAirtableIntegrationActive,
@@ -46,7 +41,6 @@ export const useSettingsIntegrationCategories =
return [
...(allIntegrations.integrations.length > 0 ? [allIntegrations] : []),
SETTINGS_INTEGRATION_ZAPIER_CATEGORY,
- ...(isAiIntegrationEnabled ? [SETTINGS_INTEGRATION_AI_CATEGORY] : []),
SETTINGS_INTEGRATION_REQUEST_CATEGORY,
];
};
diff --git a/packages/twenty-front/src/modules/users/components/UserAndViewsProviderEffect.tsx b/packages/twenty-front/src/modules/users/components/UserAndViewsProviderEffect.tsx
index 803486d42f5..e338c0e4bc0 100644
--- a/packages/twenty-front/src/modules/users/components/UserAndViewsProviderEffect.tsx
+++ b/packages/twenty-front/src/modules/users/components/UserAndViewsProviderEffect.tsx
@@ -118,8 +118,6 @@ export const UserAndViewsProviderEffect = () => {
...userQueryData.currentUser.currentWorkspace,
defaultRole:
userQueryData.currentUser.currentWorkspace.defaultRole ?? null,
- defaultAgent:
- userQueryData.currentUser.currentWorkspace.defaultAgent ?? null,
});
}
diff --git a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
index df6099ce62c..208c9971b99 100644
--- a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
+++ b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
@@ -75,9 +75,7 @@ export const USER_QUERY_FRAGMENT = gql`
defaultRole {
...RoleFragment
}
- defaultAgent {
- id
- }
+ routerModel
isTwoFactorAuthenticationEnforced
trashRetentionDays
}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
index 3ab3eff9665..8dfd1c283d0 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
@@ -1,5 +1,4 @@
import { useAiAgentOutputSchema } from '@/ai/hooks/useAiAgentOutputSchema';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { SidePanelHeader } from '@/command-menu/components/SidePanelHeader';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { Select } from '@/ui/input/components/Select';
@@ -12,7 +11,6 @@ import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components
import { type AiAgentOutputSchema } from '@/workflow/workflow-variables/types/AiAgentOutputSchema';
import styled from '@emotion/styled';
import { t } from '@lingui/core/macro';
-import { useRecoilValue } from 'recoil';
import { useIcons } from 'twenty-ui/display';
import { type SelectOption } from 'twenty-ui/input';
import { useFindManyAgentsQuery } from '~/generated-metadata/graphql';
@@ -40,7 +38,6 @@ export const WorkflowEditActionAiAgent = ({
action,
actionOptions,
}: WorkflowEditActionAiAgentProps) => {
- const currentWorkspace = useRecoilValue(currentWorkspaceState);
const { getIcon } = useIcons();
const { headerTitle, headerIcon, headerIconColor, headerType } =
useWorkflowActionHeader({
@@ -61,13 +58,11 @@ export const WorkflowEditActionAiAgent = ({
SelectOption<string>[]
>(
(acc, agent) => {
- if (agent.id !== currentWorkspace?.defaultAgent?.id) {
- acc.push({
- label: agent.label,
- value: agent.id,
- Icon: agent.icon ? getIcon(agent.icon) : undefined,
- });
- }
+ acc.push({
+ label: agent.label,
+ value: agent.id,
+ Icon: agent.icon ? getIcon(agent.icon) : undefined,
+ });
return acc;
},
[
diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsAI.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsAI.tsx
index 808ed01cb2e..41ff414c37e 100644
--- a/packages/twenty-front/src/pages/settings/ai/SettingsAI.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/SettingsAI.tsx
@@ -1,31 +1,81 @@
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SubMenuTopBarContainer } from '@/ui/layout/page/components/SubMenuTopBarContainer';
+import { TabList } from '@/ui/layout/tab-list/components/TabList';
+import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';
+import { useRecoilComponentValue } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValue';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath } from 'twenty-shared/utils';
-import { H2Title, IconPlus } from 'twenty-ui/display';
+import {
+ IconPlus,
+ IconRobot,
+ IconServer,
+ IconSettings,
+} from 'twenty-ui/display';
import { Button } from 'twenty-ui/input';
-import { Section } from 'twenty-ui/layout';
import { UndecoratedLink } from 'twenty-ui/navigation';
-import { useFindManyAgentsQuery } from '~/generated-metadata/graphql';
import { t } from '@lingui/core/macro';
import { SettingsAIAgentsTable } from './components/SettingsAIAgentsTable';
+import { SettingsAIMCP } from './components/SettingsAIMCP';
+import { SettingsAIRouterSettings } from './components/SettingsAIRouterSettings';
+
+const SETTINGS_AI_TABS_ID = 'settings-ai-tabs-id';
+
+const SETTINGS_AI_TABS = {
+ AGENTS: 'agents',
+ SETTINGS: 'settings',
+ MCP: 'mcp',
+};
export const SettingsAI = () => {
- const { data } = useFindManyAgentsQuery();
+ const activeTabId = useRecoilComponentValue(
+ activeTabIdComponentState,
+ SETTINGS_AI_TABS_ID,
+ );
+
+ const tabs = [
+ {
+ id: SETTINGS_AI_TABS.AGENTS,
+ title: t`Agents`,
+ Icon: IconRobot,
+ },
+ {
+ id: SETTINGS_AI_TABS.MCP,
+ title: t`MCP`,
+ Icon: IconServer,
+ },
+ {
+ id: SETTINGS_AI_TABS.SETTINGS,
+ title: t`Settings`,
+ Icon: IconSettings,
+ },
+ ];
+
+ const renderActiveTabContent = () => {
+ switch (activeTabId) {
+ case SETTINGS_AI_TABS.AGENTS:
+ return <SettingsAIAgentsTable />;
+ case SETTINGS_AI_TABS.SETTINGS:
+ return <SettingsAIRouterSettings />;
+ case SETTINGS_AI_TABS.MCP:
+ return <SettingsAIMCP />;
+ }
+ };
return (
<SubMenuTopBarContainer
title={t`AI`}
actionButton={
- <UndecoratedLink to={getSettingsPath(SettingsPath.AINewAgent)}>
- <Button
- Icon={IconPlus}
- title={t`New Agent`}
- accent="blue"
- size="small"
- />
- </UndecoratedLink>
+ activeTabId === SETTINGS_AI_TABS.AGENTS ? (
+ <UndecoratedLink to={getSettingsPath(SettingsPath.AINewAgent)}>
+ <Button
+ Icon={IconPlus}
+ title={t`New Agent`}
+ accent="blue"
+ size="small"
+ />
+ </UndecoratedLink>
+ ) : undefined
}
links={[
{
@@ -36,13 +86,8 @@ export const SettingsAI = () => {
]}
>
<SettingsPageContainer>
- <Section>
- <H2Title
- title={t`Agents`}
- description={t`Agents used to route queries to specialized agents`}
- />
- <SettingsAIAgentsTable agents={data?.findManyAgents || []} />
- </Section>
+ <TabList tabs={tabs} componentInstanceId={SETTINGS_AI_TABS_ID} />
+ {renderActiveTabContent()}
</SettingsPageContainer>
</SubMenuTopBarContainer>
);
diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx
index 9d304fe7121..84846977511 100644
--- a/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx
@@ -1,9 +1,7 @@
import { ApolloError } from '@apollo/client';
import styled from '@emotion/styled';
import { useParams } from 'react-router-dom';
-import { useRecoilValue } from 'recoil';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
@@ -24,12 +22,11 @@ import {
import { useNavigateApp } from '~/hooks/useNavigateApp';
import { useNavigateSettings } from '~/hooks/useNavigateSettings';
+import { useState } from 'react';
import { SettingsAgentDeleteConfirmationModal } from './components/SettingsAgentDeleteConfirmationModal';
import { SettingsAgentDetailSkeletonLoader } from './components/SettingsAgentDetailSkeletonLoader';
-import { SettingsAgentHandoffSection } from './components/SettingsAgentHandoffSection';
import { SettingsAIAgentForm } from './forms/components/SettingsAIAgentForm';
import { useSettingsAgentFormState } from './hooks/useSettingsAgentFormState';
-import { useState } from 'react';
const StyledContentContainer = styled.div`
display: flex;
@@ -47,7 +44,6 @@ export const SettingsAgentForm = ({ mode }: { mode: 'create' | 'edit' }) => {
const navigateApp = useNavigateApp();
const { enqueueErrorSnackBar } = useSnackBar();
const { openModal } = useModal();
- const currentWorkspace = useRecoilValue(currentWorkspaceState);
const [isReadonlyMode, setIsReadonlyMode] = useState(false);
const isEditMode = mode === 'edit';
@@ -103,8 +99,6 @@ export const SettingsAgentForm = ({ mode }: { mode: 'create' | 'edit' }) => {
const agent = data?.findOneAgent;
- const isAskAIAgent = agent?.id === currentWorkspace?.defaultAgent?.id;
-
if (!isCreateMode && !loading && !agent) {
return null;
}
@@ -213,45 +207,36 @@ export const SettingsAgentForm = ({ mode }: { mode: 'create' | 'edit' }) => {
>
<SettingsPageContainer>
<Section>
- {!isAskAIAgent && (
- <H2Title title={pageTitle} description={pageDescription} />
- )}
+ <H2Title title={pageTitle} description={pageDescription} />
{isEditMode && loading ? (
<SettingsAgentDetailSkeletonLoader />
) : (
<StyledContentContainer>
- {isAskAIAgent ? (
- <SettingsAgentHandoffSection agentId={agent?.id ?? ''} />
- ) : (
- <>
- <SettingsAIAgentForm
- formValues={formValues}
- onFieldChange={handleFieldChange}
- disabled={
- isReadonlyMode ||
- (isEditMode ? !agent?.isCustom : false)
- }
- />
- {!isReadonlyMode &&
- isEditMode &&
- agent &&
- formValues.isCustom && (
- <Section>
- <H2Title
- title={t`Danger zone`}
- description={t`Delete this agent`}
- />
- <Button
- accent="danger"
- variant="secondary"
- title={t`Delete Agent`}
- Icon={IconTrash}
- onClick={() => openModal(DELETE_AGENT_MODAL_ID)}
- />
- </Section>
- )}
- </>
- )}
+ <SettingsAIAgentForm
+ formValues={formValues}
+ onFieldChange={handleFieldChange}
+ disabled={
+ isReadonlyMode || (isEditMode ? !agent?.isCustom : false)
+ }
+ />
+ {!isReadonlyMode &&
+ isEditMode &&
+ agent &&
+ formValues.isCustom && (
+ <Section>
+ <H2Title
+ title={t`Danger zone`}
+ description={t`Delete this agent`}
+ />
+ <Button
+ accent="danger"
+ variant="secondary"
+ title={t`Delete Agent`}
+ Icon={IconTrash}
+ onClick={() => openModal(DELETE_AGENT_MODAL_ID)}
+ />
+ </Section>
+ )}
</StyledContentContainer>
)}
</Section>
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAIAgentsTable.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIAgentsTable.tsx
index 5936576ef43..4d7f36d5e3e 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAIAgentsTable.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIAgentsTable.tsx
@@ -10,11 +10,13 @@ import { useSortedArray } from '@/ui/layout/table/hooks/useSortedArray';
import { useTheme } from '@emotion/react';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath } from 'twenty-shared/utils';
-import { IconChevronRight, IconSearch } from 'twenty-ui/display';
-import { type Agent } from '~/generated-metadata/graphql';
+import { H2Title, IconChevronRight, IconSearch } from 'twenty-ui/display';
import { SETTINGS_AI_AGENT_TABLE_METADATA } from '~/pages/settings/ai/constants/SettingsAiAgentTableMetadata';
import { normalizeSearchText } from '~/utils/normalizeSearchText';
+import Skeleton from 'react-loading-skeleton';
+import { Section } from 'twenty-ui/layout';
+import { useFindManyAgentsQuery } from '~/generated-metadata/graphql';
import {
SettingsAIAgentTableRow,
StyledAIAgentTableRow,
@@ -34,17 +36,20 @@ const StyledTableHeaderRow = styled(StyledAIAgentTableRow)`
`;
export const SettingsAIAgentsTable = ({
- agents,
withSearchBar = false,
}: {
- agents: Agent[];
withSearchBar?: boolean;
}) => {
+ const { data, loading } = useFindManyAgentsQuery();
+
const { t } = useLingui();
const theme = useTheme();
const [searchTerm, setSearchTerm] = useState('');
- const sortedAgents = useSortedArray(agents, SETTINGS_AI_AGENT_TABLE_METADATA);
+ const sortedAgents = useSortedArray(
+ data?.findManyAgents || [],
+ SETTINGS_AI_AGENT_TABLE_METADATA,
+ );
const filteredAgents = sortedAgents.filter((agent) => {
const searchNormalized = normalizeSearchText(searchTerm);
@@ -55,7 +60,12 @@ export const SettingsAIAgentsTable = ({
});
return (
- <>
+ <Section>
+ <H2Title
+ title={t`Agents`}
+ description={t`Agents used to route queries to specialized agents`}
+ />
+
{withSearchBar && (
<StyledSearchInput
instanceId="settings-ai-agents-search"
@@ -82,6 +92,10 @@ export const SettingsAIAgentsTable = ({
)}
<TableHeader />
</StyledTableHeaderRow>
+ {loading &&
+ Array.from({ length: 3 }).map((_, index) => (
+ <Skeleton height={32} borderRadius={4} key={index} />
+ ))}
{filteredAgents.map((agent) => (
<SettingsAIAgentTableRow
key={agent.id}
@@ -98,6 +112,6 @@ export const SettingsAIAgentsTable = ({
/>
))}
</StyledTable>
- </>
+ </Section>
);
};
diff --git a/packages/twenty-front/src/modules/settings/integrations/components/SettingsIntegrationMCP.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
similarity index 58%
rename from packages/twenty-front/src/modules/settings/integrations/components/SettingsIntegrationMCP.tsx
rename to packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
index a579b38c5da..5ece591de71 100644
--- a/packages/twenty-front/src/modules/settings/integrations/components/SettingsIntegrationMCP.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
@@ -3,8 +3,14 @@ import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { Trans, useLingui } from '@lingui/react/macro';
import { useState } from 'react';
-import { IconCopy, IconDatabase, IconSitemap } from 'twenty-ui/display';
+import {
+ H2Title,
+ IconCopy,
+ IconDatabase,
+ IconSitemap,
+} from 'twenty-ui/display';
import { Button, CodeEditor } from 'twenty-ui/input';
+import { Section } from 'twenty-ui/layout';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
@@ -55,7 +61,7 @@ const StyledEditorContainer = styled.div`
}
`;
-export const SettingsIntegrationMCP = () => {
+export const SettingsAIMCP = () => {
const theme = useTheme();
const { t } = useLingui();
const { copyToClipboard } = useCopyToClipboard();
@@ -105,61 +111,67 @@ export const SettingsIntegrationMCP = () => {
};
return (
- <StyledWrapper>
- <StyledImage
- src={`/images/integrations/integration-mcp-cover-${theme.name}.svg`}
+ <Section>
+ <H2Title
+ title={t`MCP Server`}
+ description={t`Access your workspace data from your favorite MCP client like Claude Desktop, Windsurf or Cursor.`}
/>
- <StyledSchemaSelector>
- <Select
- dropdownId="mcp-schema-selector"
- value={selectedSchemaValue}
- options={options}
- onChange={onChange}
+ <StyledWrapper>
+ <StyledImage
+ src={`/images/integrations/integration-mcp-cover-${theme.name}.svg`}
/>
- <StyledLabel>
- <Trans>Interact with your workspace data</Trans>
- </StyledLabel>
- </StyledSchemaSelector>
- <StyledEditorContainer style={{ position: 'relative' }}>
- <StyledCopyButton>
- <Button
- Icon={IconCopy}
- onClick={() => {
- copyToClipboard(
- selectedOption.content,
- t`MCP Configuration copied to clipboard`,
- );
+ <StyledSchemaSelector>
+ <Select
+ dropdownId="mcp-schema-selector"
+ value={selectedSchemaValue}
+ options={options}
+ onChange={onChange}
+ />
+ <StyledLabel>
+ <Trans>Interact with your workspace data</Trans>
+ </StyledLabel>
+ </StyledSchemaSelector>
+ <StyledEditorContainer style={{ position: 'relative' }}>
+ <StyledCopyButton>
+ <Button
+ Icon={IconCopy}
+ onClick={() => {
+ copyToClipboard(
+ selectedOption.content,
+ t`MCP Configuration copied to clipboard`,
+ );
+ }}
+ type="button"
+ />
+ </StyledCopyButton>
+ <CodeEditor
+ value={selectedOption.content}
+ language="application/json"
+ options={{
+ readOnly: true,
+ domReadOnly: true,
+ renderLineHighlight: 'none',
+ renderLineHighlightOnlyWhenFocus: false,
+ lineNumbers: 'off',
+ folding: false,
+ selectionHighlight: false,
+ occurrencesHighlight: 'off',
+ hover: {
+ enabled: false,
+ },
+ guides: {
+ indentation: false,
+ bracketPairs: false,
+ bracketPairsHorizontal: false,
+ },
+ padding: {
+ top: 12,
+ },
}}
- type="button"
+ height="220px"
/>
- </StyledCopyButton>
- <CodeEditor
- value={selectedOption.content}
- language="application/json"
- options={{
- readOnly: true,
- domReadOnly: true,
- renderLineHighlight: 'none',
- renderLineHighlightOnlyWhenFocus: false,
- lineNumbers: 'off',
- folding: false,
- selectionHighlight: false,
- occurrencesHighlight: 'off',
- hover: {
- enabled: false,
- },
- guides: {
- indentation: false,
- bracketPairs: false,
- bracketPairsHorizontal: false,
- },
- padding: {
- top: 12,
- },
- }}
- height="220px"
- />
- </StyledEditorContainer>
- </StyledWrapper>
+ </StyledEditorContainer>
+ </StyledWrapper>
+ </Section>
);
};
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAIRouterSettings.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIRouterSettings.tsx
new file mode 100644
index 00000000000..518c6995110
--- /dev/null
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIRouterSettings.tsx
@@ -0,0 +1,105 @@
+import styled from '@emotion/styled';
+import { useRecoilState } from 'recoil';
+
+import { useAiModelOptions } from '@/ai/hooks/useAiModelOptions';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import {
+ StyledSettingsOptionCardContent,
+ StyledSettingsOptionCardDescription,
+ StyledSettingsOptionCardIcon,
+ StyledSettingsOptionCardTitle,
+} from '@/settings/components/SettingsOptions/SettingsOptionCardContentBase';
+import { SettingsOptionIconCustomizer } from '@/settings/components/SettingsOptions/SettingsOptionIconCustomizer';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { Select } from '@/ui/input/components/Select';
+import { t } from '@lingui/core/macro';
+import { H2Title, IconCpu } from 'twenty-ui/display';
+import { Card, Section } from 'twenty-ui/layout';
+import { useUpdateWorkspaceMutation } from '~/generated-metadata/graphql';
+
+const StyledSelectContainer = styled.div`
+ justify-content: flex-end;
+ margin-left: auto;
+ max-width: 120px;
+`;
+
+export const SettingsAIRouterSettings = () => {
+ const { enqueueSuccessSnackBar, enqueueErrorSnackBar } = useSnackBar();
+ const [currentWorkspace, setCurrentWorkspace] = useRecoilState(
+ currentWorkspaceState,
+ );
+ const [updateWorkspace] = useUpdateWorkspaceMutation();
+
+ const modelOptions = useAiModelOptions();
+
+ const handleModelChange = async (value: string) => {
+ if (!currentWorkspace?.id) {
+ return;
+ }
+
+ const newValue = value;
+ const previousValue = currentWorkspace?.routerModel || 'auto';
+
+ try {
+ setCurrentWorkspace({
+ ...currentWorkspace,
+ routerModel: newValue,
+ });
+
+ await updateWorkspace({
+ variables: {
+ input: {
+ routerModel: newValue,
+ },
+ },
+ });
+
+ enqueueSuccessSnackBar({
+ message: t`Router model updated successfully`,
+ });
+ } catch {
+ setCurrentWorkspace({
+ ...currentWorkspace,
+ routerModel: previousValue,
+ });
+
+ enqueueErrorSnackBar({
+ message: t`Failed to update router model`,
+ });
+ }
+ };
+
+ return (
+ <Section>
+ <H2Title
+ title={t`Router`}
+ description={t`Router is used in the chat to dispatch to the right agent`}
+ />
+
+ <Card rounded>
+ <StyledSettingsOptionCardContent>
+ <StyledSettingsOptionCardIcon>
+ <SettingsOptionIconCustomizer Icon={IconCpu} />
+ </StyledSettingsOptionCardIcon>
+ <div>
+ <StyledSettingsOptionCardTitle>
+ {t`Router Model`}
+ </StyledSettingsOptionCardTitle>
+ <StyledSettingsOptionCardDescription>
+ {t`Fast model to route to the right agent`}
+ </StyledSettingsOptionCardDescription>
+ </div>
+ <StyledSelectContainer>
+ <Select
+ dropdownId="router-model-select"
+ value={currentWorkspace?.routerModel || 'auto'}
+ onChange={handleModelChange}
+ options={modelOptions}
+ selectSizeVariant="small"
+ />
+ </StyledSelectContainer>
+ </StyledSettingsOptionCardContent>
+ </Card>
+ </Section>
+ );
+};
diff --git a/packages/twenty-front/src/pages/settings/ai/forms/components/SettingsAIAgentForm.tsx b/packages/twenty-front/src/pages/settings/ai/forms/components/SettingsAIAgentForm.tsx
index f326db73824..5d05204b14d 100644
--- a/packages/twenty-front/src/pages/settings/ai/forms/components/SettingsAIAgentForm.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/forms/components/SettingsAIAgentForm.tsx
@@ -155,9 +155,10 @@ export const SettingsAIAgentForm = ({
<StyledFormContainer>
<TextArea
textAreaId="agent-prompt-textarea"
- label={t`System Prompt*`}
+ label={t`System Prompt`}
placeholder={t`Enter the system prompt that defines this agent's behavior and capabilities`}
minRows={6}
+ maxRows={15}
value={formValues.prompt}
onChange={(value) => onFieldChange('prompt', value)}
disabled={disabled}
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailContentTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailContentTab.tsx
index 50a2a4a9c42..b72b93c77b5 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailContentTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailContentTab.tsx
@@ -1,13 +1,13 @@
-import { Section } from 'twenty-ui/layout';
-import { H2Title } from 'twenty-ui/display';
-import { t } from '@lingui/core/macro';
+import { objectMetadataItemsState } from '@/object-metadata/states/objectMetadataItemsState';
import { SettingsServerlessFunctionsTable } from '@/settings/serverless-functions/components/SettingsServerlessFunctionsTable';
-import { SettingsAIAgentsTable } from '~/pages/settings/ai/components/SettingsAIAgentsTable';
-import { SettingsObjectTable } from '~/pages/settings/data-model/SettingsObjectTable';
-import { isDefined } from 'twenty-shared/utils';
+import { t } from '@lingui/core/macro';
import { useRecoilValue } from 'recoil';
+import { isDefined } from 'twenty-shared/utils';
+import { H2Title } from 'twenty-ui/display';
+import { Section } from 'twenty-ui/layout';
import { type Application } from '~/generated/graphql';
-import { objectMetadataItemsState } from '@/object-metadata/states/objectMetadataItemsState';
+import { SettingsAIAgentsTable } from '~/pages/settings/ai/components/SettingsAIAgentsTable';
+import { SettingsObjectTable } from '~/pages/settings/data-model/SettingsObjectTable';
export const SettingsApplicationDetailContentTab = ({
application,
@@ -54,7 +54,7 @@ export const SettingsApplicationDetailContentTab = ({
title={t`Application agents`}
description={t`Agents created by application`}
/>
- <SettingsAIAgentsTable agents={agents} withSearchBar={false} />
+ <SettingsAIAgentsTable withSearchBar={false} />
</Section>
)}
{shouldDisplayObjects && (
diff --git a/packages/twenty-front/src/pages/settings/integrations/SettingsIntegrationMCPPage.tsx b/packages/twenty-front/src/pages/settings/integrations/SettingsIntegrationMCPPage.tsx
deleted file mode 100644
index 564e8ee1c45..00000000000
--- a/packages/twenty-front/src/pages/settings/integrations/SettingsIntegrationMCPPage.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
-import { SettingsIntegrationMCP } from '@/settings/integrations/components/SettingsIntegrationMCP';
-import { SubMenuTopBarContainer } from '@/ui/layout/page/components/SubMenuTopBarContainer';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath } from 'twenty-shared/utils';
-import { H2Title } from 'twenty-ui/display';
-import { Section } from 'twenty-ui/layout';
-
-export const SettingsIntegrationMCPPage = () => {
- const { t } = useLingui();
-
- return (
- <SubMenuTopBarContainer
- title={t`Integrations`}
- links={[
- {
- children: <Trans>Workspace</Trans>,
- href: getSettingsPath(SettingsPath.Workspace),
- },
- { children: <Trans>Integrations</Trans> },
- { children: <Trans>MCP</Trans> },
- ]}
- >
- <SettingsPageContainer>
- <Section>
- <H2Title
- title={`MCP Server`}
- description={`Access your workspace data from your favorite MCP client like Claude Desktop, Windsurf or Cursor.`}
- />
- <SettingsIntegrationMCP />
- </Section>
- </SettingsPageContainer>
- </SubMenuTopBarContainer>
- );
-};
diff --git a/packages/twenty-front/src/testing/mock-data/users.ts b/packages/twenty-front/src/testing/mock-data/users.ts
index 776b06b2de6..0d581f2951c 100644
--- a/packages/twenty-front/src/testing/mock-data/users.ts
+++ b/packages/twenty-front/src/testing/mock-data/users.ts
@@ -12,8 +12,8 @@ import {
WorkspaceMemberDateFormatEnum,
WorkspaceMemberTimeFormatEnum,
} from '~/generated/graphql';
-import { generatedMockObjectMetadataItems } from '~/testing/utils/generatedMockObjectMetadataItems';
import { mockBillingPlans } from '~/testing/mock-data/billing-plans';
+import { generatedMockObjectMetadataItems } from '~/testing/utils/generatedMockObjectMetadataItems';
type MockedUser = Pick<
User,
@@ -85,6 +85,7 @@ export const mockCurrentWorkspace: Workspace = {
updatedAt: '2023-04-26T10:23:42.33625+00:00',
metadataVersion: 1,
trashRetentionDays: 14,
+ routerModel: 'auto',
currentBillingSubscription: {
__typename: 'BillingSubscription',
id: '7efbc3f7-6e5e-4128-957e-8d86808cdf6a',
diff --git a/packages/twenty-server/src/database/typeorm/core/migrations/common/1760985484643-AddRouterModelToWorkspace.ts b/packages/twenty-server/src/database/typeorm/core/migrations/common/1760985484643-AddRouterModelToWorkspace.ts
new file mode 100644
index 00000000000..30225e978ce
--- /dev/null
+++ b/packages/twenty-server/src/database/typeorm/core/migrations/common/1760985484643-AddRouterModelToWorkspace.ts
@@ -0,0 +1,19 @@
+import { type MigrationInterface, type QueryRunner } from 'typeorm';
+
+export class AddRouterModelToWorkspace1760985484643
+ implements MigrationInterface
+{
+ name = 'AddRouterModelToWorkspace1760985484643';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."workspace" ADD "routerModel" character varying NOT NULL DEFAULT 'auto'`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."workspace" DROP COLUMN "routerModel"`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/typeorm/core/migrations/common/1760994964826-RemoveDefaultAgentAndThreadAgentId.ts b/packages/twenty-server/src/database/typeorm/core/migrations/common/1760994964826-RemoveDefaultAgentAndThreadAgentId.ts
new file mode 100644
index 00000000000..50d07f6ba0b
--- /dev/null
+++ b/packages/twenty-server/src/database/typeorm/core/migrations/common/1760994964826-RemoveDefaultAgentAndThreadAgentId.ts
@@ -0,0 +1,37 @@
+import { type MigrationInterface, type QueryRunner } from 'typeorm';
+
+export class RemoveDefaultAgentAndThreadAgentId1760994964826
+ implements MigrationInterface
+{
+ name = 'RemoveDefaultAgentAndThreadAgentId1760994964826';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."agentChatThread" DROP CONSTRAINT "FK_d0bdc80c68a48b1f26727aabfe6"`,
+ );
+ await queryRunner.query(
+ `DROP INDEX "core"."IDX_d0bdc80c68a48b1f26727aabfe"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."workspace" DROP COLUMN "defaultAgentId"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."agentChatThread" DROP COLUMN "agentId"`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."agentChatThread" ADD "agentId" uuid NOT NULL`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."workspace" ADD "defaultAgentId" uuid`,
+ );
+ await queryRunner.query(
+ `CREATE INDEX "IDX_d0bdc80c68a48b1f26727aabfe" ON "core"."agentChatThread" ("agentId") `,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."agentChatThread" ADD CONSTRAINT "FK_d0bdc80c68a48b1f26727aabfe6" FOREIGN KEY ("agentId") REFERENCES "core"."agent"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/ai/constants/ai-models.const.ts b/packages/twenty-server/src/engine/core-modules/ai/constants/ai-models.const.ts
index a5de428f91b..449737c0454 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/constants/ai-models.const.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/constants/ai-models.const.ts
@@ -19,12 +19,27 @@ export type ModelId =
| 'grok-4'
| string; // Allow custom model names
+export type SupportedFileType =
+ | 'image/png'
+ | 'image/jpeg'
+ | 'image/gif'
+ | 'image/webp'
+ | 'application/pdf'
+ | 'text/plain'
+ | 'text/html'
+ | 'text/csv'
+ | 'application/json';
+
export interface AIModelConfig {
modelId: ModelId;
label: string;
+ description: string;
provider: ModelProvider;
inputCostPer1kTokensInCents: number;
outputCostPer1kTokensInCents: number;
+ contextWindowTokens: number;
+ maxOutputTokens: number;
+ supportedFileTypes?: SupportedFileType[];
doesSupportThinking?: boolean;
nativeCapabilities?: {
webSearch?: boolean;
@@ -36,9 +51,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'gpt-4o',
label: 'GPT-4o',
+ description:
+ 'Most advanced multimodal model with strong reasoning, vision, and coding capabilities',
provider: ModelProvider.OPENAI,
inputCostPer1kTokensInCents: 0.25,
outputCostPer1kTokensInCents: 1.0,
+ contextWindowTokens: 128000,
+ maxOutputTokens: 16384,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: true,
},
@@ -46,9 +66,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'gpt-4o-mini',
label: 'GPT-4o Mini',
+ description:
+ 'Fast and cost-efficient model for lightweight tasks and high-volume operations',
provider: ModelProvider.OPENAI,
inputCostPer1kTokensInCents: 0.015,
outputCostPer1kTokensInCents: 0.06,
+ contextWindowTokens: 128000,
+ maxOutputTokens: 16384,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: true,
},
@@ -56,9 +81,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'gpt-4-turbo',
label: 'GPT-4 Turbo',
+ description:
+ 'Previous generation high-performance model with vision capabilities',
provider: ModelProvider.OPENAI,
inputCostPer1kTokensInCents: 1.0,
outputCostPer1kTokensInCents: 3.0,
+ contextWindowTokens: 128000,
+ maxOutputTokens: 4096,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: false,
},
@@ -66,9 +96,23 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'claude-opus-4-20250514',
label: 'Claude Opus 4',
+ description:
+ 'Most powerful Claude model with extended thinking for complex reasoning tasks',
provider: ModelProvider.ANTHROPIC,
inputCostPer1kTokensInCents: 1.5,
outputCostPer1kTokensInCents: 7.5,
+ contextWindowTokens: 200000,
+ maxOutputTokens: 8192,
+ supportedFileTypes: [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'application/pdf',
+ 'text/plain',
+ 'text/html',
+ 'text/csv',
+ ],
doesSupportThinking: true,
nativeCapabilities: {
webSearch: true,
@@ -77,9 +121,23 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'claude-sonnet-4-20250514',
label: 'Claude Sonnet 4',
+ description:
+ 'Balanced model with strong performance and extended thinking capabilities',
provider: ModelProvider.ANTHROPIC,
inputCostPer1kTokensInCents: 0.3,
outputCostPer1kTokensInCents: 1.5,
+ contextWindowTokens: 200000,
+ maxOutputTokens: 8192,
+ supportedFileTypes: [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'application/pdf',
+ 'text/plain',
+ 'text/html',
+ 'text/csv',
+ ],
doesSupportThinking: true,
nativeCapabilities: {
webSearch: true,
@@ -88,9 +146,23 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'claude-3-5-haiku-20241022',
label: 'Claude Haiku 3.5',
+ description:
+ 'Fast and efficient model optimized for speed and cost-effectiveness',
provider: ModelProvider.ANTHROPIC,
inputCostPer1kTokensInCents: 0.08,
outputCostPer1kTokensInCents: 0.4,
+ contextWindowTokens: 200000,
+ maxOutputTokens: 8192,
+ supportedFileTypes: [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'application/pdf',
+ 'text/plain',
+ 'text/html',
+ 'text/csv',
+ ],
doesSupportThinking: false,
nativeCapabilities: {
webSearch: true,
@@ -99,9 +171,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'grok-3',
label: 'Grok-3',
+ description:
+ 'Advanced model with web and Twitter search, optimized for real-time information',
provider: ModelProvider.XAI,
inputCostPer1kTokensInCents: 0.3,
outputCostPer1kTokensInCents: 1.5,
+ contextWindowTokens: 131072,
+ maxOutputTokens: 8192,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: true,
twitterSearch: true,
@@ -110,9 +187,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'grok-3-mini',
label: 'Grok-3 Mini',
+ description:
+ 'Lightweight model with web and Twitter search for fast, cost-effective operations',
provider: ModelProvider.XAI,
inputCostPer1kTokensInCents: 0.03,
outputCostPer1kTokensInCents: 0.05,
+ contextWindowTokens: 131072,
+ maxOutputTokens: 8192,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: true,
twitterSearch: true,
@@ -121,9 +203,14 @@ export const AI_MODELS: AIModelConfig[] = [
{
modelId: 'grok-4',
label: 'Grok-4',
+ description:
+ 'Most capable Grok model with enhanced reasoning, web and Twitter search',
provider: ModelProvider.XAI,
inputCostPer1kTokensInCents: 0.5,
outputCostPer1kTokensInCents: 2.5,
+ contextWindowTokens: 131072,
+ maxOutputTokens: 8192,
+ supportedFileTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
nativeCapabilities: {
webSearch: true,
twitterSearch: true,
diff --git a/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.spec.ts b/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.spec.ts
index b26afd8e571..2e009a2a648 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.spec.ts
@@ -32,7 +32,7 @@ describe('AiController', () => {
};
const mockAiModelRegistryService = {
- getDefaultModel: jest.fn().mockReturnValue({
+ getDefaultPerformanceModel: jest.fn().mockReturnValue({
modelId: 'gpt-4o',
provider: ModelProvider.OPENAI,
model: openai('gpt-4o'),
@@ -90,7 +90,7 @@ describe('AiController', () => {
const mockModel = openai('gpt-4o');
- aiModelRegistryService.getDefaultModel.mockReturnValue({
+ aiModelRegistryService.getDefaultPerformanceModel.mockReturnValue({
modelId: 'gpt-4o',
provider: ModelProvider.OPENAI,
model: mockModel,
@@ -153,7 +153,7 @@ describe('AiController', () => {
const mockRes = {} as any;
- aiModelRegistryService.getDefaultModel.mockReturnValue({
+ aiModelRegistryService.getDefaultPerformanceModel.mockReturnValue({
modelId: 'gpt-4o',
provider: ModelProvider.OPENAI,
model: openai('gpt-4o'),
diff --git a/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.ts b/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.ts
index e01fefa4288..787e6a491fc 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/controllers/ai.controller.ts
@@ -64,7 +64,8 @@ export class AiController {
}
try {
- const registeredModel = this.aiModelRegistryService.getDefaultModel();
+ const registeredModel =
+ this.aiModelRegistryService.getDefaultPerformanceModel();
const result = this.aiService.streamText({
messages,
diff --git a/packages/twenty-server/src/engine/core-modules/ai/services/ai-model-registry.service.ts b/packages/twenty-server/src/engine/core-modules/ai/services/ai-model-registry.service.ts
index 9ecd75fe509..0a1e186d8df 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/services/ai-model-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/services/ai-model-registry.service.ts
@@ -138,8 +138,25 @@ export class AiModelRegistryService {
return Array.from(this.modelRegistry.values());
}
- getDefaultModel(): RegisteredAIModel {
- const defaultModelId = this.twentyConfigService.get('DEFAULT_MODEL_ID');
+ getDefaultSpeedModel(): RegisteredAIModel {
+ const defaultModelId = this.twentyConfigService.get(
+ 'DEFAULT_AI_SPEED_MODEL_ID',
+ );
+ let model = this.getModel(defaultModelId);
+
+ if (!model) {
+ const availableModels = this.getAvailableModels();
+
+ model = availableModels[0];
+ }
+
+ return model;
+ }
+
+ getDefaultPerformanceModel(): RegisteredAIModel {
+ const defaultModelId = this.twentyConfigService.get(
+ 'DEFAULT_AI_PERFORMANCE_MODEL_ID',
+ );
let model = this.getModel(defaultModelId);
if (!model) {
@@ -153,7 +170,7 @@ export class AiModelRegistryService {
getEffectiveModelConfig(modelId: string): AIModelConfig {
if (modelId === 'auto') {
- const defaultModel = this.getDefaultModel();
+ const defaultModel = this.getDefaultPerformanceModel();
if (!defaultModel) {
throw new Error(
@@ -195,9 +212,12 @@ export class AiModelRegistryService {
return {
modelId: registeredModel.modelId,
label: registeredModel.modelId,
+ description: `Custom model: ${registeredModel.modelId}`,
provider: registeredModel.provider,
inputCostPer1kTokensInCents: 0,
outputCostPer1kTokensInCents: 0,
+ contextWindowTokens: 128000,
+ maxOutputTokens: 4096,
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/ai/services/ai.service.ts b/packages/twenty-server/src/engine/core-modules/ai/services/ai.service.ts
index 52d6c070024..c731eecf10e 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/services/ai.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/services/ai.service.ts
@@ -11,7 +11,7 @@ export class AiService {
getModel(modelId: string | undefined) {
const registeredModel = modelId
? this.aiModelRegistryService.getModel(modelId)
- : this.aiModelRegistryService.getDefaultModel();
+ : this.aiModelRegistryService.getDefaultPerformanceModel();
if (!registeredModel) {
throw new Error(
diff --git a/packages/twenty-server/src/engine/core-modules/ai/services/tool.service.ts b/packages/twenty-server/src/engine/core-modules/ai/services/tool.service.ts
index d0dab789585..1ceb6c277ca 100644
--- a/packages/twenty-server/src/engine/core-modules/ai/services/tool.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/ai/services/tool.service.ts
@@ -6,13 +6,11 @@ import { CreateRecordService } from 'src/engine/core-modules/record-crud/service
import { DeleteRecordService } from 'src/engine/core-modules/record-crud/services/delete-record.service';
import { FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
import { UpdateRecordService } from 'src/engine/core-modules/record-crud/services/update-record.service';
-import {
- generateBulkDeleteToolSchema,
- generateFindOneToolSchema,
- generateFindToolSchema,
- generateSoftDeleteToolSchema,
- getRecordInputSchema,
-} from 'src/engine/metadata-modules/agent/utils/agent-tool-schema.utils';
+import { BulkDeleteToolInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/bulk-delete-tool.zod-schema';
+import { generateFindToolInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/find-tool.zod-schema';
+import { FindOneToolInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/find-one-tool.zod-schema';
+import { generateRecordInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/record-input.zod-schema';
+import { SoftDeleteToolInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/soft-delete-tool.zod-schema';
import { isWorkflowRunObject } from 'src/engine/metadata-modules/agent/utils/is-workflow-run-object.util';
import { type ActorMetadata } from 'src/engine/metadata-modules/field-metadata/composite-types/actor.composite-type';
import { ObjectMetadataService } from 'src/engine/metadata-modules/object-metadata/object-metadata.service';
@@ -92,7 +90,7 @@ export class ToolService {
if (objectPermission.canUpdateObjectRecords) {
tools[`create_${objectMetadata.nameSingular}`] = {
description: `Create a new ${objectMetadata.labelSingular} record. Provide all required fields and any optional fields you want to set. The system will automatically handle timestamps and IDs. Returns the created record with all its data.`,
- inputSchema: getRecordInputSchema(objectMetadata),
+ inputSchema: generateRecordInputSchema(objectMetadata),
execute: async (parameters) => {
return this.createRecordService.execute({
objectName: objectMetadata.nameSingular,
@@ -106,7 +104,7 @@ export class ToolService {
tools[`update_${objectMetadata.nameSingular}`] = {
description: `Update an existing ${objectMetadata.labelSingular} record. Provide the record ID and only the fields you want to change. Unspecified fields will remain unchanged. Returns the updated record with all current data.`,
- inputSchema: getRecordInputSchema(objectMetadata),
+ inputSchema: generateRecordInputSchema(objectMetadata),
execute: async (parameters) => {
const { id, ...objectRecord } = parameters.input;
@@ -123,14 +121,15 @@ export class ToolService {
if (objectPermission.canReadObjectRecords) {
tools[`find_${objectMetadata.nameSingular}`] = {
- description: `Search for ${objectMetadata.labelSingular} records using flexible filtering criteria. Supports exact matches, pattern matching, ranges, and null checks. Use limit/offset for pagination. Returns an array of matching records with their full data.`,
- inputSchema: generateFindToolSchema(objectMetadata),
+ description: `Search for ${objectMetadata.labelSingular} records using flexible filtering criteria. Supports exact matches, pattern matching, ranges, and null checks. Use limit/offset for pagination and orderBy for sorting. Returns an array of matching records with their full data.`,
+ inputSchema: generateFindToolInputSchema(objectMetadata),
execute: async (parameters) => {
- const { limit, offset, ...filter } = parameters.input;
+ const { limit, offset, orderBy, ...filter } = parameters.input;
return this.findRecordsService.execute({
objectName: objectMetadata.nameSingular,
filter,
+ orderBy,
limit,
offset,
workspaceId,
@@ -141,7 +140,7 @@ export class ToolService {
tools[`find_one_${objectMetadata.nameSingular}`] = {
description: `Retrieve a single ${objectMetadata.labelSingular} record by its unique ID. Use this when you know the exact record ID and need the complete record data. Returns the full record or an error if not found.`,
- inputSchema: generateFindOneToolSchema(),
+ inputSchema: FindOneToolInputSchema,
execute: async (parameters) => {
return this.findRecordsService.execute({
objectName: objectMetadata.nameSingular,
@@ -157,7 +156,7 @@ export class ToolService {
if (objectPermission.canSoftDeleteObjectRecords) {
tools[`soft_delete_${objectMetadata.nameSingular}`] = {
description: `Soft delete a ${objectMetadata.labelSingular} record by marking it as deleted. The record remains in the database but is hidden from normal queries. This is reversible and preserves all data. Use this for temporary removal.`,
- inputSchema: generateSoftDeleteToolSchema(),
+ inputSchema: SoftDeleteToolInputSchema,
execute: async (parameters) => {
return this.deleteRecordService.execute({
objectName: objectMetadata.nameSingular,
@@ -171,7 +170,7 @@ export class ToolService {
tools[`soft_delete_many_${objectMetadata.nameSingular}`] = {
description: `Soft delete multiple ${objectMetadata.labelSingular} records at once by providing an array of record IDs. All records are marked as deleted but remain in the database. This is efficient for bulk operations and preserves all data.`,
- inputSchema: generateBulkDeleteToolSchema(),
+ inputSchema: BulkDeleteToolInputSchema,
execute: async (parameters) => {
return this.softDeleteManyRecords(
objectMetadata.nameSingular,
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/create-record-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/create-record-params.type.ts
index 79a1efcd5dc..65569d735f6 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/create-record-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/create-record-params.type.ts
@@ -1,11 +1,13 @@
-import { type ObjectRecordProperties } from 'src/engine/core-modules/record-crud/types/object-record-properties.type';
-import { type ActorMetadata } from 'src/engine/metadata-modules/field-metadata/composite-types/actor.composite-type';
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import {
+ type CreateRecordExecutionContext,
+ type RecordCrudExecutionContext,
+} from './execution-context.type';
+import { type CreateRecordInput } from './record-crud-input.type';
-export type CreateRecordParams = {
- objectName: string;
- objectRecord: ObjectRecordProperties;
- workspaceId: string;
- rolePermissionConfig?: RolePermissionConfig;
- createdBy?: ActorMetadata;
-};
+export type CreateRecordParams = CreateRecordInput &
+ Omit<CreateRecordExecutionContext, 'upsert'> & {
+ upsert?: never;
+ };
+
+export type CreateRecordParamsWithContext = CreateRecordInput &
+ RecordCrudExecutionContext;
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-record-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-record-params.type.ts
index 347ded94bdd..9c5fc793546 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-record-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/delete-record-params.type.ts
@@ -1,9 +1,7 @@
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import { type RecordCrudExecutionContext } from './execution-context.type';
+import { type DeleteRecordInput } from './record-crud-input.type';
-export type DeleteRecordParams = {
- objectName: string;
- objectRecordId: string;
- workspaceId: string;
- rolePermissionConfig?: RolePermissionConfig;
- soft?: boolean;
-};
+export type DeleteRecordParams = DeleteRecordInput &
+ RecordCrudExecutionContext & {
+ soft?: boolean;
+ };
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/execution-context.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/execution-context.type.ts
new file mode 100644
index 00000000000..f9dbe97fd37
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/execution-context.type.ts
@@ -0,0 +1,11 @@
+import { type ActorMetadata } from 'src/engine/metadata-modules/field-metadata/composite-types/actor.composite-type';
+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+
+export type RecordCrudExecutionContext = {
+ workspaceId: string;
+ rolePermissionConfig?: RolePermissionConfig;
+};
+
+export type CreateRecordExecutionContext = RecordCrudExecutionContext & {
+ createdBy?: ActorMetadata;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/find-records-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/find-records-params.type.ts
index 9af8d9d3431..0b885831d59 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/find-records-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/find-records-params.type.ts
@@ -1,20 +1,14 @@
-import {
- type ObjectRecordFilter,
- type ObjectRecordOrderBy,
-} from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+import { type ObjectRecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import { type RecordCrudExecutionContext } from './execution-context.type';
+import { type FindRecordsInput } from './record-crud-input.type';
-export type FindRecordsParams = {
- objectName: string;
- filter?:
- | Record<string, unknown>
- | Record<string, unknown>[]
- | Partial<ObjectRecordFilter>
- | Partial<ObjectRecordFilter>[];
- orderBy?: Partial<ObjectRecordOrderBy>;
- limit?: number;
- offset?: number;
- workspaceId: string;
- rolePermissionConfig?: RolePermissionConfig;
-};
+export type FindRecordsParams = FindRecordsInput &
+ RecordCrudExecutionContext & {
+ filter?:
+ | Record<string, unknown>
+ | Record<string, unknown>[]
+ | Partial<ObjectRecordFilter>
+ | Partial<ObjectRecordFilter>[];
+ offset?: number;
+ };
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts
new file mode 100644
index 00000000000..d63b930e321
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/record-crud-input.type.ts
@@ -0,0 +1,43 @@
+import {
+ type ObjectRecordFilter,
+ type ObjectRecordOrderBy,
+} from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+
+import { type ObjectRecordProperties } from './object-record-properties.type';
+
+export type CreateRecordInput = {
+ objectName: string;
+ objectRecord: ObjectRecordProperties;
+ upsert?: boolean;
+};
+
+export type UpdateRecordInput = {
+ objectName: string;
+ objectRecordId: string;
+ objectRecord: ObjectRecordProperties;
+ fieldsToUpdate?: string[];
+};
+
+export type DeleteRecordInput = {
+ objectName: string;
+ objectRecordId: string;
+};
+
+export type FindRecordsInput = {
+ objectName: string;
+ filter?: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ recordFilterGroups?: any;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ recordFilters?: any;
+ gqlOperationFilter?: Partial<ObjectRecordFilter>[];
+ };
+ orderBy?: Partial<ObjectRecordOrderBy>;
+ limit?: number;
+};
+
+export type UpsertRecordInput = {
+ objectName: string;
+ objectRecord: ObjectRecordProperties;
+ fieldsToUpdate?: string[];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/update-record-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/update-record-params.type.ts
index 7901abf6b44..19e3f723c86 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/update-record-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/update-record-params.type.ts
@@ -1,11 +1,4 @@
-import { type ObjectRecordProperties } from 'src/engine/core-modules/record-crud/types/object-record-properties.type';
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import { type RecordCrudExecutionContext } from './execution-context.type';
+import { type UpdateRecordInput } from './record-crud-input.type';
-export type UpdateRecordParams = {
- objectName: string;
- objectRecordId: string;
- objectRecord: ObjectRecordProperties;
- fieldsToUpdate?: string[];
- workspaceId: string;
- rolePermissionConfig?: RolePermissionConfig;
-};
+export type UpdateRecordParams = UpdateRecordInput & RecordCrudExecutionContext;
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/types/upsert-record-params.type.ts b/packages/twenty-server/src/engine/core-modules/record-crud/types/upsert-record-params.type.ts
index 7995ab84dab..e4a676e480d 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/types/upsert-record-params.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/types/upsert-record-params.type.ts
@@ -1,10 +1,4 @@
-import { type ObjectRecordProperties } from 'src/engine/core-modules/record-crud/types/object-record-properties.type';
-import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import { type RecordCrudExecutionContext } from './execution-context.type';
+import { type UpsertRecordInput } from './record-crud-input.type';
-export type UpsertRecordParams = {
- objectName: string;
- objectRecord: ObjectRecordProperties;
- fieldsToUpdate?: string[];
- workspaceId: string;
- rolePermissionConfig?: RolePermissionConfig;
-};
+export type UpsertRecordParams = UpsertRecordInput & RecordCrudExecutionContext;
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/bulk-delete-tool.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/bulk-delete-tool.zod-schema.ts
new file mode 100644
index 00000000000..c551f63e845
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/bulk-delete-tool.zod-schema.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+
+export const BulkDeleteToolInputSchema = z.object({
+ loadingMessage: z
+ .string()
+ .optional()
+ .describe(
+ 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
+ ),
+ input: z.object({
+ filter: z
+ .object({
+ id: z
+ .object({
+ in: z
+ .array(z.string().uuid())
+ .describe('Array of record IDs to delete'),
+ })
+ .describe('Filter to select records to delete'),
+ })
+ .describe('Filter criteria to select records for bulk delete'),
+ }),
+});
+
+export type BulkDeleteToolInput = z.infer<typeof BulkDeleteToolInputSchema>;
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/field-filters.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/field-filters.zod-schema.ts
new file mode 100644
index 00000000000..b93c5623dd9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/field-filters.zod-schema.ts
@@ -0,0 +1,511 @@
+import { z } from 'zod';
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
+
+import { type FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
+import { isFieldMetadataEntityOfType } from 'src/engine/utils/is-field-metadata-of-type.util';
+
+const NullCheckEnum = z.enum(['NULL', 'NOT_NULL']);
+
+export const generateFieldFilterZodSchema = (
+ field: FieldMetadataEntity,
+): z.ZodTypeAny | null => {
+ switch (field.type) {
+ case FieldMetadataType.UUID:
+ return z
+ .object({
+ eq: z.string().uuid().optional().describe('Equals'),
+ neq: z.string().uuid().optional().describe('Not equals'),
+ in: z
+ .array(z.string().uuid())
+ .optional()
+ .describe('In array of values'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (UUID field)`);
+
+ case FieldMetadataType.TEXT:
+ case FieldMetadataType.RICH_TEXT:
+ case FieldMetadataType.RICH_TEXT_V2:
+ return z
+ .object({
+ eq: z.string().optional().describe('Equals'),
+ neq: z.string().optional().describe('Not equals'),
+ in: z.array(z.string()).optional().describe('In array of values'),
+ like: z
+ .string()
+ .optional()
+ .describe('Case-sensitive pattern match (use % for wildcards)'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Case-insensitive pattern match (use % for wildcards)'),
+ startsWith: z.string().optional().describe('Starts with'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (text field)`);
+
+ case FieldMetadataType.NUMBER:
+ case FieldMetadataType.NUMERIC:
+ case FieldMetadataType.POSITION:
+ return z
+ .object({
+ eq: z.number().optional().describe('Equals'),
+ neq: z.number().optional().describe('Not equals'),
+ gt: z.number().optional().describe('Greater than'),
+ gte: z.number().optional().describe('Greater than or equal'),
+ lt: z.number().optional().describe('Less than'),
+ lte: z.number().optional().describe('Less than or equal'),
+ in: z.array(z.number()).optional().describe('In array of values'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (number field)`);
+
+ case FieldMetadataType.BOOLEAN:
+ return z
+ .object({
+ eq: z.boolean().optional().describe('Equals'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (boolean field)`);
+
+ case FieldMetadataType.DATE_TIME:
+ case FieldMetadataType.DATE:
+ return z
+ .object({
+ eq: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Equals (ISO datetime string)'),
+ neq: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Not equals (ISO datetime string)'),
+ gt: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Greater than (ISO datetime string)'),
+ gte: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Greater than or equal (ISO datetime string)'),
+ lt: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Less than (ISO datetime string)'),
+ lte: z
+ .string()
+ .datetime()
+ .optional()
+ .describe('Less than or equal (ISO datetime string)'),
+ in: z
+ .array(z.string().datetime())
+ .optional()
+ .describe('In array of values (ISO datetime strings)'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (date field)`);
+
+ case FieldMetadataType.SELECT: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length === 0) {
+ return null;
+ }
+
+ const selectEnum = z.enum(enumValues as [string, ...string[]]);
+
+ return z
+ .object({
+ eq: selectEnum.optional().describe('Equals'),
+ neq: selectEnum.optional().describe('Not equals'),
+ in: z.array(selectEnum).optional().describe('In array of values'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (select field)`);
+ }
+
+ case FieldMetadataType.MULTI_SELECT: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length === 0) {
+ return null;
+ }
+
+ const multiSelectEnum = z.enum(enumValues as [string, ...string[]]);
+
+ return z
+ .object({
+ in: z
+ .array(multiSelectEnum)
+ .optional()
+ .describe('Contains any of these values'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ isEmptyArray: z.boolean().optional().describe('Is empty array'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (multi-select field)`);
+ }
+
+ case FieldMetadataType.RATING: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length === 0) {
+ return null;
+ }
+
+ const ratingEnum = z.enum(enumValues as [string, ...string[]]);
+
+ return z
+ .object({
+ eq: ratingEnum.optional().describe('Equals'),
+ in: z.array(ratingEnum).optional().describe('In array of values'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (rating field)`);
+ }
+
+ case FieldMetadataType.ARRAY:
+ return z
+ .object({
+ containsIlike: z
+ .string()
+ .optional()
+ .describe('Contains case-insensitive substring'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ isEmptyArray: z.boolean().optional().describe('Is empty array'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (array field)`);
+
+ case FieldMetadataType.CURRENCY:
+ return z
+ .object({
+ amountMicros: z
+ .object({
+ eq: z.number().optional().describe('Amount equals'),
+ neq: z.number().optional().describe('Amount not equals'),
+ gt: z.number().optional().describe('Amount greater than'),
+ gte: z
+ .number()
+ .optional()
+ .describe('Amount greater than or equal'),
+ lt: z.number().optional().describe('Amount less than'),
+ lte: z.number().optional().describe('Amount less than or equal'),
+ in: z
+ .array(z.number())
+ .optional()
+ .describe('Amount in array of values'),
+ is: NullCheckEnum.optional().describe(
+ 'Amount is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by amount'),
+ currencyCode: z
+ .object({
+ eq: z.string().optional().describe('Currency code equals'),
+ neq: z.string().optional().describe('Currency code not equals'),
+ in: z
+ .array(z.string())
+ .optional()
+ .describe('Currency code in array of values'),
+ is: NullCheckEnum.optional().describe(
+ 'Currency code is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by currency code'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (currency field)`);
+
+ case FieldMetadataType.FULL_NAME:
+ return z
+ .object({
+ firstName: z
+ .object({
+ eq: z.string().optional().describe('First name equals'),
+ neq: z.string().optional().describe('First name not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('First name case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('First name case-insensitive pattern match'),
+ startsWith: z
+ .string()
+ .optional()
+ .describe('First name starts with'),
+ is: NullCheckEnum.optional().describe(
+ 'First name is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by first name'),
+ lastName: z
+ .object({
+ eq: z.string().optional().describe('Last name equals'),
+ neq: z.string().optional().describe('Last name not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Last name case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Last name case-insensitive pattern match'),
+ startsWith: z
+ .string()
+ .optional()
+ .describe('Last name starts with'),
+ is: NullCheckEnum.optional().describe(
+ 'Last name is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by last name'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (full name field)`);
+
+ case FieldMetadataType.ADDRESS:
+ return z
+ .object({
+ addressStreet1: z
+ .object({
+ eq: z.string().optional().describe('Street 1 equals'),
+ neq: z.string().optional().describe('Street 1 not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Street 1 case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Street 1 case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe(
+ 'Street 1 is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by street 1'),
+ addressCity: z
+ .object({
+ eq: z.string().optional().describe('City equals'),
+ neq: z.string().optional().describe('City not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('City case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('City case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe('City is null or not null'),
+ })
+ .optional()
+ .describe('Filter by city'),
+ addressCountry: z
+ .object({
+ eq: z.string().optional().describe('Country equals'),
+ neq: z.string().optional().describe('Country not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Country case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Country case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe(
+ 'Country is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by country'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (address field)`);
+
+ case FieldMetadataType.EMAILS:
+ return z
+ .object({
+ primaryEmail: z
+ .object({
+ eq: z
+ .string()
+ .email()
+ .optional()
+ .describe('Primary email equals'),
+ neq: z
+ .string()
+ .email()
+ .optional()
+ .describe('Primary email not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Primary email case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Primary email case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe(
+ 'Primary email is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by primary email'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (emails field)`);
+
+ case FieldMetadataType.PHONES:
+ return z
+ .object({
+ primaryPhoneNumber: z
+ .object({
+ eq: z.string().optional().describe('Primary phone number equals'),
+ neq: z
+ .string()
+ .optional()
+ .describe('Primary phone number not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Primary phone number case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe(
+ 'Primary phone number case-insensitive pattern match',
+ ),
+ is: NullCheckEnum.optional().describe(
+ 'Primary phone number is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by primary phone number'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (phones field)`);
+
+ case FieldMetadataType.LINKS:
+ return z
+ .object({
+ primaryLinkUrl: z
+ .object({
+ eq: z
+ .string()
+ .url()
+ .optional()
+ .describe('Primary link URL equals'),
+ neq: z
+ .string()
+ .url()
+ .optional()
+ .describe('Primary link URL not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Primary link URL case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Primary link URL case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe(
+ 'Primary link URL is null or not null',
+ ),
+ })
+ .optional()
+ .describe('Filter by primary link URL'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (links field)`);
+
+ case FieldMetadataType.RELATION:
+ if (
+ isFieldMetadataEntityOfType(field, FieldMetadataType.RELATION) &&
+ field.settings?.relationType === RelationType.MANY_TO_ONE
+ ) {
+ const fieldName = `${field.name}Id`;
+
+ return z
+ .object({
+ eq: z
+ .string()
+ .uuid()
+ .optional()
+ .describe('Related record ID equals'),
+ neq: z
+ .string()
+ .uuid()
+ .optional()
+ .describe('Related record ID not equals'),
+ in: z
+ .array(z.string().uuid())
+ .optional()
+ .describe('Related record ID in array of values'),
+ is: NullCheckEnum.optional().describe(
+ 'Related record ID is null or not null',
+ ),
+ })
+ .optional()
+ .describe(`Filter by ${fieldName} (relation field)`);
+ }
+
+ return null;
+
+ case FieldMetadataType.RAW_JSON:
+ return z
+ .object({
+ eq: z.string().optional().describe('Raw JSON equals'),
+ neq: z.string().optional().describe('Raw JSON not equals'),
+ like: z
+ .string()
+ .optional()
+ .describe('Raw JSON case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Raw JSON case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe('Raw JSON is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (raw JSON field)`);
+
+ default:
+ return z
+ .object({
+ eq: z.string().optional().describe('Equals'),
+ neq: z.string().optional().describe('Not equals'),
+ like: z.string().optional().describe('Case-sensitive pattern match'),
+ ilike: z
+ .string()
+ .optional()
+ .describe('Case-insensitive pattern match'),
+ is: NullCheckEnum.optional().describe('Is null or not null'),
+ })
+ .optional()
+ .describe(`Filter by ${field.name} (string field)`);
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-one-tool.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-one-tool.zod-schema.ts
new file mode 100644
index 00000000000..2bfc870ab87
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-one-tool.zod-schema.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod';
+
+export const FindOneToolInputSchema = z.object({
+ loadingMessage: z
+ .string()
+ .optional()
+ .describe(
+ 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
+ ),
+ input: z.object({
+ id: z.string().uuid().describe('The unique UUID of the record to retrieve'),
+ }),
+});
+
+export type FindOneToolInput = z.infer<typeof FindOneToolInputSchema>;
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-tool.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-tool.zod-schema.ts
new file mode 100644
index 00000000000..0a41669bb47
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/find-tool.zod-schema.ts
@@ -0,0 +1,52 @@
+import { z } from 'zod';
+
+import { ObjectRecordOrderBySchema } from 'src/engine/core-modules/record-crud/zod-schemas/order-by.zod-schema';
+import { generateFieldFilterZodSchema } from 'src/engine/core-modules/record-crud/zod-schemas/field-filters.zod-schema';
+import { type ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { shouldExcludeFieldFromAgentToolSchema } from 'src/engine/metadata-modules/field-metadata/utils/should-exclude-field-from-agent-tool-schema.util';
+
+export const generateFindToolInputSchema = (
+ objectMetadata: ObjectMetadataEntity,
+) => {
+ const filterShape: Record<string, z.ZodTypeAny> = {};
+
+ objectMetadata.fields.forEach((field) => {
+ if (shouldExcludeFieldFromAgentToolSchema(field)) {
+ return;
+ }
+
+ const filterSchema = generateFieldFilterZodSchema(field);
+
+ if (filterSchema) {
+ filterShape[field.name] = filterSchema;
+ }
+ });
+
+ return z.object({
+ loadingMessage: z
+ .string()
+ .optional()
+ .describe(
+ 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
+ ),
+ input: z.object({
+ limit: z
+ .number()
+ .int()
+ .positive()
+ .max(1000)
+ .default(100)
+ .describe('Maximum number of records to return (default: 100)'),
+ offset: z
+ .number()
+ .int()
+ .nonnegative()
+ .default(0)
+ .describe('Number of records to skip (default: 0)'),
+ orderBy: ObjectRecordOrderBySchema.describe(
+ 'Sort records by field(s). CRITICAL for "top N", "largest", "smallest" queries. Each item is an object with exactly ONE property: field name as key, sort direction as value. Example: [{"employees": "DescNullsLast"}] sorts employees descending. Use "DescNullsLast" for top/largest, "AscNullsFirst" for bottom/smallest.',
+ ),
+ ...filterShape,
+ }),
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/order-by.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/order-by.zod-schema.ts
new file mode 100644
index 00000000000..e50aa38d96e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/order-by.zod-schema.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+
+export const OrderByDirectionEnum = z.enum([
+ 'AscNullsFirst',
+ 'AscNullsLast',
+ 'DescNullsFirst',
+ 'DescNullsLast',
+]);
+
+export const ObjectRecordOrderByItemSchema = z
+ .object({})
+ .catchall(OrderByDirectionEnum)
+ .refine((obj) => Object.keys(obj).length === 1, {
+ message: 'Each orderBy item must specify exactly one field',
+ })
+ .describe(
+ 'Object with exactly ONE property: field name as key, OrderByDirection as value. Example: {"employees": "DescNullsLast"}',
+ );
+
+export const ObjectRecordOrderBySchema = z
+ .array(ObjectRecordOrderByItemSchema)
+ .optional()
+ .describe(
+ 'Array of sort criteria. Each item sorts by one field. Use "DescNullsLast" for descending (top/largest), "AscNullsFirst" for ascending (bottom/smallest). Example: [{"employees": "DescNullsLast"}]',
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-input.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-input.zod-schema.ts
new file mode 100644
index 00000000000..e98f7abd881
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-input.zod-schema.ts
@@ -0,0 +1,23 @@
+import { z } from 'zod';
+
+import { generateRecordPropertiesZodSchema } from 'src/engine/core-modules/record-crud/zod-schemas/record-properties.zod-schema';
+import { type ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+
+export const generateRecordInputSchema = (
+ objectMetadata: ObjectMetadataEntity,
+) => {
+ const recordPropertiesSchema = generateRecordPropertiesZodSchema(
+ objectMetadata,
+ false,
+ );
+
+ return z.object({
+ loadingMessage: z
+ .string()
+ .optional()
+ .describe(
+ 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
+ ),
+ input: recordPropertiesSchema,
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-properties.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-properties.zod-schema.ts
new file mode 100644
index 00000000000..3d345221962
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/record-properties.zod-schema.ts
@@ -0,0 +1,249 @@
+import { z } from 'zod';
+import { FieldMetadataType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ type FieldMetadataSettings,
+ NumberDataType,
+} from 'src/engine/metadata-modules/field-metadata/interfaces/field-metadata-settings.interface';
+import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
+
+import { type FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
+import { type ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { isFieldMetadataEntityOfType } from 'src/engine/utils/is-field-metadata-of-type.util';
+
+const isFieldAvailable = (field: FieldMetadataEntity, forResponse: boolean) => {
+ if (forResponse) {
+ return true;
+ }
+ switch (field.name) {
+ case 'id':
+ case 'createdAt':
+ case 'updatedAt':
+ case 'deletedAt':
+ return false;
+ default:
+ return true;
+ }
+};
+
+const getFieldZodType = (field: FieldMetadataEntity): z.ZodTypeAny => {
+ switch (field.type) {
+ case FieldMetadataType.UUID:
+ return z.string().uuid();
+
+ case FieldMetadataType.TEXT:
+ case FieldMetadataType.RICH_TEXT:
+ return z.string();
+
+ case FieldMetadataType.DATE_TIME:
+ return z.string().datetime();
+
+ case FieldMetadataType.DATE:
+ return z.string().date();
+
+ case FieldMetadataType.NUMBER: {
+ const settings =
+ field.settings as FieldMetadataSettings<FieldMetadataType.NUMBER>;
+
+ if (
+ settings?.dataType === NumberDataType.FLOAT ||
+ (isDefined(settings?.decimals) && settings.decimals > 0)
+ ) {
+ return z.number();
+ }
+
+ return z.number().int();
+ }
+
+ case FieldMetadataType.NUMERIC:
+ case FieldMetadataType.POSITION:
+ return z.number();
+
+ case FieldMetadataType.BOOLEAN:
+ return z.boolean();
+
+ case FieldMetadataType.RAW_JSON:
+ return z.record(z.string(), z.unknown());
+
+ default:
+ return z.string();
+ }
+};
+
+export const generateRecordPropertiesZodSchema = (
+ objectMetadata: ObjectMetadataEntity,
+ forResponse = false,
+): z.ZodObject<Record<string, z.ZodTypeAny>> => {
+ const shape: Record<string, z.ZodTypeAny> = {};
+
+ objectMetadata.fields.forEach((field) => {
+ if (
+ !isFieldAvailable(field, forResponse) ||
+ field.type === FieldMetadataType.TS_VECTOR
+ ) {
+ return;
+ }
+
+ if (
+ isFieldMetadataEntityOfType(field, FieldMetadataType.RELATION) &&
+ field.settings?.relationType === RelationType.MANY_TO_ONE
+ ) {
+ shape[`${field.name}Id`] = z.string().uuid();
+
+ return;
+ }
+
+ if (
+ isFieldMetadataEntityOfType(field, FieldMetadataType.RELATION) &&
+ field.settings?.relationType === RelationType.ONE_TO_MANY
+ ) {
+ return;
+ }
+
+ let fieldSchema: z.ZodTypeAny;
+
+ switch (field.type) {
+ case FieldMetadataType.MULTI_SELECT: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length > 0) {
+ fieldSchema = z.array(z.enum(enumValues as [string, ...string[]]));
+ } else {
+ fieldSchema = z.array(z.string());
+ }
+ break;
+ }
+
+ case FieldMetadataType.SELECT: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length > 0) {
+ fieldSchema = z.enum(enumValues as [string, ...string[]]);
+ } else {
+ fieldSchema = z.string();
+ }
+ break;
+ }
+
+ case FieldMetadataType.ARRAY:
+ fieldSchema = z.array(z.string());
+ break;
+
+ case FieldMetadataType.RATING: {
+ const enumValues =
+ field.options?.map((option: { value: string }) => option.value) || [];
+
+ if (enumValues.length > 0) {
+ fieldSchema = z.enum(enumValues as [string, ...string[]]);
+ } else {
+ fieldSchema = z.string();
+ }
+ break;
+ }
+
+ case FieldMetadataType.LINKS:
+ fieldSchema = z.object({
+ primaryLinkLabel: z.string().optional(),
+ primaryLinkUrl: z.string().url().optional(),
+ secondaryLinks: z
+ .array(
+ z.object({
+ url: z.string().url(),
+ label: z.string(),
+ }),
+ )
+ .optional(),
+ });
+ break;
+
+ case FieldMetadataType.CURRENCY:
+ fieldSchema = z.object({
+ amountMicros: z.number().optional(),
+ currencyCode: z.string().optional(),
+ });
+ break;
+
+ case FieldMetadataType.FULL_NAME:
+ fieldSchema = z.object({
+ firstName: z.string().optional(),
+ lastName: z.string().optional(),
+ });
+ break;
+
+ case FieldMetadataType.ADDRESS:
+ fieldSchema = z.object({
+ addressStreet1: z.string().optional(),
+ addressStreet2: z.string().optional(),
+ addressCity: z.string().optional(),
+ addressPostcode: z.string().optional(),
+ addressState: z.string().optional(),
+ addressCountry: z.string().optional(),
+ addressLat: z.number().optional(),
+ addressLng: z.number().optional(),
+ });
+ break;
+
+ case FieldMetadataType.ACTOR:
+ fieldSchema = z.object({
+ source: z
+ .enum([
+ 'EMAIL',
+ 'CALENDAR',
+ 'WORKFLOW',
+ 'AGENT',
+ 'API',
+ 'IMPORT',
+ 'MANUAL',
+ 'SYSTEM',
+ 'WEBHOOK',
+ ])
+ .optional(),
+ ...(forResponse
+ ? {
+ workspaceMemberId: z.string().uuid().optional(),
+ name: z.string().optional(),
+ }
+ : {}),
+ });
+ break;
+
+ case FieldMetadataType.EMAILS:
+ fieldSchema = z.object({
+ primaryEmail: z.string().email().optional(),
+ additionalEmails: z.array(z.string().email()).optional(),
+ });
+ break;
+
+ case FieldMetadataType.PHONES:
+ fieldSchema = z.object({
+ primaryPhoneNumber: z.string().optional(),
+ primaryPhoneCountryCode: z.string().optional(),
+ primaryPhoneCallingCode: z.string().optional(),
+ additionalPhones: z.array(z.string()).optional(),
+ });
+ break;
+
+ case FieldMetadataType.RICH_TEXT_V2:
+ fieldSchema = z.object({
+ markdown: z.string().optional(),
+ blocknote: z.string().optional(),
+ });
+ break;
+
+ default:
+ fieldSchema = getFieldZodType(field);
+ break;
+ }
+
+ if (field.description) {
+ fieldSchema = fieldSchema.describe(field.description);
+ }
+
+ shape[field.name] = fieldSchema;
+ });
+
+ return z.object(shape);
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/soft-delete-tool.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/soft-delete-tool.zod-schema.ts
new file mode 100644
index 00000000000..9530c6ef93c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/soft-delete-tool.zod-schema.ts
@@ -0,0 +1,18 @@
+import { z } from 'zod';
+
+export const SoftDeleteToolInputSchema = z.object({
+ loadingMessage: z
+ .string()
+ .optional()
+ .describe(
+ 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
+ ),
+ input: z.object({
+ id: z
+ .string()
+ .uuid()
+ .describe('The unique UUID of the record to soft delete'),
+ }),
+});
+
+export type SoftDeleteToolInput = z.infer<typeof SoftDeleteToolInputSchema>;
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index a3436443dcb..7ed51163ad2 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -1025,11 +1025,20 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.LLM,
description:
- 'Default model ID for AI operations (can be any available model)',
+ 'Default AI model ID for speed-optimized operations (lightweight tasks, high throughput)',
type: ConfigVariableType.STRING,
})
@IsOptional()
- DEFAULT_MODEL_ID = 'gpt-4o';
+ DEFAULT_AI_SPEED_MODEL_ID = 'gpt-4o-mini';
+
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.LLM,
+ description:
+ 'Default AI model ID for performance-optimized operations (complex reasoning, quality focus)',
+ type: ConfigVariableType.STRING,
+ })
+ @IsOptional()
+ DEFAULT_AI_PERFORMANCE_MODEL_ID = 'gpt-4o';
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.LLM,
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-input.ts b/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-input.ts
index 9a4b1e31f87..e6c5d859e46 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-input.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-input.ts
@@ -82,4 +82,9 @@ export class UpdateWorkspaceInput {
@Min(0)
@IsOptional()
trashRetentionDays?: number;
+
+ @Field({ nullable: true })
+ @IsString()
+ @IsOptional()
+ routerModel?: string;
}
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
index 8e7597b4d6d..007848ff73a 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
@@ -16,6 +16,7 @@ import {
} from 'typeorm';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { ModelId } from 'src/engine/core-modules/ai/constants/ai-models.const';
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
import { ApprovedAccessDomainEntity } from 'src/engine/core-modules/approved-access-domain/approved-access-domain.entity';
@@ -29,7 +30,6 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user
import { WebhookEntity } from 'src/engine/core-modules/webhook/webhook.entity';
import { AgentHandoffEntity } from 'src/engine/metadata-modules/agent/agent-handoff.entity';
import { AgentEntity } from 'src/engine/metadata-modules/agent/agent.entity';
-import { AgentDTO } from 'src/engine/metadata-modules/agent/dtos/agent.dto';
import { RoleDTO } from 'src/engine/metadata-modules/role/dtos/role.dto';
import { ViewFieldDTO } from 'src/engine/metadata-modules/view-field/dtos/view-field.dto';
import { ViewFieldEntity } from 'src/engine/metadata-modules/view-field/entities/view-field.entity';
@@ -253,14 +253,11 @@ export class WorkspaceEntity {
@Field(() => RoleDTO, { nullable: true })
defaultRole: RoleDTO | null;
- // TODO: set as non nullable
- @Column({ nullable: true, type: 'uuid' })
- defaultAgentId: string | null;
-
- @Field(() => AgentDTO, { nullable: true })
- defaultAgent: AgentDTO | null;
-
@Field(() => String, { nullable: true })
@Column({ type: 'varchar', nullable: true })
version: string | null;
+
+ @Field(() => String, { nullable: false })
+ @Column({ type: 'varchar', nullable: false, default: 'auto' })
+ routerModel: ModelId;
}
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
index 5e1da5f2212..cd2ed9df061 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
@@ -62,8 +62,6 @@ import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
import { SettingsPermissionsGuard } from 'src/engine/guards/settings-permissions.guard';
import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
-import { AgentService } from 'src/engine/metadata-modules/agent/agent.service';
-import { AgentDTO } from 'src/engine/metadata-modules/agent/dtos/agent.dto';
import { PermissionFlagType } from 'src/engine/metadata-modules/permissions/constants/permission-flag-type.constants';
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
import { RoleDTO } from 'src/engine/metadata-modules/role/dtos/role.dto';
@@ -72,7 +70,6 @@ import { ViewDTO } from 'src/engine/metadata-modules/view/dtos/view.dto';
import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
import { getRequest } from 'src/utils/extract-request';
import { streamToBuffer } from 'src/utils/stream-to-buffer';
-
const OriginHeader = createParamDecorator(
(_: unknown, ctx: ExecutionContext) => {
const request = getRequest(ctx);
@@ -98,7 +95,6 @@ export class WorkspaceResolver {
private readonly billingSubscriptionService: BillingSubscriptionService,
private readonly featureFlagService: FeatureFlagService,
private readonly roleService: RoleService,
- private readonly agentService: AgentService,
private readonly viewService: ViewService,
private readonly dnsManagerService: DnsManagerService,
private readonly customDomainManagerService: CustomDomainManagerService,
@@ -232,30 +228,11 @@ export class WorkspaceResolver {
);
}
- @ResolveField(() => AgentDTO, { nullable: true })
- async defaultAgent(
+ @ResolveField(() => String, { nullable: true })
+ async routerModel(
@Parent() workspace: WorkspaceEntity,
- ): Promise<AgentDTO | null> {
- if (!workspace.defaultAgentId) {
- return null;
- }
-
- try {
- const agent = await this.agentService.findOneAgent(
- workspace.defaultAgentId,
- workspace.id,
- );
-
- // Convert roleId from null to undefined to match AgentDTO
- return {
- ...agent,
- roleId: agent.roleId ?? undefined,
- applicationId: agent.applicationId ?? undefined,
- };
- } catch {
- // If agent is not found, return null instead of throwing
- return null;
- }
+ ): Promise<string | null> {
+ return workspace.routerModel;
}
@ResolveField(() => BillingSubscriptionEntity, { nullable: true })
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat-thread.entity.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat-thread.entity.ts
index 944b2248a7e..3738f59a279 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat-thread.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat-thread.entity.ts
@@ -15,23 +15,11 @@ import { Relation } from 'src/engine/workspace-manager/workspace-sync-metadata/i
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentChatMessageEntity } from 'src/engine/metadata-modules/agent/agent-chat-message.entity';
-import { AgentEntity } from './agent.entity';
-
@Entity('agentChatThread')
export class AgentChatThreadEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
- @Column('uuid')
- @Index()
- agentId: string;
-
- @ManyToOne(() => AgentEntity, (agent) => agent.chatThreads, {
- onDelete: 'CASCADE',
- })
- @JoinColumn({ name: 'agentId' })
- agent: Relation<AgentEntity>;
-
@Column('uuid')
@Index()
userWorkspaceId: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.controller.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.controller.ts
index 3c5d5677c87..909bc7844d4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.controller.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.controller.ts
@@ -1,8 +1,6 @@
import {
Body,
Controller,
- Get,
- Param,
Post,
Res,
UseFilters,
@@ -32,33 +30,6 @@ export class AgentChatController {
private readonly agentStreamingService: AgentStreamingService,
) {}
- @Get('threads/:agentId')
- async getThreadsForAgent(
- @Param('agentId') agentId: string,
- @AuthUserWorkspaceId() userWorkspaceId: string,
- ) {
- return this.agentChatService.getThreadsForAgent(agentId, userWorkspaceId);
- }
-
- @Get('threads/:threadId/messages')
- async getMessagesForThread(
- @Param('threadId') threadId: string,
- @AuthUserWorkspaceId() userWorkspaceId: string,
- ) {
- return this.agentChatService.getMessagesForThread(
- threadId,
- userWorkspaceId,
- );
- }
-
- @Post('threads')
- async createThread(
- @Body() body: { agentId: string },
- @AuthUserWorkspaceId() userWorkspaceId: string,
- ) {
- return this.agentChatService.createThread(body.agentId, userWorkspaceId);
- }
-
@Post('stream')
async streamAgentChat(
@Body()
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.resolver.ts
index 63d9b633e5e..6668220caea 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.resolver.ts
@@ -13,7 +13,6 @@ import { AgentChatService } from 'src/engine/metadata-modules/agent/agent-chat.s
import { AgentChatMessageDTO } from './dtos/agent-chat-message.dto';
import { AgentChatThreadDTO } from './dtos/agent-chat-thread.dto';
-import { CreateAgentChatThreadInput } from './dtos/create-agent-chat-thread.input';
@UseGuards(WorkspaceAuthGuard, FeatureFlagGuard)
@Resolver()
@@ -22,16 +21,13 @@ export class AgentChatResolver {
@Query(() => [AgentChatThreadDTO])
@RequireFeatureFlag(FeatureFlagKey.IS_AI_ENABLED)
- async agentChatThreads(
- @Args('agentId', { type: () => UUIDScalarType }) agentId: string,
- @AuthUserWorkspaceId() userWorkspaceId: string,
- ) {
- return this.agentChatService.getThreadsForAgent(agentId, userWorkspaceId);
+ async chatThreads(@AuthUserWorkspaceId() userWorkspaceId: string) {
+ return this.agentChatService.getThreadsForUser(userWorkspaceId);
}
@Query(() => AgentChatThreadDTO)
@RequireFeatureFlag(FeatureFlagKey.IS_AI_ENABLED)
- async agentChatThread(
+ async chatThread(
@Args('id', { type: () => UUIDScalarType }) id: string,
@AuthUserWorkspaceId() userWorkspaceId: string,
) {
@@ -40,7 +36,7 @@ export class AgentChatResolver {
@Query(() => [AgentChatMessageDTO])
@RequireFeatureFlag(FeatureFlagKey.IS_AI_ENABLED)
- async agentChatMessages(
+ async chatMessages(
@Args('threadId', { type: () => UUIDScalarType }) threadId: string,
@AuthUserWorkspaceId() userWorkspaceId: string,
) {
@@ -52,10 +48,7 @@ export class AgentChatResolver {
@Mutation(() => AgentChatThreadDTO)
@RequireFeatureFlag(FeatureFlagKey.IS_AI_ENABLED)
- async createAgentChatThread(
- @Args('input') input: CreateAgentChatThreadInput,
- @AuthUserWorkspaceId() userWorkspaceId: string,
- ) {
- return this.agentChatService.createThread(input.agentId, userWorkspaceId);
+ async createChatThread(@AuthUserWorkspaceId() userWorkspaceId: string) {
+ return this.agentChatService.createThread(userWorkspaceId);
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.service.ts
index 276ebfde3a4..39d0491e0ee 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-chat.service.ts
@@ -1,9 +1,10 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { ExtendedUIMessage } from 'twenty-shared/ai';
import { Repository } from 'typeorm';
-import type { UIDataTypes, UIMessage, UIMessagePart, UITools } from 'ai';
+import type { UIDataTypes, UIMessagePart, UITools } from 'ai';
import { AgentChatMessagePartEntity } from 'src/engine/metadata-modules/agent/agent-chat-message-part.entity';
import {
@@ -31,19 +32,17 @@ export class AgentChatService {
private readonly titleGenerationService: AgentTitleGenerationService,
) {}
- async createThread(agentId: string, userWorkspaceId: string) {
+ async createThread(userWorkspaceId: string) {
const thread = this.threadRepository.create({
- agentId,
userWorkspaceId,
});
return this.threadRepository.save(thread);
}
- async getThreadsForAgent(agentId: string, userWorkspaceId: string) {
+ async getThreadsForUser(userWorkspaceId: string) {
return this.threadRepository.find({
where: {
- agentId,
userWorkspaceId,
},
order: { createdAt: 'DESC' },
@@ -73,7 +72,7 @@ export class AgentChatService {
uiMessage,
}: {
threadId: string;
- uiMessage: Omit<UIMessage<unknown, UIDataTypes, UITools>, 'id'>;
+ uiMessage: Omit<ExtendedUIMessage, 'id'>;
uiMessageParts?: UIMessagePart<UIDataTypes, UITools>[];
}) {
const message = this.messageRepository.create({
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-execution.service.ts
index becbed8885d..aae3b2cd4d6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-execution.service.ts
@@ -36,6 +36,8 @@ import { AgentToolGeneratorService } from './agent-tool-generator.service';
import { AgentEntity } from './agent.entity';
import { AgentException, AgentExceptionCode } from './agent.exception';
+import { repairToolCall } from './utils/repair-tool-call.util';
+
export interface AgentExecutionResult {
result: object;
usage: LanguageModelUsage;
@@ -129,6 +131,30 @@ export class AgentExecutionService implements AgentExecutionContext {
messages: convertToModelMessages(messages),
stopWhen: stepCountIs(AGENT_CONFIG.MAX_STEPS),
providerOptions,
+ experimental_repairToolCall: async ({
+ toolCall,
+ tools: toolsForRepair,
+ inputSchema,
+ error,
+ }: {
+ toolCall: {
+ type: 'tool-call';
+ toolCallId: string;
+ toolName: string;
+ input: string;
+ };
+ tools: Record<string, unknown>;
+ inputSchema: (toolCall: { toolName: string }) => unknown;
+ error: Error;
+ }) => {
+ return repairToolCall({
+ toolCall,
+ tools: toolsForRepair,
+ inputSchema,
+ error,
+ model: registeredModel.model,
+ });
+ },
};
} catch (error) {
this.logger.error(
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-streaming.service.ts
index 9d59fec6319..de6e822a27c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-streaming.service.ts
@@ -9,6 +9,7 @@ import {
UITools,
} from 'ai';
import { type Response } from 'express';
+import { ExtendedUIMessage } from 'twenty-shared/ai';
import { Repository } from 'typeorm';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -21,6 +22,7 @@ import {
AgentExceptionCode,
} from 'src/engine/metadata-modules/agent/agent.exception';
import { type RecordIdsByObjectMetadataNameSingularType } from 'src/engine/metadata-modules/agent/types/recordIdsByObjectMetadataNameSingular.type';
+import { AiRouterService } from 'src/engine/metadata-modules/ai-router/ai-router.service';
export type StreamAgentChatOptions = {
threadId: string;
@@ -40,6 +42,7 @@ export class AgentStreamingService {
private readonly threadRepository: Repository<AgentChatThreadEntity>,
private readonly agentChatService: AgentChatService,
private readonly agentExecutionService: AgentExecutionService,
+ private readonly aiRouterService: AiRouterService,
) {}
async streamAgentChat({
@@ -56,7 +59,7 @@ export class AgentStreamingService {
id: threadId,
userWorkspaceId,
},
- relations: ['messages', 'agent'],
+ relations: ['messages'],
});
if (!thread) {
@@ -66,11 +69,54 @@ export class AgentStreamingService {
);
}
- const stream = createUIMessageStream({
+ const stream = createUIMessageStream<ExtendedUIMessage>({
execute: async ({ writer }) => {
+ writer.write({
+ type: 'data-routing-status' as const,
+ id: 'routing-status',
+ data: {
+ text: 'Finding the best agent for your request...',
+ state: 'loading',
+ },
+ });
+
+ const agent = await this.aiRouterService.routeMessage({
+ messages,
+ workspaceId: workspace.id,
+ routerModel: workspace.routerModel,
+ });
+
+ if (!agent) {
+ writer.write({
+ type: 'data-routing-status' as const,
+ id: 'routing-status',
+ data: {
+ text: '',
+ state: 'error',
+ },
+ });
+ throw new AgentException(
+ 'No agents available for routing',
+ AgentExceptionCode.AGENT_EXECUTION_FAILED,
+ );
+ }
+
+ this.logger.log(`Using agent ${agent.id} for message routing`);
+
+ const routedStatusPart = {
+ type: 'data-routing-status' as const,
+ id: 'routing-status',
+ data: {
+ text: `Routed to ${agent.label} agent`,
+ state: 'routed',
+ },
+ };
+
+ writer.write(routedStatusPart);
+
const result = await this.agentExecutionService.streamChatResponse({
workspace,
- agentId: thread.agent.id,
+ agentId: agent.id,
userWorkspaceId,
messages,
recordIdsByObjectMetadataNameSingular,
@@ -81,6 +127,7 @@ export class AgentStreamingService {
onError: (error) => {
return error instanceof Error ? error.message : String(error);
},
+ sendStart: false,
onFinish: async ({ responseMessage }) => {
if (responseMessage.parts.length === 0) {
return;
@@ -101,9 +148,13 @@ export class AgentStreamingService {
],
},
});
+
await this.agentChatService.addMessage({
threadId,
- uiMessage: responseMessage,
+ uiMessage: {
+ ...responseMessage,
+ parts: [routedStatusPart, ...responseMessage.parts],
+ },
});
},
sendReasoning: true,
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent-title-generation.service.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent-title-generation.service.ts
index f4c31734d5d..dca045a9af3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent-title-generation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent-title-generation.service.ts
@@ -14,7 +14,7 @@ export class AgentTitleGenerationService {
async generateThreadTitle(messageContent: string): Promise<string> {
try {
- const defaultModel = this.aiModelRegistryService.getDefaultModel();
+ const defaultModel = this.aiModelRegistryService.getDefaultSpeedModel();
if (!defaultModel) {
this.logger.warn('No default AI model available for title generation');
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent.entity.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent.entity.ts
index 5175f55e52f..59646c8cda9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent.entity.ts
@@ -18,7 +18,6 @@ import { ModelId } from 'src/engine/core-modules/ai/constants/ai-models.const';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { ModelConfiguration } from 'src/engine/metadata-modules/agent/types/modelConfiguration';
-import { AgentChatThreadEntity } from './agent-chat-thread.entity';
import { AgentHandoffEntity } from './agent-handoff.entity';
@Entity('agent')
@@ -70,9 +69,6 @@ export class AgentEntity
@JoinColumn({ name: 'workspaceId' })
workspace: Relation<WorkspaceEntity>;
- @OneToMany(() => AgentChatThreadEntity, (chatThread) => chatThread.agent)
- chatThreads: Relation<AgentChatThreadEntity[]>;
-
@OneToMany(() => AgentHandoffEntity, (handoff) => handoff.fromAgent)
outgoingHandoffs: Relation<AgentHandoffEntity[]>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/agent.module.ts b/packages/twenty-server/src/engine/metadata-modules/agent/agent.module.ts
index 6ba463b20a9..17a180fce38 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/agent.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/agent.module.ts
@@ -15,6 +15,7 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { AgentRoleModule } from 'src/engine/metadata-modules/agent-role/agent-role.module';
import { AgentChatController } from 'src/engine/metadata-modules/agent/agent-chat.controller';
+import { AiRouterModule } from 'src/engine/metadata-modules/ai-router/ai-router.module';
import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { RoleTargetsEntity } from 'src/engine/metadata-modules/role/role-targets.entity';
@@ -66,6 +67,7 @@ import { AgentActorContextService } from './services/agent-actor-context.service
FileModule,
ObjectMetadataModule,
PermissionsModule,
+ AiRouterModule,
WorkspacePermissionsCacheModule,
WorkspaceCacheStorageModule,
TokenModule,
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/dtos/agent-chat-thread.dto.ts b/packages/twenty-server/src/engine/metadata-modules/agent/dtos/agent-chat-thread.dto.ts
index 153a6817bb0..432df172111 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/dtos/agent-chat-thread.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/dtos/agent-chat-thread.dto.ts
@@ -7,9 +7,6 @@ export class AgentChatThreadDTO {
@Field(() => UUIDScalarType)
id: string;
- @Field(() => UUIDScalarType)
- agentId: string;
-
@Field({ nullable: true })
title: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/dtos/create-agent-chat-thread.input.ts b/packages/twenty-server/src/engine/metadata-modules/agent/dtos/create-agent-chat-thread.input.ts
deleted file mode 100644
index 247a4de8be4..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/agent/dtos/create-agent-chat-thread.input.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Field, InputType } from '@nestjs/graphql';
-
-import { IsNotEmpty } from 'class-validator';
-
-import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-
-@InputType()
-export class CreateAgentChatThreadInput {
- @IsNotEmpty()
- @Field(() => UUIDScalarType)
- agentId: string;
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/services/agent-actor-context.service.ts b/packages/twenty-server/src/engine/metadata-modules/agent/services/agent-actor-context.service.ts
index c94a2450325..d8c06d7e16d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/services/agent-actor-context.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/services/agent-actor-context.service.ts
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
-import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { buildCreatedByFromFullNameMetadata } from 'src/engine/core-modules/actor/utils/build-created-by-from-full-name-metadata.util';
+import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import {
AgentException,
AgentExceptionCode,
@@ -16,9 +16,10 @@ export type AgentActorContext = {
};
@Injectable()
+// eslint-disable-next-line @nx/workspace-inject-workspace-repository
export class AgentActorContextService {
constructor(
- private readonly userService: UserService,
+ private readonly userWorkspaceService: UserWorkspaceService,
private readonly userRoleService: UserRoleService,
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
) {}
@@ -27,7 +28,8 @@ export class AgentActorContextService {
userWorkspaceId: string,
workspaceId: string,
): Promise<AgentActorContext> {
- const userWorkspace = await this.userService.findById(userWorkspaceId);
+ const userWorkspace =
+ await this.userWorkspaceService.findById(userWorkspaceId);
if (!userWorkspace) {
throw new AgentException(
@@ -45,7 +47,7 @@ export class AgentActorContextService {
const workspaceMember = await workspaceMemberRepository.findOne({
where: {
- userId: userWorkspace.id,
+ userId: userWorkspace.userId,
},
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/utils/agent-tool-schema.utils.ts b/packages/twenty-server/src/engine/metadata-modules/agent/utils/agent-tool-schema.utils.ts
deleted file mode 100644
index e6f750d7e10..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/agent/utils/agent-tool-schema.utils.ts
+++ /dev/null
@@ -1,876 +0,0 @@
-import { jsonSchema } from 'ai';
-import { type JSONSchema7Definition } from 'json-schema';
-import { FieldMetadataType } from 'twenty-shared/types';
-
-import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
-
-import { type FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
-import { shouldExcludeFieldFromAgentToolSchema } from 'src/engine/metadata-modules/field-metadata/utils/should-exclude-field-from-agent-tool-schema.util';
-import { type ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-import { convertObjectMetadataToSchemaProperties } from 'src/engine/utils/convert-object-metadata-to-schema-properties.util';
-import { isFieldMetadataEntityOfType } from 'src/engine/utils/is-field-metadata-of-type.util';
-
-const createToolSchema = (
- inputProperties: Record<string, JSONSchema7Definition>,
- required?: string[],
-) => {
- return jsonSchema({
- type: 'object',
- properties: {
- loadingMessage: {
- type: 'string',
- description:
- 'A clear, human-readable description of the action being performed. Explain what operation you are executing and with what parameters in natural language.',
- },
- input: {
- type: 'object',
- properties: inputProperties,
- ...(required && { required }),
- },
- },
- });
-};
-
-export const getRecordInputSchema = (objectMetadata: ObjectMetadataEntity) => {
- return createToolSchema(
- convertObjectMetadataToSchemaProperties({
- item: objectMetadata,
- forResponse: false,
- }),
- );
-};
-
-export const generateFindToolSchema = (
- objectMetadata: ObjectMetadataEntity,
-) => {
- const schemaProperties: Record<string, JSONSchema7Definition> = {
- limit: {
- type: 'number',
- description: 'Maximum number of records to return (default: 100)',
- default: 100,
- },
- offset: {
- type: 'number',
- description: 'Number of records to skip (default: 0)',
- default: 0,
- },
- };
-
- objectMetadata.fields.forEach((field: FieldMetadataEntity) => {
- if (shouldExcludeFieldFromAgentToolSchema(field)) {
- return;
- }
-
- const filterSchema = generateFieldFilterJsonSchema(field);
-
- if (filterSchema) {
- schemaProperties[field.name] = filterSchema;
- }
- });
-
- return createToolSchema(schemaProperties);
-};
-
-const generateFieldFilterJsonSchema = (
- field: FieldMetadataEntity,
-): JSONSchema7Definition | null => {
- switch (field.type) {
- case FieldMetadataType.UUID:
- return {
- type: 'object',
- description: `Filter by ${field.name} (UUID field)`,
- properties: {
- eq: {
- type: 'string',
- format: 'uuid',
- description: 'Equals',
- },
- neq: {
- type: 'string',
- format: 'uuid',
- description: 'Not equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- format: 'uuid',
- },
- description: 'In array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
-
- case FieldMetadataType.TEXT:
- case FieldMetadataType.RICH_TEXT:
- case FieldMetadataType.RICH_TEXT_V2:
- return {
- type: 'object',
- description: `Filter by ${field.name} (text field)`,
- properties: {
- eq: {
- type: 'string',
- description: 'Equals',
- },
- neq: {
- type: 'string',
- description: 'Not equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- },
- description: 'In array of values',
- },
- like: {
- type: 'string',
- description: 'Case-sensitive pattern match (use % for wildcards)',
- },
- ilike: {
- type: 'string',
- description: 'Case-insensitive pattern match (use % for wildcards)',
- },
- startsWith: {
- type: 'string',
- description: 'Starts with',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
-
- case FieldMetadataType.NUMBER:
- case FieldMetadataType.NUMERIC:
- case FieldMetadataType.POSITION:
- return {
- type: 'object',
- description: `Filter by ${field.name} (number field)`,
- properties: {
- eq: {
- type: 'number',
- description: 'Equals',
- },
- neq: {
- type: 'number',
- description: 'Not equals',
- },
- gt: {
- type: 'number',
- description: 'Greater than',
- },
- gte: {
- type: 'number',
- description: 'Greater than or equal',
- },
- lt: {
- type: 'number',
- description: 'Less than',
- },
- lte: {
- type: 'number',
- description: 'Less than or equal',
- },
- in: {
- type: 'array',
- items: {
- type: 'number',
- },
- description: 'In array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
-
- case FieldMetadataType.BOOLEAN:
- return {
- type: 'object',
- description: `Filter by ${field.name} (boolean field)`,
- properties: {
- eq: {
- type: 'boolean',
- description: 'Equals',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
-
- case FieldMetadataType.DATE_TIME:
- case FieldMetadataType.DATE:
- return {
- type: 'object',
- description: `Filter by ${field.name} (date field)`,
- properties: {
- eq: {
- type: 'string',
- format: 'date-time',
- description: 'Equals (ISO datetime string)',
- },
- neq: {
- type: 'string',
- format: 'date-time',
- description: 'Not equals (ISO datetime string)',
- },
- gt: {
- type: 'string',
- format: 'date-time',
- description: 'Greater than (ISO datetime string)',
- },
- gte: {
- type: 'string',
- format: 'date-time',
- description: 'Greater than or equal (ISO datetime string)',
- },
- lt: {
- type: 'string',
- format: 'date-time',
- description: 'Less than (ISO datetime string)',
- },
- lte: {
- type: 'string',
- format: 'date-time',
- description: 'Less than or equal (ISO datetime string)',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- format: 'date-time',
- },
- description: 'In array of values (ISO datetime strings)',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
-
- case FieldMetadataType.SELECT: {
- const enumValues =
- field.options?.map((option: { value: string }) => option.value) || [];
-
- return {
- type: 'object',
- description: `Filter by ${field.name} (select field)`,
- properties: {
- eq: {
- type: 'string',
- enum: enumValues,
- description: 'Equals',
- },
- neq: {
- type: 'string',
- enum: enumValues,
- description: 'Not equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- enum: enumValues,
- },
- description: 'In array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
- }
-
- case FieldMetadataType.MULTI_SELECT: {
- const enumValues =
- field.options?.map((option: { value: string }) => option.value) || [];
-
- return {
- type: 'object',
- description: `Filter by ${field.name} (multi-select field)`,
- properties: {
- in: {
- type: 'array',
- items: {
- type: 'string',
- enum: enumValues,
- },
- description: 'Contains any of these values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- isEmptyArray: {
- type: 'boolean',
- description: 'Is empty array',
- },
- },
- };
- }
-
- case FieldMetadataType.RATING: {
- const enumValues =
- field.options?.map((option: { value: string }) => option.value) || [];
-
- return {
- type: 'object',
- description: `Filter by ${field.name} (rating field)`,
- properties: {
- eq: {
- type: 'string',
- enum: enumValues,
- description: 'Equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- enum: enumValues,
- },
- description: 'In array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
- }
-
- case FieldMetadataType.ARRAY:
- return {
- type: 'object',
- description: `Filter by ${field.name} (array field)`,
- properties: {
- containsIlike: {
- type: 'string',
- description: 'Contains case-insensitive substring',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- isEmptyArray: {
- type: 'boolean',
- description: 'Is empty array',
- },
- },
- };
-
- case FieldMetadataType.CURRENCY:
- return {
- type: 'object',
- description: `Filter by ${field.name} (currency field)`,
- properties: {
- amountMicros: {
- type: 'object',
- description: 'Filter by amount',
- properties: {
- eq: {
- type: 'number',
- description: 'Amount equals',
- },
- neq: {
- type: 'number',
- description: 'Amount not equals',
- },
- gt: {
- type: 'number',
- description: 'Amount greater than',
- },
- gte: {
- type: 'number',
- description: 'Amount greater than or equal',
- },
- lt: {
- type: 'number',
- description: 'Amount less than',
- },
- lte: {
- type: 'number',
- description: 'Amount less than or equal',
- },
- in: {
- type: 'array',
- items: {
- type: 'number',
- },
- description: 'Amount in array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Amount is null or not null',
- },
- },
- },
- currencyCode: {
- type: 'object',
- description: 'Filter by currency code',
- properties: {
- eq: {
- type: 'string',
- description: 'Currency code equals',
- },
- neq: {
- type: 'string',
- description: 'Currency code not equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- },
- description: 'Currency code in array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Currency code is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.FULL_NAME:
- return {
- type: 'object',
- description: `Filter by ${field.name} (full name field)`,
- properties: {
- firstName: {
- type: 'object',
- description: 'Filter by first name',
- properties: {
- eq: {
- type: 'string',
- description: 'First name equals',
- },
- neq: {
- type: 'string',
- description: 'First name not equals',
- },
- like: {
- type: 'string',
- description: 'First name case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'First name case-insensitive pattern match',
- },
- startsWith: {
- type: 'string',
- description: 'First name starts with',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'First name is null or not null',
- },
- },
- },
- lastName: {
- type: 'object',
- description: 'Filter by last name',
- properties: {
- eq: {
- type: 'string',
- description: 'Last name equals',
- },
- neq: {
- type: 'string',
- description: 'Last name not equals',
- },
- like: {
- type: 'string',
- description: 'Last name case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Last name case-insensitive pattern match',
- },
- startsWith: {
- type: 'string',
- description: 'Last name starts with',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Last name is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.ADDRESS:
- return {
- type: 'object',
- description: `Filter by ${field.name} (address field)`,
- properties: {
- addressStreet1: {
- type: 'object',
- description: 'Filter by street 1',
- properties: {
- eq: {
- type: 'string',
- description: 'Street 1 equals',
- },
- neq: {
- type: 'string',
- description: 'Street 1 not equals',
- },
- like: {
- type: 'string',
- description: 'Street 1 case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Street 1 case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Street 1 is null or not null',
- },
- },
- },
- addressCity: {
- type: 'object',
- description: 'Filter by city',
- properties: {
- eq: {
- type: 'string',
- description: 'City equals',
- },
- neq: {
- type: 'string',
- description: 'City not equals',
- },
- like: {
- type: 'string',
- description: 'City case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'City case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'City is null or not null',
- },
- },
- },
- addressCountry: {
- type: 'object',
- description: 'Filter by country',
- properties: {
- eq: {
- type: 'string',
- description: 'Country equals',
- },
- neq: {
- type: 'string',
- description: 'Country not equals',
- },
- like: {
- type: 'string',
- description: 'Country case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Country case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Country is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.EMAILS:
- return {
- type: 'object',
- description: `Filter by ${field.name} (emails field)`,
- properties: {
- primaryEmail: {
- type: 'object',
- description: 'Filter by primary email',
- properties: {
- eq: {
- type: 'string',
- format: 'email',
- description: 'Primary email equals',
- },
- neq: {
- type: 'string',
- format: 'email',
- description: 'Primary email not equals',
- },
- like: {
- type: 'string',
- description: 'Primary email case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Primary email case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Primary email is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.PHONES:
- return {
- type: 'object',
- description: `Filter by ${field.name} (phones field)`,
- properties: {
- primaryPhoneNumber: {
- type: 'object',
- description: 'Filter by primary phone number',
- properties: {
- eq: {
- type: 'string',
- description: 'Primary phone number equals',
- },
- neq: {
- type: 'string',
- description: 'Primary phone number not equals',
- },
- like: {
- type: 'string',
- description:
- 'Primary phone number case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description:
- 'Primary phone number case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Primary phone number is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.LINKS:
- return {
- type: 'object',
- description: `Filter by ${field.name} (links field)`,
- properties: {
- primaryLinkUrl: {
- type: 'object',
- description: 'Filter by primary link URL',
- properties: {
- eq: {
- type: 'string',
- format: 'uri',
- description: 'Primary link URL equals',
- },
- neq: {
- type: 'string',
- format: 'uri',
- description: 'Primary link URL not equals',
- },
- like: {
- type: 'string',
- description: 'Primary link URL case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Primary link URL case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Primary link URL is null or not null',
- },
- },
- },
- },
- };
-
- case FieldMetadataType.RELATION:
- if (
- isFieldMetadataEntityOfType(field, FieldMetadataType.RELATION) &&
- field.settings?.relationType === RelationType.MANY_TO_ONE
- ) {
- const fieldName = `${field.name}Id`;
-
- return {
- type: 'object',
- description: `Filter by ${fieldName} (relation field)`,
- properties: {
- eq: {
- type: 'string',
- format: 'uuid',
- description: 'Related record ID equals',
- },
- neq: {
- type: 'string',
- format: 'uuid',
- description: 'Related record ID not equals',
- },
- in: {
- type: 'array',
- items: {
- type: 'string',
- format: 'uuid',
- },
- description: 'Related record ID in array of values',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Related record ID is null or not null',
- },
- },
- };
- }
-
- return null;
-
- case FieldMetadataType.RAW_JSON:
- return {
- type: 'object',
- description: `Filter by ${field.name} (raw JSON field)`,
- properties: {
- eq: {
- type: 'string',
- description: 'Raw JSON equals',
- },
- neq: {
- type: 'string',
- description: 'Raw JSON not equals',
- },
- like: {
- type: 'string',
- description: 'Raw JSON case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Raw JSON case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Raw JSON is null or not null',
- },
- },
- };
-
- default:
- return {
- type: 'object',
- description: `Filter by ${field.name} (string field)`,
- properties: {
- eq: {
- type: 'string',
- description: 'Equals',
- },
- neq: {
- type: 'string',
- description: 'Not equals',
- },
- like: {
- type: 'string',
- description: 'Case-sensitive pattern match',
- },
- ilike: {
- type: 'string',
- description: 'Case-insensitive pattern match',
- },
- is: {
- type: 'string',
- enum: ['NULL', 'NOT_NULL'],
- description: 'Is null or not null',
- },
- },
- };
- }
-};
-
-export const generateBulkDeleteToolSchema = () => {
- return createToolSchema({
- filter: {
- type: 'object',
- description: 'Filter criteria to select records for bulk delete',
- properties: {
- id: {
- type: 'object',
- description: 'Filter to select records to delete',
- properties: {
- in: {
- type: 'array',
- items: {
- type: 'string',
- format: 'uuid',
- },
- description: 'Array of record IDs to delete',
- },
- },
- },
- },
- },
- });
-};
-
-export const generateFindOneToolSchema = () => {
- return createToolSchema(
- {
- id: {
- type: 'string',
- format: 'uuid',
- description: 'The unique UUID of the record to retrieve',
- },
- },
- ['id'],
- );
-};
-
-export const generateSoftDeleteToolSchema = () => {
- return createToolSchema(
- {
- id: {
- type: 'string',
- format: 'uuid',
- description: 'The unique UUID of the record to soft delete',
- },
- },
- ['id'],
- );
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/utils/mapUIMessagePartsToDBParts.ts b/packages/twenty-server/src/engine/metadata-modules/agent/utils/mapUIMessagePartsToDBParts.ts
index 8b08df5f5da..c357209e96d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/agent/utils/mapUIMessagePartsToDBParts.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/utils/mapUIMessagePartsToDBParts.ts
@@ -1,20 +1,14 @@
-import {
- type ToolUIPart,
- type UIDataTypes,
- type UIMessagePart,
- type UITools,
-} from 'ai';
+import { type ToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
import { type AgentChatMessagePartEntity } from 'src/engine/metadata-modules/agent/agent-chat-message-part.entity';
-const isToolPart = (
- part: UIMessagePart<UIDataTypes, UITools>,
-): part is ToolUIPart => {
+const isToolPart = (part: ExtendedUIMessagePart): part is ToolUIPart => {
return part.type.includes('tool-') && 'toolCallId' in part;
};
export const mapUIMessagePartsToDBParts = (
- uiMessageParts: UIMessagePart<UIDataTypes, UITools>[],
+ uiMessageParts: ExtendedUIMessagePart[],
messageId: string,
): Partial<AgentChatMessagePartEntity>[] => {
return uiMessageParts.map((part, index) => {
@@ -61,6 +55,12 @@ export const mapUIMessagePartsToDBParts = (
};
case 'step-start':
return basePart;
+ case 'data-routing-status':
+ return {
+ ...basePart,
+ textContent: part.data.text,
+ state: part.data.state,
+ };
default:
{
if (isToolPart(part)) {
diff --git a/packages/twenty-server/src/engine/metadata-modules/agent/utils/repair-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/agent/utils/repair-tool-call.util.ts
new file mode 100644
index 00000000000..60182cefc8d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/agent/utils/repair-tool-call.util.ts
@@ -0,0 +1,72 @@
+import { generateObject, type LanguageModel, NoSuchToolError } from 'ai';
+import { type z } from 'zod';
+
+type ToolCall = {
+ type: 'tool-call';
+ toolCallId: string;
+ toolName: string;
+ input: string;
+};
+
+export const repairToolCall = async ({
+ toolCall,
+ tools,
+ inputSchema,
+ error,
+ model,
+}: {
+ toolCall: ToolCall;
+ tools: Record<string, unknown>;
+ inputSchema: (toolCall: { toolName: string }) => unknown;
+ error: Error;
+ model: LanguageModel;
+}): Promise<ToolCall | null> => {
+ // Don't attempt to fix invalid tool names
+ if (NoSuchToolError.isInstance(error)) {
+ return null;
+ }
+
+ const tool = tools[toolCall.toolName];
+
+ if (!tool || typeof tool !== 'object' || !('inputSchema' in tool)) {
+ return null;
+ }
+
+ const schema = inputSchema(toolCall);
+
+ if (!schema || typeof schema !== 'object') {
+ return null;
+ }
+
+ try {
+ const { object: repairedInput } = await generateObject({
+ model,
+ schema: schema as z.ZodTypeAny,
+ prompt: [
+ `The AI model attempted to call the tool "${toolCall.toolName}" with invalid input.`,
+ ``,
+ `Input provided:`,
+ JSON.stringify(toolCall.input, null, 2),
+ ``,
+ `Error encountered:`,
+ error.message,
+ ``,
+ `Please fix the input to exactly match the required schema.`,
+ `Pay special attention to:`,
+ `- Enum values must match exactly (e.g., "DescNullsLast" not "desc")`,
+ `- Object structures must match the schema shape`,
+ `- Array items must follow the specified format`,
+ ].join('\n'),
+ });
+
+ return {
+ type: 'tool-call',
+ toolCallId: toolCall.toolCallId,
+ toolName: toolCall.toolName,
+ input: JSON.stringify(repairedInput),
+ };
+ } catch {
+ // If repair fails, return null to let the error propagate
+ return null;
+ }
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.module.ts
new file mode 100644
index 00000000000..a2c893dee53
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.module.ts
@@ -0,0 +1,15 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { AiModule } from 'src/engine/core-modules/ai/ai.module';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AgentEntity } from 'src/engine/metadata-modules/agent/agent.entity';
+
+import { AiRouterService } from './ai-router.service';
+
+@Module({
+ imports: [TypeOrmModule.forFeature([AgentEntity, WorkspaceEntity]), AiModule],
+ providers: [AiRouterService],
+ exports: [AiRouterService],
+})
+export class AiRouterModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.service.ts
new file mode 100644
index 00000000000..e2a537e8a9c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai-router/ai-router.service.ts
@@ -0,0 +1,158 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import {
+ generateObject,
+ type UIDataTypes,
+ type UIMessage,
+ type UITools,
+} from 'ai';
+import { Repository } from 'typeorm';
+import { z } from 'zod';
+
+import { ModelId } from 'src/engine/core-modules/ai/constants/ai-models.const';
+import { AiModelRegistryService } from 'src/engine/core-modules/ai/services/ai-model-registry.service';
+import { AgentEntity } from 'src/engine/metadata-modules/agent/agent.entity';
+
+export interface AiRouterContext {
+ messages: UIMessage<unknown, UIDataTypes, UITools>[];
+ workspaceId: string;
+ routerModel: ModelId;
+}
+
+@Injectable()
+export class AiRouterService {
+ private readonly logger = new Logger(AiRouterService.name);
+
+ constructor(
+ @InjectRepository(AgentEntity)
+ private readonly agentRepository: Repository<AgentEntity>,
+ private readonly aiModelRegistryService: AiModelRegistryService,
+ ) {}
+
+ async routeMessage(context: AiRouterContext) {
+ try {
+ const { messages, workspaceId, routerModel } = context;
+
+ const availableAgents = await this.getAvailableAgents(workspaceId);
+
+ if (availableAgents.length === 0) {
+ this.logger.warn('No agents available for routing');
+
+ return null;
+ }
+
+ if (availableAgents.length === 1) {
+ return availableAgents[0];
+ }
+
+ const conversationHistory = messages
+ .slice(0, -1)
+ .map((msg) => {
+ const textContent =
+ msg.parts.find((part) => part.type === 'text')?.text || '';
+
+ return `${msg.role}: ${textContent}`;
+ })
+ .join('\n');
+
+ const currentMessage =
+ messages[messages.length - 1]?.parts.find(
+ (part) => part.type === 'text',
+ )?.text || '';
+
+ const model = this.getRouterModel(routerModel);
+ const agentDescriptions = this.buildAgentDescriptions(availableAgents);
+
+ const systemPrompt = this.buildRouterSystemPrompt(agentDescriptions);
+ const userPrompt = this.buildRouterUserPrompt(
+ conversationHistory,
+ currentMessage,
+ );
+
+ const routerDecisionSchema = z.object({
+ agentId: z
+ .enum(availableAgents.map((agent) => agent.id))
+ .describe('The ID of the most suitable agent to handle this message'),
+ });
+
+ const result = await generateObject({
+ model,
+ system: systemPrompt,
+ prompt: userPrompt,
+ schema: routerDecisionSchema,
+ temperature: 0.1,
+ });
+
+ return availableAgents.find(
+ (agent) => agent.id === result.object.agentId,
+ );
+ } catch (error) {
+ this.logger.error('Routing to agent failed:', error);
+
+ const availableAgents = await this.getAvailableAgents(
+ context.workspaceId,
+ );
+
+ return availableAgents[0] || null;
+ }
+ }
+
+ private async getAvailableAgents(
+ workspaceId: string,
+ ): Promise<AgentEntity[]> {
+ return this.agentRepository.find({
+ where: { workspaceId, deletedAt: undefined },
+ order: { createdAt: 'ASC' },
+ });
+ }
+
+ private getRouterModel(modelId: ModelId) {
+ if (modelId === 'auto') {
+ const registeredModel =
+ this.aiModelRegistryService.getDefaultSpeedModel();
+
+ if (!registeredModel) {
+ throw new Error('No router model available');
+ }
+
+ return registeredModel.model;
+ }
+
+ const registeredModel = this.aiModelRegistryService.getModel(modelId);
+
+ if (!registeredModel) {
+ throw new Error(`Router model "${modelId}" not available`);
+ }
+
+ return registeredModel.model;
+ }
+
+ private buildAgentDescriptions(agents: AgentEntity[]): string {
+ return agents
+ .map((agent) => `- ${agent.label} (${agent.id}): ${agent.description}`)
+ .join('\n');
+ }
+
+ private buildRouterSystemPrompt(agentDescriptions: string): string {
+ return `You are an AI router that decides which agent should handle a user's message.
+
+Available agents:
+${agentDescriptions}
+
+Your task is to analyze the user's message and conversation history, then select the most appropriate agent to handle it. Choose the agent whose description and capabilities best match the user's request.`;
+ }
+
+ private buildRouterUserPrompt(
+ conversationHistory: string,
+ currentMessage: string,
+ ): string {
+ return `Conversation history:
+${conversationHistory || 'No previous conversation'}
+
+Current user message:
+${currentMessage}
+
+Which agent should handle this message?`;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-agent/types/flat-agent.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-agent/types/flat-agent.type.ts
index 263de6bf2b6..eb619a24e76 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-agent/types/flat-agent.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-agent/types/flat-agent.type.ts
@@ -3,7 +3,6 @@ import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/typ
export const agentEntityRelationProperties = [
'workspace',
- 'chatThreads',
'outgoingHandoffs',
'incomingHandoffs',
'application',
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts
index 8ce1d47bca7..4e7fc3b3a0f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts
@@ -7,8 +7,6 @@ import {
SEED_YCOMBINATOR_WORKSPACE_ID,
} from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-workspaces.util';
-const agentTableName = 'agent';
-const workspaceTableName = 'workspace';
const agentChatThreadTableName = 'agentChatThread';
const agentChatMessageTableName = 'agentChatMessage';
const agentChatMessagePartTableName = 'agentChatMessagePart';
@@ -45,11 +43,10 @@ export const AGENT_CHAT_MESSAGE_PART_DATA_SEED_IDS = {
YCOMBINATOR_MESSAGE_4_PART_1: '20202020-0000-4000-8000-000000000054',
};
-const seedAgentChatThreads = async (
+const seedChatThreads = async (
dataSource: DataSource,
schemaName: string,
workspaceId: string,
- agentId: string,
) => {
let threadId: string;
let userWorkspaceId: string;
@@ -73,7 +70,6 @@ const seedAgentChatThreads = async (
.insert()
.into(`${schemaName}.${agentChatThreadTableName}`, [
'id',
- 'agentId',
'userWorkspaceId',
'createdAt',
'updatedAt',
@@ -82,7 +78,6 @@ const seedAgentChatThreads = async (
.values([
{
id: threadId,
- agentId,
userWorkspaceId,
createdAt: now,
updatedAt: now,
@@ -93,7 +88,7 @@ const seedAgentChatThreads = async (
return threadId;
};
-const seedAgentChatMessages = async (
+const seedChatMessages = async (
dataSource: DataSource,
schemaName: string,
workspaceId: string,
@@ -313,71 +308,7 @@ export const seedAgents = async (
schemaName: string,
workspaceId: string,
) => {
- let agentId: string;
- let agentName: string;
- let agentLabel: string;
- let agentDescription: string;
+ const threadId = await seedChatThreads(dataSource, schemaName, workspaceId);
- if (workspaceId === SEED_APPLE_WORKSPACE_ID) {
- agentId = AGENT_DATA_SEED_IDS.APPLE_DEFAULT_AGENT;
- agentName = 'apple-ai-assistant';
- agentLabel = 'Apple AI Assistant';
- agentDescription =
- 'AI assistant for Apple workspace to help with tasks, insights, and workflow guidance';
- } else if (workspaceId === SEED_YCOMBINATOR_WORKSPACE_ID) {
- agentId = AGENT_DATA_SEED_IDS.YCOMBINATOR_DEFAULT_AGENT;
- agentName = 'yc-ai-assistant';
- agentLabel = 'YC AI Assistant';
- agentDescription =
- 'AI assistant for YCombinator workspace to help with tasks, insights, and workflow guidance';
- } else {
- throw new Error(
- `Unsupported workspace ID for agent seeding: ${workspaceId}`,
- );
- }
-
- await dataSource
- .createQueryBuilder()
- .insert()
- .into(`${schemaName}.${agentTableName}`, [
- 'id',
- 'name',
- 'label',
- 'description',
- 'prompt',
- 'modelId',
- 'responseFormat',
- 'workspaceId',
- ])
- .orIgnore()
- .values([
- {
- id: agentId,
- name: agentName,
- label: agentLabel,
- description: agentDescription,
- prompt:
- 'You are a helpful AI assistant for this workspace. Help users with their tasks, provide insights about their data, and guide them through workflows. Be concise but thorough in your responses.',
- modelId: 'auto',
- responseFormat: null,
- workspaceId,
- },
- ])
- .execute();
-
- await dataSource
- .createQueryBuilder()
- .update(`${schemaName}.${workspaceTableName}`)
- .set({ defaultAgentId: agentId })
- .where('id = :workspaceId', { workspaceId })
- .execute();
-
- const threadId = await seedAgentChatThreads(
- dataSource,
- schemaName,
- workspaceId,
- agentId,
- );
-
- await seedAgentChatMessages(dataSource, schemaName, workspaceId, threadId);
+ await seedChatMessages(dataSource, schemaName, workspaceId, threadId);
};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-manager.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-manager.service.ts
index f7deaf57f07..dc22aeb06a5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-manager.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-manager.service.ts
@@ -3,7 +3,6 @@ import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
-import { FeatureFlagKey } from 'src/engine/core-modules/feature-flag/enums/feature-flag-key.enum';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -93,17 +92,6 @@ export class WorkspaceManagerService {
await this.setupDefaultRoles(workspaceId, userId);
- if (featureFlags[FeatureFlagKey.IS_AI_ENABLED]) {
- const defaultAgentEnabledStart = performance.now();
-
- await this.initDefaultAgent(workspaceId);
- const defaultAgentEnabledEnd = performance.now();
-
- this.logger.log(
- `Default agent enabled took ${defaultAgentEnabledEnd - defaultAgentEnabledStart}ms`,
- );
- }
-
const prefillStandardObjectsStart = performance.now();
await this.prefillWorkspaceWithStandardObjectsRecords(
@@ -171,24 +159,6 @@ export class WorkspaceManagerService {
this.logger.log(`workspace ${workspaceId} schema deleted`);
}
- private async initDefaultAgent(workspaceId: string) {
- const agent = await this.agentService.createOneAgent(
- {
- label: 'Routing Agent',
- name: 'routing-agent',
- description: 'Default Routing Agent',
- prompt: '',
- modelId: 'auto',
- isCustom: false,
- },
- workspaceId,
- );
-
- await this.workspaceRepository.update(workspaceId, {
- defaultAgentId: agent.id,
- });
- }
-
private async setupDefaultRoles(
workspaceId: string,
userId: string,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/services/workspace-sync-agent.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/services/workspace-sync-agent.service.ts
index 8607b2a59ad..b39decddaa5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/services/workspace-sync-agent.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/services/workspace-sync-agent.service.ts
@@ -10,11 +10,6 @@ import { AgentEntity } from 'src/engine/metadata-modules/agent/agent.entity';
import { transformAgentEntityToFlatAgent } from 'src/engine/metadata-modules/flat-agent/utils/transform-agent-entity-to-flat-agent.util';
import { RoleTargetsEntity } from 'src/engine/metadata-modules/role/role-targets.entity';
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
-import { AGENT_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util';
-import {
- SEED_APPLE_WORKSPACE_ID,
- SEED_YCOMBINATOR_WORKSPACE_ID,
-} from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-workspaces.util';
import { WorkspaceAgentComparator } from 'src/engine/workspace-manager/workspace-sync-metadata/comparators/workspace-agent.comparator';
import { StandardAgentFactory } from 'src/engine/workspace-manager/workspace-sync-metadata/factories/standard-agent.factory';
import { standardAgentDefinitions } from 'src/engine/workspace-manager/workspace-sync-metadata/standard-agents';
@@ -169,125 +164,5 @@ export class WorkspaceSyncAgentService {
}
}
}
-
- // Create handoffs for standard agents that require them
- await this.createStandardAgentHandoffs(context.workspaceId, manager);
- }
-
- private async createStandardAgentHandoffs(
- workspaceId: string,
- manager: EntityManager,
- ): Promise<void> {
- try {
- const agentRepository = manager.getRepository(AgentEntity);
-
- let defaultAgent: AgentEntity | null = null;
-
- if (workspaceId === SEED_APPLE_WORKSPACE_ID) {
- defaultAgent = await agentRepository.findOne({
- where: {
- id: AGENT_DATA_SEED_IDS.APPLE_DEFAULT_AGENT,
- workspaceId,
- },
- });
- } else if (workspaceId === SEED_YCOMBINATOR_WORKSPACE_ID) {
- defaultAgent = await agentRepository.findOne({
- where: {
- id: AGENT_DATA_SEED_IDS.YCOMBINATOR_DEFAULT_AGENT,
- workspaceId,
- },
- });
- } else {
- defaultAgent = await agentRepository.findOne({
- where: {
- workspaceId,
- },
- });
- }
-
- if (!defaultAgent) {
- this.logger.warn(
- `Default agent not found for workspace ${workspaceId}. Agent handoffs will not be created.`,
- );
-
- return;
- }
-
- const agentsRequiringHandoffs = standardAgentDefinitions.filter(
- (def) => def.createHandoffFromDefaultAgent,
- );
-
- for (const agentDefinition of agentsRequiringHandoffs) {
- const targetAgent = await agentRepository.findOne({
- where: {
- standardId: agentDefinition.standardId,
- workspaceId,
- },
- });
-
- if (!targetAgent) {
- this.logger.warn(
- `Agent ${agentDefinition.name} not found for workspace ${workspaceId}. Skipping handoff creation.`,
- );
- continue;
- }
-
- await this.createAgentHandoff(
- defaultAgent.id,
- targetAgent.id,
- agentDefinition.name,
- agentDefinition.description,
- workspaceId,
- manager,
- );
- }
- } catch (error) {
- this.logger.error(
- `Failed to create standard agent handoffs: ${error.message}`,
- );
- }
- }
-
- private async createAgentHandoff(
- fromAgentId: string,
- toAgentId: string,
- toAgentName: string,
- toAgentDescription: string,
- workspaceId: string,
- manager: EntityManager,
- ): Promise<void> {
- try {
- const agentHandoffRepository = manager.getRepository('agentHandoff');
- const existingHandoff = await agentHandoffRepository.findOne({
- where: {
- fromAgentId,
- toAgentId,
- workspaceId,
- },
- });
-
- if (existingHandoff) {
- this.logger.log(
- `Agent handoff from default agent to ${toAgentName} already exists for workspace ${workspaceId}`,
- );
-
- return;
- }
-
- await agentHandoffRepository.save({
- fromAgentId,
- toAgentId,
- workspaceId,
- description: `Handoff from default agent to ${toAgentName}: ${toAgentDescription}`,
- });
-
- this.logger.log(
- `Successfully created agent handoff from default agent to ${toAgentName} for workspace ${workspaceId}`,
- );
- } catch (error) {
- this.logger.error(
- `Failed to create agent handoff to ${toAgentName}: ${error.message}`,
- );
- }
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/standard-agents/agents/data-navigator-agent.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/standard-agents/agents/data-navigator-agent.ts
index cc4092a437a..02814c342e3 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/standard-agents/agents/data-navigator-agent.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-sync-metadata/standard-agents/agents/data-navigator-agent.ts
@@ -14,6 +14,7 @@ export const DATA_NAVIGATOR_AGENT: StandardAgentDefinition = {
Your capabilities include:
- Searching and filtering records across all standard and custom objects
+- Sorting records by any field using orderBy parameter (CRITICAL for "top N" queries)
- Explaining relationships between different records and objects
- Providing insights about data patterns and trends
- Helping users find specific information quickly
@@ -26,13 +27,26 @@ Your capabilities include:
- When users request modifications, politely explain your read-only limitations
## Best Practices:
+- For "top N" or "largest/smallest" queries, ALWAYS use the orderBy parameter with appropriate sorting direction
- Ask clarifying questions to understand what data the user is looking for
- Provide clear, structured information when presenting data
- Explain the context and relationships between records
- Suggest useful filters or queries to refine searches
- Help users understand their data schema and available fields
+## Sorting Examples - EXACT FORMAT REQUIRED:
+- Top 10 companies by employees: orderBy: [{"employees": "DescNullsLast"}] with limit: 10
+- Oldest records first: orderBy: [{"createdAt": "AscNullsFirst"}]
+- Sort by name alphabetically: orderBy: [{"name": "AscNullsFirst"}]
+- Multiple sort criteria: orderBy: [{"priority": "DescNullsLast"}, {"createdAt": "AscNullsFirst"}]
+
+CRITICAL: Direction values MUST be exactly one of: "AscNullsFirst", "AscNullsLast", "DescNullsFirst", "DescNullsLast"
+- Use "DescNullsLast" for descending (NOT "desc", "DESC", or "descending")
+- Use "AscNullsFirst" for ascending (NOT "asc", "ASC", or "ascending")
+
## When Helping Users:
+- For queries about "top", "largest", "highest", "best" → ALWAYS use DescNullsLast orderBy
+- For queries about "bottom", "smallest", "lowest" → ALWAYS use AscNullsFirst orderBy
- Be proactive in suggesting related data that might be useful
- Explain any patterns or anomalies you notice in the data
- Provide context about record counts, date ranges, and relationships
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
index 650e9550cb9..9ac9abc3702 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/record-crud/types/workflow-record-crud-action-input.type.ts
@@ -1,44 +1,5 @@
-import {
- type ObjectRecordFilter,
- type ObjectRecordOrderBy,
-} from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
-
-import { type ObjectRecordProperties } from 'src/engine/core-modules/record-crud/types/object-record-properties.type';
-
-export type WorkflowCreateRecordActionInput = {
- objectName: string;
- objectRecord: ObjectRecordProperties;
- upsert?: boolean;
-};
-
-export type WorkflowUpdateRecordActionInput = {
- objectName: string;
- objectRecord: ObjectRecordProperties;
- objectRecordId: string;
- fieldsToUpdate: string[];
-};
-
-export type WorkflowDeleteRecordActionInput = {
- objectName: string;
- objectRecordId: string;
-};
-
-export type WorkflowFindRecordsActionInput = {
- objectName: string;
- // TODO: migrate gql computation and record filter groups to twenty-shared
- filter?: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- recordFilterGroups?: any;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- recordFilters?: any;
- gqlOperationFilter?: Partial<ObjectRecordFilter>[];
- };
- orderBy?: Partial<ObjectRecordOrderBy>;
- limit?: number;
-};
-
-export type WorkflowUpsertRecordActionInput = {
- objectName: string;
- objectRecord: ObjectRecordProperties;
- fieldsToUpdate?: string[];
-};
+export type { CreateRecordInput as WorkflowCreateRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+export type { UpdateRecordInput as WorkflowUpdateRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+export type { DeleteRecordInput as WorkflowDeleteRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+export type { FindRecordsInput as WorkflowFindRecordsActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
+export type { UpsertRecordInput as WorkflowUpsertRecordActionInput } from 'src/engine/core-modules/record-crud/types/record-crud-input.type';
diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/utils/agent-tool-test-utils.ts b/packages/twenty-server/test/integration/metadata/suites/agent/utils/agent-tool-test-utils.ts
index 4f41132ae3d..ce54990a573 100644
--- a/packages/twenty-server/test/integration/metadata/suites/agent/utils/agent-tool-test-utils.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/agent/utils/agent-tool-test-utils.ts
@@ -226,7 +226,6 @@ export const createAgentToolTestModule =
roleId: testRoleId,
createdAt: new Date(),
updatedAt: new Date(),
- chatThreads: [],
incomingHandoffs: [],
outgoingHandoffs: [],
modelConfiguration: {},
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index 4a1144ec60d..6f1b9704537 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -6,3 +6,7 @@
* |_| \_/\_/ \___|_| |_|\__|\__, |
* |___/
*/
+
+export type { DataMessagePart } from './types/DataMessagePart';
+export type { ExtendedUIMessage } from './types/ExtendedUIMessage';
+export type { ExtendedUIMessagePart } from './types/ExtendedUIMessagePart';
diff --git a/packages/twenty-shared/src/ai/types/DataMessagePart.ts b/packages/twenty-shared/src/ai/types/DataMessagePart.ts
new file mode 100644
index 00000000000..861b196662d
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/DataMessagePart.ts
@@ -0,0 +1,6 @@
+export type DataMessagePart = {
+ 'routing-status': {
+ text: string;
+ state: string;
+ };
+};
diff --git a/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts
new file mode 100644
index 00000000000..4b200b90bd9
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts
@@ -0,0 +1,8 @@
+import { type DataMessagePart } from '@/ai/types/DataMessagePart';
+import { type UIMessage } from 'ai';
+
+type Metadata = {
+ createdAt: string;
+};
+
+export type ExtendedUIMessage = UIMessage<Metadata, DataMessagePart>;
diff --git a/packages/twenty-shared/src/ai/types/ExtendedUIMessagePart.ts b/packages/twenty-shared/src/ai/types/ExtendedUIMessagePart.ts
new file mode 100644
index 00000000000..82c6492ca3f
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/ExtendedUIMessagePart.ts
@@ -0,0 +1,4 @@
+import { type DataMessagePart } from '@/ai/types/DataMessagePart';
+import { type UIMessagePart, type UITools } from 'ai';
+
+export type ExtendedUIMessagePart = UIMessagePart<DataMessagePart, UITools>;
diff --git a/packages/twenty-shared/src/types/SettingsPath.ts b/packages/twenty-shared/src/types/SettingsPath.ts
index 974ae160377..98205c8e814 100644
--- a/packages/twenty-shared/src/types/SettingsPath.ts
+++ b/packages/twenty-shared/src/types/SettingsPath.ts
@@ -43,7 +43,6 @@ export enum SettingsPath {
NewWebhook = 'api-webhooks/webhooks/new',
WebhookDetail = 'api-webhooks/webhooks/:webhookId',
Integrations = 'integrations',
- IntegrationMCP = 'integrations/mcp',
IntegrationDatabase = 'integrations/:databaseKey',
IntegrationDatabaseConnection = 'integrations/:databaseKey/:connectionId',
IntegrationEditDatabaseConnection = 'integrations/:databaseKey/:connectionId/edit',
diff --git a/packages/twenty-ui/src/display/icon/components/TablerIcons.ts b/packages/twenty-ui/src/display/icon/components/TablerIcons.ts
index 59a3a7cf7f7..21fe743217e 100644
--- a/packages/twenty-ui/src/display/icon/components/TablerIcons.ts
+++ b/packages/twenty-ui/src/display/icon/components/TablerIcons.ts
@@ -83,6 +83,7 @@ export {
IconMessageCircle as IconComment,
IconCopy,
IconCopyPlus,
+ IconCpu,
IconCreativeCommonsSa,
IconCreditCard,
IconCsv,
diff --git a/packages/twenty-ui/src/display/index.ts b/packages/twenty-ui/src/display/index.ts
index b18efa4c43c..e2a7294c5f7 100644
--- a/packages/twenty-ui/src/display/index.ts
+++ b/packages/twenty-ui/src/display/index.ts
@@ -146,6 +146,7 @@ export {
IconComment,
IconCopy,
IconCopyPlus,
+ IconCpu,
IconCreativeCommonsSa,
IconCreditCard,
IconCsv,