Skip to content

The open alternative to Salesforce, designed for AI.

Let runAgent messages carry file attachments (#25835)

Abdul Rahmanef6afd5a20eb
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index a67566a3fed..8880e3333d2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -5252,6 +5252,7 @@ input RunAgentInput {
input RunAgentMessageInput {
role: RunAgentMessageRole!
content: String!
+ attachments: [RunAgentMessageAttachmentInput!]
}
enum RunAgentMessageRole {
@@ -5259,6 +5260,11 @@ enum RunAgentMessageRole {
assistant
}
+input RunAgentMessageAttachmentInput {
+ fileId: UUID!
+ filename: String
+}
+
input CreateWebhookInput {
id: UUID
targetUrl: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 139e6b9d4cc..26f5915a252 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -7703,7 +7703,9 @@ export interface CreateEmailingDomainInput {domain: Scalars['String']}
export interface RunAgentInput {agentUniversalIdentifier: Scalars['String'],prompt?: (Scalars['String'] | null),runAsWorkspaceMemberId?: (Scalars['UUID'] | null),messages?: (RunAgentMessageInput[] | null)}
-export interface RunAgentMessageInput {role: RunAgentMessageRole,content: Scalars['String']}
+export interface RunAgentMessageInput {role: RunAgentMessageRole,content: Scalars['String'],attachments?: (RunAgentMessageAttachmentInput[] | null)}
+
+export interface RunAgentMessageAttachmentInput {fileId: Scalars['UUID'],filename?: (Scalars['String'] | null)}
export interface CreateWebhookInput {id?: (Scalars['UUID'] | null),targetUrl: Scalars['String'],operations: Scalars['String'][],description?: (Scalars['String'] | null),secret?: (Scalars['String'] | null)}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 55a1e91118c..9daf1a2b22b 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -103,7 +103,7 @@ export default {
425,
545,
549,
- 575
+ 576
],
"types": {
"BillingProductDTO": {
@@ -9862,7 +9862,7 @@ export default {
346,
{
"input": [
- 550,
+ 551,
"CreateWebhookInput!"
]
}
@@ -9871,7 +9871,7 @@ export default {
346,
{
"input": [
- 551,
+ 552,
"UpdateWebhookInput!"
]
}
@@ -9889,7 +9889,7 @@ export default {
388,
{
"input": [
- 553,
+ 554,
"UpdateMessageFolderInput!"
]
}
@@ -9898,7 +9898,7 @@ export default {
388,
{
"input": [
- 555,
+ 556,
"UpdateMessageFoldersInput!"
]
}
@@ -9907,7 +9907,7 @@ export default {
383,
{
"input": [
- 556,
+ 557,
"UpdateCalendarChannelInput!"
]
}
@@ -9916,7 +9916,7 @@ export default {
381,
{
"input": [
- 558,
+ 559,
"SetAppKeyValueInput!"
]
}
@@ -9937,7 +9937,7 @@ export default {
379,
{
"input": [
- 559,
+ 560,
"EnqueueJobInput!"
]
}
@@ -9946,7 +9946,7 @@ export default {
380,
{
"input": [
- 560,
+ 561,
"EnqueueJobsInput!"
]
}
@@ -9955,7 +9955,7 @@ export default {
8,
{
"input": [
- 562,
+ 563,
"ReportAppConnectionAuthFailureInput!"
]
}
@@ -9985,7 +9985,7 @@ export default {
1
],
"fileAttachments": [
- 563,
+ 564,
"[FileAttachmentInput!]"
]
}
@@ -10014,14 +10014,14 @@ export default {
"UUID!"
],
"answers": [
- 564,
+ 565,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 563,
+ 564,
"[FileAttachmentInput!]"
]
}
@@ -10099,7 +10099,7 @@ export default {
365,
{
"input": [
- 565,
+ 566,
"CreateSkillInput!"
]
}
@@ -10108,7 +10108,7 @@ export default {
365,
{
"input": [
- 566,
+ 567,
"UpdateSkillInput!"
]
}
@@ -10166,7 +10166,7 @@ export default {
394,
{
"input": [
- 567,
+ 568,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -10184,7 +10184,7 @@ export default {
280,
{
"input": [
- 568,
+ 569,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -10350,7 +10350,7 @@ export default {
283,
{
"input": [
- 569
+ 570
]
}
],
@@ -10528,7 +10528,7 @@ export default {
8,
{
"input": [
- 570,
+ 571,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -10562,7 +10562,7 @@ export default {
235,
{
"input": [
- 571,
+ 572,
"SetupOIDCSsoInput!"
]
}
@@ -10571,7 +10571,7 @@ export default {
235,
{
"input": [
- 572,
+ 573,
"SetupSAMLSsoInput!"
]
}
@@ -10580,7 +10580,7 @@ export default {
231,
{
"input": [
- 573,
+ 574,
"DeleteSsoInput!"
]
}
@@ -10589,7 +10589,7 @@ export default {
232,
{
"input": [
- 574,
+ 575,
"EditSsoInput!"
]
}
@@ -10618,7 +10618,7 @@ export default {
361,
{
"type": [
- 575,
+ 576,
"AnalyticsType!"
],
"name": [
@@ -10661,7 +10661,7 @@ export default {
351,
{
"input": [
- 576,
+ 577,
"CreateCalendarEventInput!"
]
}
@@ -10670,7 +10670,7 @@ export default {
360,
{
"input": [
- 577,
+ 578,
"SendEmailInput!"
]
}
@@ -10692,7 +10692,7 @@ export default {
"String!"
],
"connectionParameters": [
- 579,
+ 580,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10704,7 +10704,7 @@ export default {
195,
{
"input": [
- 581,
+ 582,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -10797,7 +10797,7 @@ export default {
"String!"
],
"files": [
- 582,
+ 583,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -13336,11 +13336,25 @@ export default {
"content": [
1
],
+ "attachments": [
+ 550
+ ],
"__typename": [
1
]
},
"RunAgentMessageRole": {},
+ "RunAgentMessageAttachmentInput": {
+ "fileId": [
+ 3
+ ],
+ "filename": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateWebhookInput": {
"id": [
3
@@ -13366,7 +13380,7 @@ export default {
3
],
"update": [
- 552
+ 553
],
"__typename": [
1
@@ -13394,7 +13408,7 @@ export default {
3
],
"update": [
- 554
+ 555
],
"__typename": [
1
@@ -13413,7 +13427,7 @@ export default {
3
],
"update": [
- 554
+ 555
],
"__typename": [
1
@@ -13424,7 +13438,7 @@ export default {
3
],
"update": [
- 557
+ 558
],
"__typename": [
1
@@ -13489,7 +13503,7 @@ export default {
9
],
"jobs": [
- 561
+ 562
],
"retryLimit": [
28
@@ -13777,7 +13791,7 @@ export default {
1
],
"files": [
- 578
+ 579
],
"__typename": [
1
@@ -13799,13 +13813,13 @@ export default {
1
],
"IMAP": [
- 580
+ 581
],
"SMTP": [
- 580
+ 581
],
"CALDAV": [
- 580
+ 581
],
"__typename": [
1
@@ -13870,7 +13884,7 @@ export default {
272,
{
"input": [
- 584,
+ 585,
"LogicFunctionLogsInput!"
]
}
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index fe4cde90276..5b8a2fe739f 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -132,7 +132,8 @@ const { result, error, success } = await runAgent({
Key points:
- Provide **exactly one** of `prompt` (string) or `messages` (1 to 100 entries
- of `{ role: 'user' | 'assistant', content: string }`).
+ of `{ role: 'user' | 'assistant', content: string }`). A `user` message can
+ also carry file attachments — see below.
- The agent runs **synchronously** and can read/update records itself via its
own tools — `runAgent()` resolves once the run completes.
- An app can only run its own agents.
@@ -164,6 +165,35 @@ export default defineApplicationRole({
guard on whether any target field is still empty before calling `runAgent()`.
</Warning>
+### Sending files with a message
+
+A `user` message can carry `attachments`, so the agent sees a screenshot or a
+PDF instead of only its name. Each entry references a file your app has already
+uploaded into the `agent-chat` folder:
+
+```ts src/logic-functions/describe-screenshot.ts
+const { result } = await runAgent({
+ agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
+ messages: [
+ {
+ role: 'user',
+ content: 'What does this error screen say?',
+ attachments: [{ fileId: uploadedFileId, filename: 'error.png' }],
+ },
+ ],
+});
+```
+
+Uploading requires the `UPLOAD_FILE` permission flag on the app's default role,
+alongside `AI`. `filename` is optional and only labels the file for the model.
+
+- Only `user` messages may carry attachments. They cannot be represented on an
+ assistant turn, so `runAgent()` rejects them there rather than dropping them.
+- At most **10** attachments per message.
+- The `fileId` must name a fully uploaded file in the same workspace, under the
+ `agent-chat` folder. Anything else fails the call instead of quietly
+ answering without the file.
+
### Running on behalf of a workspace member
Pass `runAsWorkspaceMemberId` when the run is triggered by a person — a chat
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index fe2161468dc..3d779698f13 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -5773,7 +5773,13 @@ export type RunAgentInput = {
runAsWorkspaceMemberId?: InputMaybe<Scalars['UUID']['input']>;
};
+export type RunAgentMessageAttachmentInput = {
+ fileId: Scalars['UUID']['input'];
+ filename?: InputMaybe<Scalars['String']['input']>;
+};
+
export type RunAgentMessageInput = {
+ attachments?: InputMaybe<Array<RunAgentMessageAttachmentInput>>;
content: Scalars['String']['input'];
role: RunAgentMessageRole;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
index f2ef55c39e8..5cc32185ba7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
@@ -4,6 +4,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
+import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileUrlModule } from 'src/engine/core-modules/file/file-url/file-url.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
@@ -28,6 +29,7 @@ import { AgentRunResolver } from './resolvers/agent-run.resolver';
import { AgentActorContextService } from './services/agent-actor-context.service';
import { AgentAsyncExecutorService } from './services/agent-async-executor.service';
import { AgentRunService } from './services/agent-run.service';
+import { RunAgentAttachmentService } from './services/run-agent-attachment.service';
@Module({
imports: [
@@ -49,6 +51,7 @@ import { AgentRunService } from './services/agent-run.service';
AgentMessageEntity,
AgentMessagePartEntity,
AgentTurnEntity,
+ FileEntity,
RoleTargetEntity,
WorkspaceEntity,
]),
@@ -60,8 +63,10 @@ import { AgentRunService } from './services/agent-run.service';
AgentMessagePartResolver,
AgentRunResolver,
AgentRunService,
+ RunAgentAttachmentService,
provideWorkspaceScopedRepository(RoleTargetEntity),
provideWorkspaceScopedRepository(AgentEntity),
+ provideWorkspaceScopedRepository(FileEntity),
],
exports: [
AgentAsyncExecutorService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const.ts
new file mode 100644
index 00000000000..8154a502f54
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const.ts
@@ -0,0 +1 @@
+export const MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH = 255;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const.ts
new file mode 100644
index 00000000000..629c2c99bc3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const.ts
@@ -0,0 +1 @@
+export const MAX_RUN_AGENT_MESSAGE_ATTACHMENTS = 10;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message-attachment.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message-attachment.input.ts
new file mode 100644
index 00000000000..ada0af03264
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message-attachment.input.ts
@@ -0,0 +1,20 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
+import { type RunAgentMessageAttachment } from 'twenty-shared/application';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const';
+
+@InputType('RunAgentMessageAttachmentInput')
+export class RunAgentMessageAttachmentInputDTO implements RunAgentMessageAttachment {
+ @IsUUID()
+ @Field(() => UUIDScalarType)
+ fileId: string;
+
+ @IsString()
+ @IsOptional()
+ @MaxLength(MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH)
+ @Field({ nullable: true })
+ filename?: string;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input.ts
index 9505153f0f2..b33b842094b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input.ts
@@ -1,8 +1,21 @@
import { Field, InputType } from '@nestjs/graphql';
-import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
+import { Type } from 'class-transformer';
+import {
+ ArrayMaxSize,
+ IsArray,
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ ValidateIf,
+ ValidateNested,
+} from 'class-validator';
import { type RunAgentMessage } from 'twenty-shared/application';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { MAX_RUN_AGENT_MESSAGE_ATTACHMENTS } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const';
+import { RunAgentMessageAttachmentInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message-attachment.input';
import { RunAgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/enums/run-agent-message-role.enum';
@InputType('RunAgentMessageInput')
@@ -12,7 +25,18 @@ export class RunAgentMessageInputDTO implements RunAgentMessage {
role: RunAgentMessageRole;
@IsString()
+ @ValidateIf(
+ (message: RunAgentMessageInputDTO) => !isNonEmptyArray(message.attachments),
+ )
@IsNotEmpty()
@Field()
content: string;
+
+ @IsArray()
+ @IsOptional()
+ @ArrayMaxSize(MAX_RUN_AGENT_MESSAGE_ATTACHMENTS)
+ @ValidateNested({ each: true })
+ @Type(() => RunAgentMessageAttachmentInputDTO)
+ @Field(() => [RunAgentMessageAttachmentInputDTO], { nullable: true })
+ attachments?: RunAgentMessageAttachmentInputDTO[];
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
index c5c06d250d3..8d983845ed5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
@@ -25,6 +25,9 @@ import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai
UsageLimitGraphqlApiExceptionFilter,
BillingGraphqlApiExceptionFilter,
)
+// TODO(@abdulrahmancodes): install ResolverValidationPipe here; without it every
+// class-validator decorator on RunAgentInputDTO is inert. Enabling it rejects the
+// empty assistant turns the Slack app replays, so those callers go first.
@MetadataResolver()
export class AgentRunResolver {
constructor(private readonly agentRunService: AgentRunService) {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts
new file mode 100644
index 00000000000..ac2aefc451c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts
@@ -0,0 +1,58 @@
+import { FileFolder } from 'twenty-shared/types';
+import { In, Like } from 'typeorm';
+
+import { RunAgentAttachmentService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service';
+
+const WORKSPACE_ID = 'workspace-id';
+const FILE_ID = '6fdbd0ba-9a10-4b71-b0b7-2b1d64f8dc27';
+
+describe('RunAgentAttachmentService', () => {
+ it('resolves attachments only against uploaded agent chat files of the workspace', async () => {
+ const fileRepository = {
+ find: jest
+ .fn()
+ .mockResolvedValue([{ id: FILE_ID, mimeType: 'image/png' }]),
+ };
+ const service = new RunAgentAttachmentService(
+ fileRepository as never,
+ {
+ signFileByIdUrl: jest
+ .fn()
+ .mockResolvedValue('https://twenty.test/file'),
+ } as never,
+ );
+
+ await service.buildModelMessagesOrThrow({
+ messages: [
+ { role: 'user', content: 'hi', attachments: [{ fileId: FILE_ID }] },
+ ],
+ workspaceId: WORKSPACE_ID,
+ });
+
+ expect(fileRepository.find).toHaveBeenCalledWith(WORKSPACE_ID, {
+ where: {
+ id: In([FILE_ID]),
+ path: Like(`${FileFolder.AgentChat}/%`),
+ status: 'UPLOADED',
+ },
+ });
+ });
+
+ it('does not query files for a conversation that carries no attachment', async () => {
+ const fileRepository = { find: jest.fn() };
+ const service = new RunAgentAttachmentService(
+ fileRepository as never,
+ {
+ signFileByIdUrl: jest.fn(),
+ } as never,
+ );
+
+ expect(
+ await service.buildModelMessagesOrThrow({
+ messages: [{ role: 'user', content: 'hello' }],
+ workspaceId: WORKSPACE_ID,
+ }),
+ ).toEqual([{ role: 'user', content: 'hello' }]);
+ expect(fileRepository.find).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index d795ee1b436..f590d2afffc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -5,7 +5,6 @@ import {
generateText,
jsonSchema,
type LanguageModelUsage,
- type ModelMessage,
Output,
isStepCount,
type StepResult,
@@ -46,6 +45,7 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent
import { OPEN_ENDED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/open-ended-agent-registry-tool-categories.const';
import { WORKFLOW_AGENT_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-excluded-tool-names.const';
import { WORKFLOW_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/workflow-agent-registry-tool-categories.const';
+import { RunAgentAttachmentService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-tool-loading-strategy.type';
import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
@@ -106,6 +106,7 @@ export class AgentAsyncExecutorService {
private readonly nativeToolBinder: NativeToolBinderService,
private readonly aiBillingService: AiBillingService,
private readonly metricsService: MetricsService,
+ private readonly runAgentAttachmentService: RunAgentAttachmentService,
@InjectWorkspaceScopedRepository(RoleTargetEntity)
private readonly roleTargetRepository: WorkspaceScopedRepository<RoleTargetEntity>,
@InjectRepository(WorkspaceEntity)
@@ -381,16 +382,17 @@ export class AgentAsyncExecutorService {
let hasNoMoreAvailableCredits = false;
+ const modelMessages =
+ await this.runAgentAttachmentService.buildModelMessagesOrThrow({
+ messages,
+ workspaceId,
+ });
+
const textResponse = await generateText({
instructions: `${baseSystemPrompt}\n\n${agent ? tipTapDocumentToMarkdown(agent.prompt) : ''}${toolCatalogSection}`,
tools,
model: registeredModel.model,
- messages: messages.map(
- (message): ModelMessage => ({
- role: message.role,
- content: message.content,
- }),
- ),
+ messages: modelMessages,
stopWhen: (step) =>
isStepCount(AGENT_CONFIG.MAX_STEPS)(step) ||
hasNoMoreAvailableCredits,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
index 6ec9c5469dc..53fe8e064f3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
@@ -149,6 +149,13 @@ export class AgentRunService {
success: true,
};
} catch (error) {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.INVALID_AGENT_INPUT
+ ) {
+ throw error;
+ }
+
this.logger.error(
`Agent execution failed for ${input.agentUniversalIdentifier}`,
error instanceof Error ? error.stack : error,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service.ts
new file mode 100644
index 00000000000..0c3193c203d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service.ts
@@ -0,0 +1,77 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ModelMessage } from 'ai';
+import { type RunAgentMessage } from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { In, Like } from 'typeorm';
+
+import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
+import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
+import { type ResolvedRunAgentAttachment } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type';
+import { buildRunAgentModelMessageOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-run-agent-model-message.util';
+import { extractRunAgentAttachmentFileIdsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/extract-run-agent-attachment-file-ids.util';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+
+@Injectable()
+export class RunAgentAttachmentService {
+ constructor(
+ @InjectWorkspaceScopedRepository(FileEntity)
+ private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
+ private readonly fileUrlService: FileUrlService,
+ ) {}
+
+ async buildModelMessagesOrThrow({
+ messages,
+ workspaceId,
+ }: {
+ messages: RunAgentMessage[];
+ workspaceId: string;
+ }): Promise<ModelMessage[]> {
+ const fileIds = extractRunAgentAttachmentFileIdsOrThrow(messages);
+
+ const attachmentsByFileId = isNonEmptyArray(fileIds)
+ ? await this.resolveAttachments({ fileIds, workspaceId })
+ : new Map<string, ResolvedRunAgentAttachment>();
+
+ return messages.map((message) =>
+ buildRunAgentModelMessageOrThrow({ message, attachmentsByFileId }),
+ );
+ }
+
+ private async resolveAttachments({
+ fileIds,
+ workspaceId,
+ }: {
+ fileIds: string[];
+ workspaceId: string;
+ }): Promise<Map<string, ResolvedRunAgentAttachment>> {
+ const files = await this.fileRepository.find(workspaceId, {
+ where: {
+ id: In(fileIds),
+ path: Like(`${FileFolder.AgentChat}/%`),
+ status: FILE_STATUS.UPLOADED,
+ },
+ });
+
+ const resolvedEntries = await Promise.all(
+ files.map(
+ async (file): Promise<[string, ResolvedRunAgentAttachment]> => [
+ file.id,
+ {
+ mediaType: file.mimeType,
+ url: await this.fileUrlService.signFileByIdUrl({
+ fileId: file.id,
+ workspaceId,
+ fileFolder: FileFolder.AgentChat,
+ }),
+ },
+ ],
+ ),
+ );
+
+ return new Map(resolvedEntries);
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type.ts
new file mode 100644
index 00000000000..87eb62890ec
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type.ts
@@ -0,0 +1,4 @@
+export type ResolvedRunAgentAttachment = {
+ mediaType: string;
+ url: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-run-agent-model-message.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-run-agent-model-message.util.spec.ts
new file mode 100644
index 00000000000..75bb5ecea22
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-run-agent-model-message.util.spec.ts
@@ -0,0 +1,72 @@
+import { type ResolvedRunAgentAttachment } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type';
+import { buildRunAgentModelMessageOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-run-agent-model-message.util';
+
+const FILE_ID = '6fdbd0ba-9a10-4b71-b0b7-2b1d64f8dc27';
+const FILE_URL = `https://twenty.test/file/agent-chat/${FILE_ID}?token=t`;
+
+const attachmentsByFileId = new Map<string, ResolvedRunAgentAttachment>([
+ [FILE_ID, { mediaType: 'image/png', url: FILE_URL }],
+]);
+
+describe('buildRunAgentModelMessageOrThrow', () => {
+ it('leaves a message without attachments as a plain string', () => {
+ expect(
+ buildRunAgentModelMessageOrThrow({
+ message: { role: 'assistant', content: 'hi' },
+ attachmentsByFileId,
+ }),
+ ).toEqual({ role: 'assistant', content: 'hi' });
+ });
+
+ it('turns an attachment into a file part carrying the stored media type', () => {
+ expect(
+ buildRunAgentModelMessageOrThrow({
+ message: {
+ role: 'user',
+ content: 'what is in this?',
+ attachments: [{ fileId: FILE_ID, filename: 'screenshot.png' }],
+ },
+ attachmentsByFileId,
+ }),
+ ).toEqual({
+ role: 'user',
+ content: [
+ { type: 'text', text: 'what is in this?' },
+ {
+ type: 'file',
+ data: FILE_URL,
+ mediaType: 'image/png',
+ filename: 'screenshot.png',
+ },
+ ],
+ });
+ });
+
+ it('omits the text part when an attachment arrives with no caption', () => {
+ const message = buildRunAgentModelMessageOrThrow({
+ message: {
+ role: 'user',
+ content: '',
+ attachments: [{ fileId: FILE_ID }],
+ },
+ attachmentsByFileId,
+ });
+
+ expect(message.content).toEqual([
+ expect.objectContaining({ type: 'file' }),
+ ]);
+ });
+
+ it('rejects an attachment it cannot resolve rather than answering without it', () => {
+ expect(() =>
+ buildRunAgentModelMessageOrThrow({
+ message: {
+ role: 'user',
+ content: 'hi',
+ attachments: [{ fileId: FILE_ID }],
+ },
+ attachmentsByFileId: new Map(),
+ }),
+ ).toThrow(FILE_ID);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/extract-run-agent-attachment-file-ids.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/extract-run-agent-attachment-file-ids.util.spec.ts
new file mode 100644
index 00000000000..39f12eb1986
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/extract-run-agent-attachment-file-ids.util.spec.ts
@@ -0,0 +1,86 @@
+import { type RunAgentMessage } from 'twenty-shared/application';
+
+import { MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const';
+import { MAX_RUN_AGENT_MESSAGE_ATTACHMENTS } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const';
+import { extractRunAgentAttachmentFileIdsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/extract-run-agent-attachment-file-ids.util';
+
+const FILE_ID = '6fdbd0ba-9a10-4b71-b0b7-2b1d64f8dc27';
+const OTHER_FILE_ID = 'c1d3f0a8-8f4e-4a3f-9a7d-0f1d2e3b4c5d';
+
+describe('extractRunAgentAttachmentFileIdsOrThrow', () => {
+ it('returns nothing for a conversation that carries no attachment', () => {
+ const messages: RunAgentMessage[] = [
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: 'hi' },
+ ];
+
+ expect(extractRunAgentAttachmentFileIdsOrThrow(messages)).toEqual([]);
+ });
+
+ it('lists each file once when a conversation reuses it', () => {
+ const messages: RunAgentMessage[] = [
+ { role: 'user', content: 'one', attachments: [{ fileId: FILE_ID }] },
+ { role: 'assistant', content: 'ok' },
+ {
+ role: 'user',
+ content: 'two',
+ attachments: [{ fileId: FILE_ID }, { fileId: OTHER_FILE_ID }],
+ },
+ ];
+
+ expect(extractRunAgentAttachmentFileIdsOrThrow(messages)).toEqual([
+ FILE_ID,
+ OTHER_FILE_ID,
+ ]);
+ });
+
+ it('rejects attachments on an assistant message', () => {
+ const messages: RunAgentMessage[] = [
+ {
+ role: 'assistant',
+ content: 'here you go',
+ attachments: [{ fileId: FILE_ID }],
+ },
+ ];
+
+ expect(() => extractRunAgentAttachmentFileIdsOrThrow(messages)).toThrow(
+ 'Only user messages can carry attachments',
+ );
+ });
+
+ it('rejects more attachments than a message may carry', () => {
+ const messages: RunAgentMessage[] = [
+ {
+ role: 'user',
+ content: 'hi',
+ attachments: Array.from(
+ { length: MAX_RUN_AGENT_MESSAGE_ATTACHMENTS + 1 },
+ () => ({ fileId: FILE_ID }),
+ ),
+ },
+ ];
+
+ expect(() => extractRunAgentAttachmentFileIdsOrThrow(messages)).toThrow(
+ `${MAX_RUN_AGENT_MESSAGE_ATTACHMENTS} allowed`,
+ );
+ });
+
+ it('rejects a filename longer than the cap', () => {
+ const messages: RunAgentMessage[] = [
+ {
+ role: 'user',
+ content: 'hi',
+ attachments: [
+ {
+ fileId: FILE_ID,
+ filename: 'a'.repeat(MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH + 1),
+ },
+ ],
+ },
+ ];
+
+ expect(() => extractRunAgentAttachmentFileIdsOrThrow(messages)).toThrow(
+ `${MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH} characters allowed`,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-run-agent-model-message.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-run-agent-model-message.util.ts
new file mode 100644
index 00000000000..6bfa9d860d2
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-run-agent-model-message.util.ts
@@ -0,0 +1,53 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type FilePart, type ModelMessage } from 'ai';
+import { type RunAgentMessage } from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type ResolvedRunAgentAttachment } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-run-agent-attachment.type';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+export const buildRunAgentModelMessageOrThrow = ({
+ message,
+ attachmentsByFileId,
+}: {
+ message: RunAgentMessage;
+ attachmentsByFileId: Map<string, ResolvedRunAgentAttachment>;
+}): ModelMessage => {
+ const attachments = message.attachments ?? [];
+
+ if (!isNonEmptyArray(attachments)) {
+ return { role: message.role, content: message.content };
+ }
+
+ const fileParts = attachments.map((attachment): FilePart => {
+ const resolvedAttachment = attachmentsByFileId.get(attachment.fileId);
+
+ if (!isDefined(resolvedAttachment)) {
+ throw new AiException(
+ `Attachment ${attachment.fileId} is not an uploaded ${FileFolder.AgentChat} file in this workspace`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ return {
+ type: 'file',
+ data: resolvedAttachment.url,
+ mediaType: resolvedAttachment.mediaType,
+ filename: attachment.filename,
+ };
+ });
+
+ return {
+ role: 'user',
+ content: [
+ ...(isNonEmptyString(message.content)
+ ? [{ type: 'text' as const, text: message.content }]
+ : []),
+ ...fileParts,
+ ],
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/extract-run-agent-attachment-file-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/extract-run-agent-attachment-file-ids.util.ts
new file mode 100644
index 00000000000..44d2fc5e83f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/extract-run-agent-attachment-file-ids.util.ts
@@ -0,0 +1,52 @@
+import { type RunAgentMessage } from 'twenty-shared/application';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-attachment-filename-length.const';
+import { MAX_RUN_AGENT_MESSAGE_ATTACHMENTS } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/max-run-agent-message-attachments.const';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+export const extractRunAgentAttachmentFileIdsOrThrow = (
+ messages: RunAgentMessage[],
+): string[] => {
+ for (const message of messages) {
+ const attachments = message.attachments ?? [];
+
+ if (message.role !== 'user' && isNonEmptyArray(attachments)) {
+ throw new AiException(
+ 'Only user messages can carry attachments',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ if (attachments.length > MAX_RUN_AGENT_MESSAGE_ATTACHMENTS) {
+ throw new AiException(
+ `A message carries ${attachments.length} attachments, more than the ${MAX_RUN_AGENT_MESSAGE_ATTACHMENTS} allowed`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ const overlongFilename = attachments.find(
+ (attachment) =>
+ (attachment.filename?.length ?? 0) >
+ MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH,
+ );
+
+ if (isDefined(overlongFilename)) {
+ throw new AiException(
+ `An attachment filename is longer than the ${MAX_RUN_AGENT_ATTACHMENT_FILENAME_LENGTH} characters allowed`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+ }
+
+ return [
+ ...new Set(
+ messages.flatMap((message) =>
+ (message.attachments ?? []).map((attachment) => attachment.fileId),
+ ),
+ ),
+ ];
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 4043e79ee1f..e7e0c35d3b5 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -178,6 +178,7 @@ export type {
RowLevelPermissionPredicateManifest,
RoleManifest,
} from './roleManifestType';
+export type { RunAgentMessageAttachment } from './runAgentMessageAttachmentType';
export type {
RunAgentMessageRole,
RunAgentMessage,
diff --git a/packages/twenty-shared/src/application/runAgentMessageAttachmentType.ts b/packages/twenty-shared/src/application/runAgentMessageAttachmentType.ts
new file mode 100644
index 00000000000..52f52adbf7b
--- /dev/null
+++ b/packages/twenty-shared/src/application/runAgentMessageAttachmentType.ts
@@ -0,0 +1,4 @@
+export type RunAgentMessageAttachment = {
+ fileId: string;
+ filename?: string;
+};
diff --git a/packages/twenty-shared/src/application/runAgentType.ts b/packages/twenty-shared/src/application/runAgentType.ts
index a8117101002..2622d20fd3a 100644
--- a/packages/twenty-shared/src/application/runAgentType.ts
+++ b/packages/twenty-shared/src/application/runAgentType.ts
@@ -1,8 +1,11 @@
+import { type RunAgentMessageAttachment } from './runAgentMessageAttachmentType';
+
export type RunAgentMessageRole = 'user' | 'assistant';
export type RunAgentMessage = {
role: RunAgentMessageRole;
content: string;
+ attachments?: RunAgentMessageAttachment[];
};
export type RunAgentInput = {