Skip to content

The open alternative to Salesforce, designed for AI.

[BREAKING_CHANGE] Let AI workflow steps run from their own config and permission scope (#29368)

Félix Malfait963c73a49ec9
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 67b66dccfa5..f6647f5b44e 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -80,6 +80,68 @@ When adding AI behavior:
- Avoid exposing raw IDs, timestamps, or nested API output to end users when a readable answer is possible.
- A `defineAgent` `roleUniversalIdentifier` must reference a role the app defines, and the application role (`defineApplicationRole` or `defaultRoleUniversalIdentifier`) must cover every permission that agent role grants. The build and `twenty app apply` fail otherwise, listing the excess grants.
+### Following An Agent Conversation
+
+`runAgent` (from `twenty-sdk/logic-function`) returns `{ threadId, runId, status, result, error, success }`; `runId` is the turn the call opens, which its messages carry as `turnId`. An app follows a conversation it holds with its agent through the chat's own API, named by the agent and the `thread` key it passes to `runAgent`:
+
+```ts
+import { listConversationMessages, streamConversation } from 'twenty-sdk/logic-function';
+
+const conversation = { agentUniversalIdentifier, threadKey: 'deal-42' };
+let maxCatchupSeq: number | undefined;
+
+// subscribe before reading the history, so nothing streamed in between is lost
+for await (const event of streamConversation({ ...conversation, signal })) {
+ if (event.type === 'keepalive' && maxCatchupSeq === undefined) {
+ const { messages, streamCatchup } = await listConversationMessages(conversation);
+ showMessages(messages);
+ for (const chunk of streamCatchup.chunks) showChunk(chunk);
+ maxCatchupSeq = streamCatchup.maxSeq;
+ }
+ if (event.type === 'stream-chunk' && (event.seq ?? 0) > (maxCatchupSeq ?? 0)) showChunk(event.chunk);
+}
+```
+
+- Events are the chat's `AgentChatSubscriptionEvent`s: `stream-chunk` (an AI SDK `UIMessageChunk` with a `seq`), notifications such as `message-persisted`, `queue-updated` and `stream-error`, and a periodic `keepalive`. Pipe chunks into `readUIMessageStream()` from `ai` to build messages as the chat does.
+- Messages come as AI SDK `UIMessage`s, as the chat builds them, with the run in `metadata.turnId`. `streamCatchup` holds the chunks of a reply still streaming: show them, then skip live chunks whose `seq` is at most `streamCatchup.maxSeq`.
+- The first event once connected is a `keepalive`: read the history then. The stream stays open until `signal` aborts or the loop breaks, and throws if the connection drops; stream again to resume. It can start before the first run reaches the conversation.
+- Both need an application token and reach only the app's own conversations. Turns a member opened elsewhere, such as in the chat, show only their text, in the history, live and in the agent's next run, where their other chunks arrive as empty `message-metadata` chunks so `seq` stays gapless. Turns the app ran as a member stay whole when the app reads on its own. Requires `"engines": { "twenty": ">=2.56.0" }`.
+
+## AI Generate
+
+`ai.generate` calls a model with no agent and no conversation. Import it from `twenty-sdk/logic-function`.
+
+```ts
+import { ai } from 'twenty-sdk/logic-function';
+
+const { success, text, error } = await ai.generate({
+ input: 'Is Acme a good fit for us?', // or RunAgentMessage[] ({ role, content })
+ instructions: 'Qualify leads for Twenty in one sentence.',
+});
+```
+
+For JSON, pass a `responseFormat`: the schema goes on the model request itself, so the answer takes one request (plus tool steps when a `scope` grants tools), and comes back in `object`:
+
+```ts
+const { object } = await ai.generate({
+ input: 'Is Acme a good fit for us?',
+ responseFormat: {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { fit: { type: 'boolean' }, reason: { type: 'string' } },
+ },
+ },
+});
+```
+
+- Without a `scope` the model gets no data tools. A `scope` (`AiRunScope`, e.g. `objectPermissions`) grants tools on those objects, and can only narrow what the caller may already reach.
+- The call runs as the caller (the member a user-scoped token belongs to, else the app, else the API key) and never exceeds the app's role. From a logic function it follows the default clients: the person who triggered the run, within the app's role, or the app when nobody did. The app needs a default role with the AI permission flag.
+- `modelId` is optional; the workspace default model is used when unset.
+- It returns `{ success, text, object, error, runId, usage }`: `text` for a text response, `object` for a JSON one (the other is `null`), `error` when `success` is false, `runId` for the recorded run and `usage` as `{ inputTokens, outputTokens }`, which counts the steps that finished before a failure too. A run that fails comes back as `success: false` rather than a throw (a call that cannot start a run, such as invalid input, still throws), so check `success`.
+- To stream the reply, pass `onChunk` (and optionally `signal`): the SDK subscribes to the run first, waits until the subscription is live, then starts it, hands each AI SDK `UIMessageChunk` to `onChunk`, and resolves with the same result once the last chunk is delivered. If the stream's end never arrives, it stops reading after 5 s without a new chunk once the result is in, then still delivers every chunk already received; once the stream is live, a failure of it only stops the chunks, and the call still resolves with the billed result. The call rejects when the subscription fails before it goes live, so the run never starts, or when `onChunk` throws. Aborting `signal` rejects the call and closes the stream; the run itself goes on.
+- An app follows only its own runs, so `onChunk` needs an app token. Requires `"engines": { "twenty": ">=2.56.0" }`.
+
## Inbox Messages
`sendInboxMessage` posts a message from the app in the chats of one or more workspace members. Import it from `twenty-sdk/logic-function` in a logic function and from `twenty-sdk/front-component` in a front component; the inbox helpers are the same in both.
diff --git a/packages/twenty-agent-skills/references/develop-app/workflows.md b/packages/twenty-agent-skills/references/develop-app/workflows.md
index 78ddd3ed080..604ace15fc9 100644
--- a/packages/twenty-agent-skills/references/develop-app/workflows.md
+++ b/packages/twenty-agent-skills/references/develop-app/workflows.md
@@ -22,8 +22,12 @@ Workflows created at runtime through the workspace API are a `Workflow` plus at
## AI Agent Steps
-- `AI_AGENT` runs one of the app's agents, named with `agentUniversalIdentifier`, and takes the step's `prompt`, `responseFormat`, `humanInputInstructions`, `conversation` and `workspaceMemberId` (the member the agent's conversation is with).
-- A step can only name an agent the app exports: `twenty app pull` reports a workflow on any other agent as unsupported.
+- `AI_AGENT` is one of two kinds. Never mix them: an agent brings its own instructions, model and permissions.
+ - Generate step: no agent. It carries its own `instructions`, `modelId`, `modelConfiguration` and `scope` and runs once, with no conversation, no human input and no waiting.
+ - Agent step: runs one of the app's agents, named with `agentUniversalIdentifier`. Only this kind takes `humanInputInstructions` and `conversation`; a Generate step with either fails validation.
+- Both kinds take the step's `prompt`, `responseFormat` and `workspaceMemberId` (the member the agent's conversation is with).
+- `scope` is what the step's AI may reach on top of the permissions of whoever runs the workflow: a role's permissions (`canReadAllObjectRecords`, `objectPermissions`, `fieldPermissions`, `permissionFlagUniversalIdentifiers`, ...) without its identity or row-level predicates. It resolves like a role whose all-records flags default to off: object actions and permission flags it doesn't grant are denied, system objects stay readable unless it grants more, and unlisted fields follow their object. A Generate step without a `scope` gets no data tools; an Agent step runs with its agent's role.
+- A step can only name an agent the app exports. `twenty app pull` reports as unsupported a workflow on any other agent, or with a stored step that has human input instructions or a conversation but no agent.
## Email and Calendar Steps
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 8d47ddc4577..d354a628930 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -91,7 +91,7 @@ enum AgentChatChannelThreadStatus {
type AgentChatEvent {
event: JSON!
- threadId: String!
+ threadId: String
}
enum AgentChatInboxAction {
@@ -215,7 +215,7 @@ type AgentRun {
reply: String
startedAt: DateTime
status: AgentTurnStatus!
- threadId: UUID!
+ threadId: UUID
threadTitle: String
toolNames: [String!]!
}
@@ -286,6 +286,11 @@ enum AiModelTier {
smart
}
+type AiRunUsage {
+ inputTokens: Int!
+ outputTokens: Int!
+}
+
type AiSystemPromptPreview {
estimatedTokenCount: Int!
sections: [AiSystemPromptSection!]!
@@ -2577,6 +2582,24 @@ type FullName {
lastName: String!
}
+input GenerateInput {
+ input: [RunAgentMessageInput!]!
+ instructions: String
+ modelId: String
+ responseFormat: JSON
+ runId: UUID
+ scope: JSON
+}
+
+type GenerateResult {
+ error: String
+ object: JSON
+ runId: UUID!
+ success: Boolean!
+ text: String
+ usage: AiRunUsage!
+}
+
input GetApiKeyInput {
id: UUID!
}
@@ -3429,6 +3452,7 @@ type Mutation {
enqueueJobs(input: EnqueueJobsInput!): EnqueueJobsResult!
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult!
executeOneLogicFunction(input: ExecuteOneLogicFunctionInput!): LogicFunctionExecutionResult!
+ generate(input: GenerateInput!): GenerateResult!
generateApiKeyToken(apiKeyId: UUID!, expiresAt: String!): ApiKeyToken!
generateFrontComponentApplicationTokenPair(applicationId: UUID!): ApplicationTokenPair!
generatePlaygroundToken: AuthToken!
@@ -4121,8 +4145,8 @@ type Query {
billingPlans: [BillingPlan!]!
billingPortalSession(forPaymentMethodUpdate: Boolean, returnUrlPath: String): BillingSession!
callRecordingIdForCalendarEvent(calendarEventId: UUID!): UUID
- chatMessages(threadId: UUID!): [AgentMessage!]!
- chatStreamCatchupChunks(threadId: UUID!): ChatStreamCatchupChunks!
+ chatMessages(agentUniversalIdentifier: UUID, threadId: UUID, threadKey: String): [AgentMessage!]!
+ chatStreamCatchupChunks(agentUniversalIdentifier: UUID, threadId: UUID, threadKey: String): ChatStreamCatchupChunks!
chatThread(id: UUID!): AgentChatThread!
checkUserExists(captchaToken: String, email: String!): CheckUserExist!
checkWorkspaceInviteHashIsValid(inviteHash: String!): WorkspaceInviteHashValid!
@@ -4552,6 +4576,7 @@ enum RunAgentMessageRole {
type RunAgentResult {
error: String
result: JSON
+ runId: UUID!
status: String!
success: Boolean!
threadId: UUID!
@@ -4799,7 +4824,7 @@ type Subscription {
eventLogsLive(fieldFilters: [EventLogFieldFilterInput!], table: EventLogTable!): [EventLogRecord!]
exportRecords(input: CreateRecordExportInput!): RecordExport!
logicFunctionLogs(input: LogicFunctionLogsInput!): LogicFunctionLogs!
- onAgentChatEvent(threadId: UUID!): AgentChatEvent!
+ onAgentChatEvent(agentUniversalIdentifier: UUID, runId: UUID, threadId: UUID, threadKey: String): AgentChatEvent!
onEventSubscription(eventStreamId: String!): EventSubscription
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index f656cd89560..d5feda5e126 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -88,7 +88,7 @@ export type AgentChatChannelThreadStatus = 'DONE' | 'OPEN' | 'SNOOZED'
export interface AgentChatEvent {
event: Scalars['JSON']
- threadId: Scalars['String']
+ threadId?: Scalars['String']
__typename: 'AgentChatEvent'
}
@@ -206,7 +206,7 @@ export interface AgentRun {
reply?: Scalars['String']
startedAt?: Scalars['DateTime']
status: AgentTurnStatus
- threadId: Scalars['UUID']
+ threadId?: Scalars['UUID']
threadTitle?: Scalars['String']
toolNames: Scalars['String'][]
__typename: 'AgentRun'
@@ -252,6 +252,12 @@ export interface AiChatUserCreditsUsage {
export type AiModelTier = 'balanced' | 'extraFast' | 'extraSmart' | 'fast' | 'smart'
+export interface AiRunUsage {
+ inputTokens: Scalars['Int']
+ outputTokens: Scalars['Int']
+ __typename: 'AiRunUsage'
+}
+
export interface AiSystemPromptPreview {
estimatedTokenCount: Scalars['Int']
sections: AiSystemPromptSection[]
@@ -1711,6 +1717,16 @@ export interface FullName {
__typename: 'FullName'
}
+export interface GenerateResult {
+ error?: Scalars['String']
+ object?: Scalars['JSON']
+ runId: Scalars['UUID']
+ success: Scalars['Boolean']
+ text?: Scalars['String']
+ usage: AiRunUsage
+ __typename: 'GenerateResult'
+}
+
export interface GetAuthorizationUrlForSSO {
authorizationURL: Scalars['String']
id: Scalars['UUID']
@@ -2422,6 +2438,7 @@ export interface Mutation {
enqueueJobs: EnqueueJobsResult
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult
executeOneLogicFunction: LogicFunctionExecutionResult
+ generate: GenerateResult
generateApiKeyToken: ApiKeyToken
generateFrontComponentApplicationTokenPair: ApplicationTokenPair
generatePlaygroundToken: AuthToken
@@ -3364,6 +3381,7 @@ export type RunAgentMessageRole = 'assistant' | 'user'
export interface RunAgentResult {
error?: Scalars['String']
result?: Scalars['JSON']
+ runId: Scalars['UUID']
status: Scalars['String']
success: Scalars['Boolean']
threadId: Scalars['UUID']
@@ -4545,6 +4563,13 @@ export interface AiChatUserCreditsUsageGenqlSelection{
__scalar?: boolean | number
}
+export interface AiRunUsageGenqlSelection{
+ inputTokens?: boolean | number
+ outputTokens?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface AiSystemPromptPreviewGenqlSelection{
estimatedTokenCount?: boolean | number
sections?: AiSystemPromptSectionGenqlSelection
@@ -6270,6 +6295,19 @@ export interface FullNameGenqlSelection{
__scalar?: boolean | number
}
+export interface GenerateInput {input: RunAgentMessageInput[],instructions?: (Scalars['String'] | null),modelId?: (Scalars['String'] | null),responseFormat?: (Scalars['JSON'] | null),runId?: (Scalars['UUID'] | null),scope?: (Scalars['JSON'] | null)}
+
+export interface GenerateResultGenqlSelection{
+ error?: boolean | number
+ object?: boolean | number
+ runId?: boolean | number
+ success?: boolean | number
+ text?: boolean | number
+ usage?: AiRunUsageGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface GetApiKeyInput {id: Scalars['UUID']}
export interface GetAuthorizationUrlForSSOGenqlSelection{
@@ -7006,6 +7044,7 @@ export interface MutationGenqlSelection{
enqueueJobs?: (EnqueueJobsResultGenqlSelection & { __args: {input: EnqueueJobsInput} })
enrichWorkspaceCompany?: WorkspaceCompanyEnrichmentResultGenqlSelection
executeOneLogicFunction?: (LogicFunctionExecutionResultGenqlSelection & { __args: {input: ExecuteOneLogicFunctionInput} })
+ generate?: (GenerateResultGenqlSelection & { __args: {input: GenerateInput} })
generateApiKeyToken?: (ApiKeyTokenGenqlSelection & { __args: {apiKeyId: Scalars['UUID'], expiresAt: Scalars['String']} })
generateFrontComponentApplicationTokenPair?: (ApplicationTokenPairGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
generatePlaygroundToken?: AuthTokenGenqlSelection
@@ -7661,8 +7700,8 @@ export interface QueryGenqlSelection{
billingPlans?: BillingPlanGenqlSelection
billingPortalSession?: (BillingSessionGenqlSelection & { __args?: {forPaymentMethodUpdate?: (Scalars['Boolean'] | null), returnUrlPath?: (Scalars['String'] | null)} })
callRecordingIdForCalendarEvent?: { __args: {calendarEventId: Scalars['UUID']} }
- chatMessages?: (AgentMessageGenqlSelection & { __args: {threadId: Scalars['UUID']} })
- chatStreamCatchupChunks?: (ChatStreamCatchupChunksGenqlSelection & { __args: {threadId: Scalars['UUID']} })
+ chatMessages?: (AgentMessageGenqlSelection & { __args?: {agentUniversalIdentifier?: (Scalars['UUID'] | null), threadId?: (Scalars['UUID'] | null), threadKey?: (Scalars['String'] | null)} })
+ chatStreamCatchupChunks?: (ChatStreamCatchupChunksGenqlSelection & { __args?: {agentUniversalIdentifier?: (Scalars['UUID'] | null), threadId?: (Scalars['UUID'] | null), threadKey?: (Scalars['String'] | null)} })
chatThread?: (AgentChatThreadGenqlSelection & { __args: {id: Scalars['UUID']} })
checkUserExists?: (CheckUserExistGenqlSelection & { __args: {captchaToken?: (Scalars['String'] | null), email: Scalars['String']} })
checkWorkspaceInviteHashIsValid?: (WorkspaceInviteHashValidGenqlSelection & { __args: {inviteHash: Scalars['String']} })
@@ -8023,6 +8062,7 @@ export interface RunAgentMessageInput {attachments?: (RunAgentMessageAttachmentI
export interface RunAgentResultGenqlSelection{
error?: boolean | number
result?: boolean | number
+ runId?: boolean | number
status?: boolean | number
success?: boolean | number
threadId?: boolean | number
@@ -8238,7 +8278,7 @@ export interface SubscriptionGenqlSelection{
eventLogsLive?: (EventLogRecordGenqlSelection & { __args: {fieldFilters?: (EventLogFieldFilterInput[] | null), table: EventLogTable} })
exportRecords?: (RecordExportGenqlSelection & { __args: {input: CreateRecordExportInput} })
logicFunctionLogs?: (LogicFunctionLogsGenqlSelection & { __args: {input: LogicFunctionLogsInput} })
- onAgentChatEvent?: (AgentChatEventGenqlSelection & { __args: {threadId: Scalars['UUID']} })
+ onAgentChatEvent?: (AgentChatEventGenqlSelection & { __args?: {agentUniversalIdentifier?: (Scalars['UUID'] | null), runId?: (Scalars['UUID'] | null), threadId?: (Scalars['UUID'] | null), threadKey?: (Scalars['String'] | null)} })
onEventSubscription?: (EventSubscriptionGenqlSelection & { __args: {eventStreamId: Scalars['String']} })
__typename?: boolean | number
__scalar?: boolean | number
@@ -9413,6 +9453,14 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const AiRunUsage_possibleTypes: string[] = ['AiRunUsage']
+ export const isAiRunUsage = (obj?: { __typename?: any } | null): obj is AiRunUsage => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isAiRunUsage"')
+ return AiRunUsage_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const AiSystemPromptPreview_possibleTypes: string[] = ['AiSystemPromptPreview']
export const isAiSystemPromptPreview = (obj?: { __typename?: any } | null): obj is AiSystemPromptPreview => {
if (!obj?.__typename) throw new Error('__typename is missing in "isAiSystemPromptPreview"')
@@ -10557,6 +10605,14 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const GenerateResult_possibleTypes: string[] = ['GenerateResult']
+ export const isGenerateResult = (obj?: { __typename?: any } | null): obj is GenerateResult => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isGenerateResult"')
+ return GenerateResult_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const GetAuthorizationUrlForSSO_possibleTypes: string[] = ['GetAuthorizationUrlForSSO']
export const isGetAuthorizationUrlForSSO = (obj?: { __typename?: any } | null): obj is GetAuthorizationUrlForSSO => {
if (!obj?.__typename) throw new Error('__typename is missing in "isGetAuthorizationUrlForSSO"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 72cc7effba9..e3c88b4477d 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -13,116 +13,116 @@ export default {
27,
28,
31,
- 34,
- 36,
- 43,
- 56,
- 64,
- 74,
- 80,
- 92,
- 96,
+ 35,
+ 37,
+ 44,
+ 57,
+ 65,
+ 75,
+ 81,
+ 93,
97,
- 99,
- 104,
- 109,
- 115,
- 120,
- 126,
- 129,
+ 98,
+ 100,
+ 105,
+ 110,
+ 116,
+ 121,
+ 127,
130,
131,
132,
- 140,
- 142,
- 156,
- 160,
- 162,
- 164,
- 211,
+ 133,
+ 141,
+ 143,
+ 157,
+ 161,
+ 163,
+ 165,
212,
- 239,
- 243,
+ 213,
+ 240,
244,
- 246,
- 256,
- 262,
- 266,
- 270,
- 273,
- 280,
- 295,
- 297,
- 303,
- 305,
- 317,
- 324,
- 325,
- 326,
- 338,
- 340,
- 356,
- 357,
- 358,
+ 245,
+ 247,
+ 257,
+ 263,
+ 267,
+ 271,
+ 274,
+ 281,
+ 298,
+ 300,
+ 306,
+ 308,
+ 320,
+ 327,
+ 328,
+ 329,
+ 341,
+ 343,
359,
360,
361,
+ 362,
363,
364,
- 365,
+ 366,
+ 367,
368,
- 369,
371,
+ 372,
374,
- 379,
- 383,
- 392,
- 399,
- 400,
+ 377,
+ 382,
+ 386,
+ 395,
+ 402,
403,
- 407,
- 408,
- 413,
- 417,
- 440,
- 442,
+ 406,
+ 410,
+ 411,
+ 416,
+ 420,
443,
- 451,
- 463,
- 465,
- 469,
- 474,
- 494,
- 506,
- 507,
+ 445,
+ 446,
+ 454,
+ 466,
+ 468,
+ 472,
+ 477,
+ 497,
509,
- 534,
- 536,
- 538,
- 603,
- 623,
- 630,
- 632,
- 636,
- 647,
- 653,
- 654,
+ 510,
+ 512,
+ 537,
+ 539,
+ 541,
+ 606,
+ 626,
+ 633,
+ 635,
+ 639,
+ 650,
656,
657,
659,
660,
- 661,
+ 662,
+ 663,
664,
- 665,
- 666,
- 671,
- 673,
+ 667,
+ 668,
+ 669,
+ 674,
676,
- 681,
- 682,
- 683,
+ 679,
+ 684,
+ 685,
686,
- 687
+ 689,
+ 690
],
"types": {
"ActivateWorkspaceInput": {
@@ -139,7 +139,7 @@ export default {
1
],
"operationSignature": [
- 324
+ 327
],
"queryId": [
1
@@ -150,10 +150,10 @@ export default {
},
"Agent": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"description": [
1
@@ -162,7 +162,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -177,7 +177,7 @@ export default {
1
],
"modelConfiguration": [
- 324
+ 327
],
"modelId": [
1
@@ -189,16 +189,16 @@ export default {
1
],
"responseFormat": [
- 324
+ 327
],
"roleId": [
- 534
+ 537
],
"triggers": [
- 324
+ 327
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -207,7 +207,7 @@ export default {
"Boolean": {},
"AgentChatChannel": {
"applicationId": [
- 534
+ 537
],
"color": [
1
@@ -216,7 +216,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isAccessible": [
4
@@ -231,7 +231,7 @@ export default {
6
],
"roleIds": [
- 534
+ 537
],
"__typename": [
1
@@ -247,7 +247,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"label": [
1
@@ -264,7 +264,7 @@ export default {
10
],
"channelId": [
- 534
+ 537
],
"doneCount": [
10
@@ -304,7 +304,7 @@ export default {
4
],
"threadIds": [
- 534
+ 537
],
"__typename": [
1
@@ -313,7 +313,7 @@ export default {
"AgentChatChannelThreadStatus": {},
"AgentChatEvent": {
"event": [
- 324
+ 327
],
"threadId": [
1
@@ -366,10 +366,10 @@ export default {
10
],
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"id": [
18
@@ -393,7 +393,7 @@ export default {
10
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -402,31 +402,31 @@ export default {
"ID": {},
"AgentChatThreadParticipant": {
"archivedAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"isSubscribed": [
4
],
"lastMentionedAt": [
- 212
+ 213
],
"lastReadAt": [
- 212
+ 213
],
"mentionsResolvedAt": [
- 212
+ 213
],
"snoozedUntil": [
- 212
+ 213
],
"threadId": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -434,7 +434,7 @@ export default {
},
"AgentIdInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -442,19 +442,19 @@ export default {
},
"AgentMessage": {
"agentId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"parts": [
22
],
"processedAt": [
- 212
+ 213
],
"reactions": [
23
@@ -463,19 +463,19 @@ export default {
1
],
"senderUserWorkspaceId": [
- 534
+ 537
],
"senderWorkspaceMemberId": [
- 534
+ 537
],
"status": [
1
],
"threadId": [
- 534
+ 537
],
"turnId": [
- 534
+ 537
],
"__typename": [
1
@@ -483,7 +483,7 @@ export default {
},
"AgentMessagePart": {
"createdAt": [
- 212
+ 213
],
"errorMessage": [
1
@@ -492,7 +492,7 @@ export default {
1
],
"fileId": [
- 534
+ 537
],
"fileMediaType": [
1
@@ -501,10 +501,10 @@ export default {
1
],
"id": [
- 534
+ 537
],
"messageId": [
- 534
+ 537
],
"orderIndex": [
10
@@ -513,7 +513,7 @@ export default {
4
],
"providerMetadata": [
- 324
+ 327
],
"reasoningContent": [
1
@@ -549,13 +549,13 @@ export default {
1
],
"toolInput": [
- 324
+ 327
],
"toolName": [
1
],
"toolOutput": [
- 324
+ 327
],
"type": [
1
@@ -566,7 +566,7 @@ export default {
},
"AgentMessageReactionSummary": {
"agentIds": [
- 534
+ 537
],
"emoji": [
1
@@ -575,7 +575,7 @@ export default {
4
],
"workspaceMemberIds": [
- 534
+ 537
],
"__typename": [
1
@@ -583,7 +583,7 @@ export default {
},
"AgentRun": {
"createdAt": [
- 212
+ 213
],
"creatorName": [
1
@@ -595,13 +595,13 @@ export default {
6
],
"endedAt": [
- 212
+ 213
],
"errorMessage": [
1
],
"id": [
- 534
+ 537
],
"input": [
1
@@ -619,13 +619,13 @@ export default {
1
],
"startedAt": [
- 212
+ 213
],
"status": [
25
],
"threadId": [
- 534
+ 537
],
"threadTitle": [
1
@@ -640,13 +640,13 @@ export default {
"AgentTurnStatus": {},
"AggregateChartConfiguration": {
"aggregateFieldMetadataId": [
- 534
+ 537
],
"aggregateOperation": [
27
],
"configurationType": [
- 664
+ 667
],
"description": [
1
@@ -655,7 +655,7 @@ export default {
4
],
"filter": [
- 324
+ 327
],
"firstDayOfTheWeek": [
10
@@ -664,13 +664,13 @@ export default {
1
],
"numberFormat": [
- 142
+ 143
],
"prefix": [
1
],
"ratioAggregateConfig": [
- 435
+ 438
],
"suffix": [
1
@@ -686,16 +686,16 @@ export default {
"AiChatAssistantMode": {},
"AiChatUsage": {
"consumedValue": [
- 99
+ 100
],
"kind": [
1
],
"limitValue": [
- 99
+ 100
],
"periodEnd": [
- 212
+ 213
],
"__typename": [
1
@@ -703,25 +703,36 @@ export default {
},
"AiChatUserCreditsUsage": {
"consumedValue": [
- 99
+ 100
],
"limitValue": [
- 99
+ 100
],
"periodEnd": [
- 212
+ 213
],
"__typename": [
1
]
},
"AiModelTier": {},
+ "AiRunUsage": {
+ "inputTokens": [
+ 10
+ ],
+ "outputTokens": [
+ 10
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"AiSystemPromptPreview": {
"estimatedTokenCount": [
10
],
"sections": [
- 33
+ 34
],
"__typename": [
1
@@ -761,25 +772,25 @@ export default {
},
"ApiKey": {
"createdAt": [
- 212
+ 213
],
"expiresAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"name": [
1
],
"revokedAt": [
- 212
+ 213
],
"role": [
- 457
+ 460
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -787,16 +798,16 @@ export default {
},
"ApiKeyForRole": {
"expiresAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"name": [
1
],
"revokedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -839,7 +850,7 @@ export default {
1
],
"scope": [
- 160
+ 161
],
"scopes": [
1
@@ -862,10 +873,10 @@ export default {
1
],
"scope": [
- 43
+ 44
],
"value": [
- 324
+ 327
],
"__typename": [
1
@@ -894,10 +905,10 @@ export default {
1
],
"participants": [
- 46
+ 47
],
"receivedAt": [
- 212
+ 213
],
"subject": [
1
@@ -920,13 +931,13 @@ export default {
1
],
"personId": [
- 534
+ 537
],
"role": [
- 365
+ 368
],
"workspaceMemberId": [
- 534
+ 537
],
"__typename": [
1
@@ -937,31 +948,31 @@ export default {
3
],
"applicationRegistration": [
- 76
+ 77
],
"applicationRegistrationId": [
- 534
+ 537
],
"applicationVariables": [
- 79
+ 80
],
"autoUpgrade": [
4
],
"availablePackages": [
- 324
+ 327
],
"canBeUninstalled": [
4
],
"commandMenuItems": [
- 155
+ 156
],
"createdAt": [
- 212
+ 213
],
"defaultLogicFunctionRole": [
- 457
+ 460
],
"defaultRoleId": [
1
@@ -970,22 +981,22 @@ export default {
1
],
"frontComponents": [
- 287
+ 288
],
"healthCheckLogicFunctionId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"isUninstallBlockedByOtherWorkspaceInstallations": [
4
],
"logicFunctions": [
- 337
+ 340
],
"logoFileId": [
- 534
+ 537
],
"logoUrl": [
1
@@ -994,22 +1005,22 @@ export default {
1
],
"objects": [
- 385
+ 388
],
"packageJsonChecksum": [
1
],
"packageJsonFileId": [
- 534
+ 537
],
"runOnUserPreferences": [
4
],
"settingsCustomTabFrontComponentId": [
- 534
+ 537
],
"settingsMenuItems": [
- 493
+ 496
],
"universalIdentifier": [
1
@@ -1021,7 +1032,7 @@ export default {
1
],
"yarnLockFileId": [
- 534
+ 537
],
"__typename": [
1
@@ -1029,7 +1040,7 @@ export default {
},
"ApplicationAuthorization": {
"applicationId": [
- 534
+ 537
],
"applicationName": [
1
@@ -1038,22 +1049,22 @@ export default {
1
],
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"lastAuthorizedAt": [
- 212
+ 213
],
"lastUsedAt": [
- 212
+ 213
],
"scopes": [
1
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -1064,7 +1075,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -1072,25 +1083,25 @@ export default {
},
"ApplicationConnectedAccountDTO": {
"applicationId": [
- 534
+ 537
],
"archivedAt": [
- 212
+ 213
],
"authFailedAt": [
- 212
+ 213
],
"authFailedReason": [
1
],
"connectionParameters": [
- 431
+ 434
],
"connectionProviderId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"handle": [
1
@@ -1099,16 +1110,16 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isOwnedByCurrentUser": [
4
],
"lastCredentialsRefreshedAt": [
- 212
+ 213
],
"lastSignedInAt": [
- 212
+ 213
],
"name": [
1
@@ -1117,16 +1128,16 @@ export default {
1
],
"scope": [
- 160
+ 161
],
"scopes": [
1
],
"updatedAt": [
- 212
+ 213
],
"userWorkspaceId": [
- 534
+ 537
],
"visibility": [
1
@@ -1143,7 +1154,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"logoUrl": [
1
@@ -1152,10 +1163,10 @@ export default {
1
],
"oauth": [
- 52
+ 53
],
"scope": [
- 164
+ 165
],
"type": [
1
@@ -1177,16 +1188,16 @@ export default {
},
"ApplicationExport": {
"application": [
- 54
+ 55
],
"coverage": [
- 55
+ 56
],
"files": [
- 57
+ 58
],
"manifest": [
- 324
+ 327
],
"__typename": [
1
@@ -1197,7 +1208,7 @@ export default {
1
],
"sourceType": [
- 74
+ 75
],
"universalIdentifier": [
1
@@ -1214,7 +1225,7 @@ export default {
1
],
"status": [
- 56
+ 57
],
"universalIdentifier": [
1
@@ -1240,7 +1251,7 @@ export default {
},
"ApplicationFileCompletionError": {
"fileId": [
- 534
+ 537
],
"message": [
1
@@ -1251,7 +1262,7 @@ export default {
},
"ApplicationFileUploadError": {
"fileFolder": [
- 280
+ 281
],
"filePath": [
1
@@ -1265,7 +1276,7 @@ export default {
},
"ApplicationFileUploadRequestInput": {
"fileFolder": [
- 280
+ 281
],
"filePath": [
1
@@ -1282,13 +1293,13 @@ export default {
1
],
"expiresAt": [
- 212
+ 213
],
"fileFolder": [
- 280
+ 281
],
"fileId": [
- 534
+ 537
],
"filePath": [
1
@@ -1313,13 +1324,13 @@ export default {
},
"ApplicationHealthCheckResult": {
"action": [
- 62
+ 63
],
"description": [
1
],
"status": [
- 64
+ 65
],
"title": [
1
@@ -1331,13 +1342,13 @@ export default {
"ApplicationHealthStatus": {},
"ApplicationMonitoring": {
"activity": [
- 66
+ 67
],
"bucketSizeInSeconds": [
10
],
"creditUsage": [
- 67
+ 68
],
"creditsUsed": [
6
@@ -1346,13 +1357,13 @@ export default {
10
],
"functions": [
- 68
+ 69
],
"issues": [
- 69
+ 70
],
"lifecycle": [
- 70
+ 71
],
"lifecycleFailureCount": [
10
@@ -1361,10 +1372,10 @@ export default {
10
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"rateLimitEventCount": [
10
@@ -1373,7 +1384,7 @@ export default {
10
],
"versions": [
- 71
+ 72
],
"__typename": [
1
@@ -1381,7 +1392,7 @@ export default {
},
"ApplicationMonitoringActivityBucket": {
"bucketStart": [
- 212
+ 213
],
"errorCount": [
10
@@ -1398,7 +1409,7 @@ export default {
},
"ApplicationMonitoringCreditBucket": {
"bucketStart": [
- 212
+ 213
],
"creditsUsed": [
6
@@ -1441,7 +1452,7 @@ export default {
10
],
"lastSeenAt": [
- 212
+ 213
],
"level": [
1
@@ -1461,7 +1472,7 @@ export default {
},
"ApplicationMonitoringLifecycleBucket": {
"bucketStart": [
- 212
+ 213
],
"failedCount": [
10
@@ -1498,19 +1509,19 @@ export default {
},
"ApplicationPreferences": {
"applicationId": [
- 534
+ 537
],
"connectionProviders": [
- 51
+ 52
],
"hasUserHealthCheck": [
4
],
"settingsMenuItems": [
- 493
+ 496
],
"variables": [
- 635
+ 638
],
"__typename": [
1
@@ -1518,13 +1529,13 @@ export default {
},
"ApplicationRegistration": {
"createdAt": [
- 212
+ 213
],
"galleryImagesUrls": [
1
],
"id": [
- 534
+ 537
],
"isConfigured": [
4
@@ -1554,19 +1565,19 @@ export default {
1
],
"ownerWorkspaceId": [
- 534
+ 537
],
"sourcePackage": [
1
],
"sourceType": [
- 74
+ 75
],
"universalIdentifier": [
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -1581,7 +1592,7 @@ export default {
10
],
"creditsUsedBreakdown": [
- 209
+ 210
],
"mostInstalledVersion": [
1
@@ -1593,7 +1604,7 @@ export default {
6
],
"versionDistribution": [
- 645
+ 648
],
"__typename": [
1
@@ -1601,7 +1612,7 @@ export default {
},
"ApplicationRegistrationSummary": {
"id": [
- 534
+ 537
],
"latestAvailableVersion": [
1
@@ -1610,7 +1621,7 @@ export default {
1
],
"sourceType": [
- 74
+ 75
],
"__typename": [
1
@@ -1618,13 +1629,13 @@ export default {
},
"ApplicationRegistrationVariable": {
"createdAt": [
- 212
+ 213
],
"description": [
1
],
"id": [
- 534
+ 537
],
"isDeprecated": [
4
@@ -1642,13 +1653,13 @@ export default {
1
],
"options": [
- 324
+ 327
],
"type": [
1
],
"updatedAt": [
- 212
+ 213
],
"value": [
1
@@ -1659,10 +1670,10 @@ export default {
},
"ApplicationTokenPair": {
"applicationAccessToken": [
- 84
+ 85
],
"applicationRefreshToken": [
- 84
+ 85
],
"__typename": [
1
@@ -1673,7 +1684,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isDeprecated": [
4
@@ -1691,10 +1702,10 @@ export default {
1
],
"options": [
- 324
+ 327
],
"scope": [
- 80
+ 81
],
"type": [
1
@@ -1709,13 +1720,13 @@ export default {
"ApplicationVariableScope": {},
"ApprovedAccessDomain": {
"createdAt": [
- 212
+ 213
],
"domain": [
1
],
"id": [
- 534
+ 537
],
"isValidated": [
4
@@ -1752,7 +1763,7 @@ export default {
4
],
"sso": [
- 473
+ 476
],
"__typename": [
1
@@ -1760,7 +1771,7 @@ export default {
},
"AuthToken": {
"expiresAt": [
- 212
+ 213
],
"token": [
1
@@ -1771,10 +1782,10 @@ export default {
},
"AuthTokenPair": {
"accessOrWorkspaceAgnosticToken": [
- 84
+ 85
],
"refreshToken": [
- 84
+ 85
],
"__typename": [
1
@@ -1782,7 +1793,7 @@ export default {
},
"AuthTokens": {
"tokens": [
- 85
+ 86
],
"__typename": [
1
@@ -1812,7 +1823,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"inviteHash": [
1
@@ -1827,10 +1838,10 @@ export default {
1
],
"sso": [
- 472
+ 475
],
"workspaceUrls": [
- 688
+ 691
],
"__typename": [
1
@@ -1838,10 +1849,10 @@ export default {
},
"AvailableWorkspaces": {
"availableWorkspacesForSignIn": [
- 89
+ 90
],
"availableWorkspacesForSignUp": [
- 89
+ 90
],
"__typename": [
1
@@ -1849,10 +1860,10 @@ export default {
},
"AvailableWorkspacesAndAccessTokens": {
"availableWorkspaces": [
- 90
+ 91
],
"tokens": [
- 85
+ 86
],
"__typename": [
1
@@ -1861,19 +1872,19 @@ export default {
"AxisNameDisplay": {},
"BarChartConfiguration": {
"aggregateFieldMetadataId": [
- 534
+ 537
],
"aggregateOperation": [
27
],
"axisNameDisplay": [
- 92
+ 93
],
"color": [
1
],
"configurationType": [
- 664
+ 667
],
"description": [
1
@@ -1885,31 +1896,31 @@ export default {
4
],
"filter": [
- 324
+ 327
],
"firstDayOfTheWeek": [
10
],
"groupMode": [
- 96
+ 97
],
"isCumulative": [
4
],
"layout": [
- 97
+ 98
],
"numberFormat": [
- 142
+ 143
],
"omitNullValues": [
4
],
"primaryAxisDateGranularity": [
- 399
+ 402
],
"primaryAxisGroupByFieldMetadataId": [
- 534
+ 537
],
"primaryAxisGroupBySubFieldName": [
1
@@ -1918,7 +1929,7 @@ export default {
1
],
"primaryAxisOrderBy": [
- 303
+ 306
],
"rangeMax": [
6
@@ -1927,10 +1938,10 @@ export default {
6
],
"secondaryAxisGroupByDateGranularity": [
- 399
+ 402
],
"secondaryAxisGroupByFieldMetadataId": [
- 534
+ 537
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -1939,7 +1950,7 @@ export default {
1
],
"secondaryAxisOrderBy": [
- 303
+ 306
],
"splitMultiValueFields": [
4
@@ -1953,13 +1964,13 @@ export default {
},
"BarChartData": {
"data": [
- 324
+ 327
],
"formattedToRawLookup": [
- 324
+ 327
],
"groupMode": [
- 96
+ 97
],
"hasTooManyGroups": [
4
@@ -1971,10 +1982,10 @@ export default {
1
],
"layout": [
- 97
+ 98
],
"series": [
- 98
+ 99
],
"showDataLabels": [
4
@@ -1994,10 +2005,10 @@ export default {
},
"BarChartDataInput": {
"configuration": [
- 324
+ 327
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -2028,7 +2039,7 @@ export default {
1
],
"trialPeriods": [
- 124
+ 125
],
"__typename": [
1
@@ -2039,10 +2050,10 @@ export default {
4
],
"id": [
- 534
+ 537
],
"userCreditsFallback": [
- 636
+ 639
],
"__typename": [
1
@@ -2053,16 +2064,16 @@ export default {
1
],
"billingSubscriptions": [
- 119
+ 120
],
"currentBillingSubscription": [
- 119
+ 120
],
"hasPaymentMethod": [
4
],
"status": [
- 507
+ 510
],
"__typename": [
1
@@ -2070,7 +2081,7 @@ export default {
},
"BillingEntitlement": {
"key": [
- 104
+ 105
],
"value": [
4
@@ -2088,13 +2099,13 @@ export default {
1
],
"metadata": [
- 116
+ 117
],
"name": [
1
],
"prices": [
- 110
+ 111
],
"__typename": [
1
@@ -2108,13 +2119,13 @@ export default {
1
],
"metadata": [
- 116
+ 117
],
"name": [
1
],
"prices": [
- 111
+ 112
],
"__typename": [
1
@@ -2133,10 +2144,10 @@ export default {
},
"BillingPlan": {
"baseProducts": [
- 105
+ 106
],
"downgradePlanKeys": [
- 109
+ 110
],
"isCheckoutDefault": [
4
@@ -2145,16 +2156,16 @@ export default {
4
],
"meteredProducts": [
- 106
+ 107
],
"planKey": [
- 109
+ 110
],
"resourceCreditProducts": [
- 105
+ 106
],
"upgradePlanKeys": [
- 109
+ 110
],
"__typename": [
1
@@ -2169,10 +2180,10 @@ export default {
4
],
"priceUsageType": [
- 126
+ 127
],
"recurringInterval": [
- 506
+ 509
],
"stripePriceId": [
1
@@ -2186,16 +2197,16 @@ export default {
},
"BillingPriceMetered": {
"priceUsageType": [
- 126
+ 127
],
"recurringInterval": [
- 506
+ 509
],
"stripePriceId": [
1
],
"tiers": [
- 112
+ 113
],
"__typename": [
1
@@ -2223,7 +2234,7 @@ export default {
1
],
"metadata": [
- 116
+ 117
],
"name": [
1
@@ -2240,16 +2251,16 @@ export default {
1
],
"metadata": [
- 116
+ 117
],
"name": [
1
],
"on_BillingLicensedProduct": [
- 105
+ 106
],
"on_BillingMeteredProduct": [
- 106
+ 107
],
"__typename": [
1
@@ -2261,13 +2272,13 @@ export default {
1
],
"planKey": [
- 109
+ 110
],
"priceUsageBased": [
- 126
+ 127
],
"productKey": [
- 115
+ 116
],
"__typename": [
1
@@ -2275,13 +2286,13 @@ export default {
},
"BillingResourceCreditUsage": {
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"productKey": [
- 115
+ 116
],
"unitPriceCents": [
6
@@ -2321,34 +2332,34 @@ export default {
},
"BillingSubscription": {
"billingSubscriptionItems": [
- 121
+ 122
],
"cancelAt": [
- 212
+ 213
],
"collectionMethod": [
- 120
+ 121
],
"currentPeriodEnd": [
- 212
+ 213
],
"hasUserCredits": [
4
],
"id": [
- 534
+ 537
],
"interval": [
- 506
+ 509
],
"metadata": [
- 324
+ 327
],
"phases": [
- 122
+ 123
],
"status": [
- 507
+ 510
],
"__typename": [
1
@@ -2357,7 +2368,7 @@ export default {
"BillingSubscriptionCollectionMethod": {},
"BillingSubscriptionItem": {
"billingProduct": [
- 114
+ 115
],
"creditAmount": [
6
@@ -2366,7 +2377,7 @@ export default {
4
],
"id": [
- 534
+ 537
],
"quantity": [
6
@@ -2386,7 +2397,7 @@ export default {
6
],
"items": [
- 123
+ 124
],
"start_date": [
6
@@ -2419,10 +2430,10 @@ export default {
},
"BillingUpdate": {
"billingSubscriptions": [
- 119
+ 120
],
"currentBillingSubscription": [
- 119
+ 120
],
"__typename": [
1
@@ -2442,13 +2453,13 @@ export default {
},
"CalendarChannel": {
"connectedAccountId": [
- 534
+ 537
],
"contactAutoCreationPolicy": [
- 129
+ 130
],
"createdAt": [
- 212
+ 213
],
"excludePrivateEvents": [
4
@@ -2457,7 +2468,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isContactAutoCreationEnabled": [
4
@@ -2466,25 +2477,25 @@ export default {
4
],
"syncStage": [
- 130
+ 131
],
"syncStageStartedAt": [
- 212
+ 213
],
"syncStatus": [
- 131
+ 132
],
"syncedAt": [
- 212
+ 213
],
"throttleFailureCount": [
6
],
"updatedAt": [
- 212
+ 213
],
"visibility": [
- 132
+ 133
],
"__typename": [
1
@@ -2496,7 +2507,7 @@ export default {
"CalendarChannelVisibility": {},
"CalendarConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -2504,7 +2515,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -2512,7 +2523,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -2568,7 +2579,7 @@ export default {
},
"Captcha": {
"provider": [
- 140
+ 141
],
"siteKey": [
1
@@ -2589,7 +2600,7 @@ export default {
"ChartNumberFormat": {},
"ChatConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -2597,10 +2608,10 @@ export default {
},
"ChatStreamCatchupChunks": {
"chunks": [
- 324
+ 327
],
"error": [
- 145
+ 146
],
"maxSeq": [
10
@@ -2622,7 +2633,7 @@ export default {
},
"ChatThreadsConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -2747,7 +2758,7 @@ export default {
6
],
"modelFamily": [
- 379
+ 382
],
"modelFamilyLabel": [
1
@@ -2756,7 +2767,7 @@ export default {
1
],
"nativeCapabilities": [
- 381
+ 384
],
"outputCostPerMillionTokens": [
6
@@ -2790,13 +2801,13 @@ export default {
},
"ClientConfig": {
"aiEvaluationModels": [
- 149
+ 150
],
"aiModelTiers": [
- 151
+ 152
],
"aiModels": [
- 150
+ 151
],
"allowRequestsToTwentyIcons": [
4
@@ -2805,16 +2816,16 @@ export default {
4
],
"api": [
- 37
+ 38
],
"appVersion": [
1
],
"authProviders": [
- 83
+ 84
],
"billing": [
- 100
+ 101
],
"calendarBookingPageId": [
1
@@ -2823,7 +2834,7 @@ export default {
4
],
"captcha": [
- 139
+ 140
],
"defaultSubdomain": [
1
@@ -2886,16 +2897,16 @@ export default {
4
],
"maintenance": [
- 153
+ 154
],
"publicFeatureFlags": [
- 429
+ 432
],
"publicFunctionDomain": [
1
],
"sentry": [
- 491
+ 494
],
"serverUrl": [
1
@@ -2904,7 +2915,7 @@ export default {
4
],
"support": [
- 508
+ 511
],
"__typename": [
1
@@ -2912,13 +2923,13 @@ export default {
},
"ClientConfigMaintenanceMode": {
"endAt": [
- 212
+ 213
],
"link": [
1
],
"startAt": [
- 212
+ 213
],
"__typename": [
1
@@ -2926,7 +2937,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 34
+ 35
],
"hash": [
1
@@ -2937,13 +2948,13 @@ export default {
},
"CommandMenuItem": {
"applicationId": [
- 534
+ 537
],
"availabilityObjectMetadataId": [
- 534
+ 537
],
"availabilityType": [
- 156
+ 157
],
"conditionalAvailabilityExpression": [
1
@@ -2952,19 +2963,19 @@ export default {
1
],
"coreWorkflowVersionId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"engineComponentKey": [
- 246
+ 247
],
"frontComponent": [
- 287
+ 288
],
"frontComponentId": [
- 534
+ 537
],
"hotKeys": [
1
@@ -2973,7 +2984,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -2985,13 +2996,13 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 534
+ 537
],
"pageLayoutId": [
- 534
+ 537
],
"payload": [
- 157
+ 158
],
"position": [
6
@@ -3000,13 +3011,13 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"workflowVersionId": [
- 534
+ 537
],
"__typename": [
1
@@ -3015,10 +3026,10 @@ export default {
"CommandMenuItemAvailabilityType": {},
"CommandMenuItemPayload": {
"on_ObjectMetadataCommandMenuItemPayload": [
- 391
+ 394
],
"on_PathCommandMenuItemPayload": [
- 415
+ 418
],
"__typename": [
1
@@ -3026,10 +3037,10 @@ export default {
},
"CompleteApplicationFileUploadsResult": {
"errors": [
- 58
+ 59
],
"files": [
- 278
+ 279
],
"__typename": [
1
@@ -3037,25 +3048,25 @@ export default {
},
"ConnectedAccountPublicDTO": {
"applicationId": [
- 534
+ 537
],
"archivedAt": [
- 212
+ 213
],
"authFailedAt": [
- 212
+ 213
],
"authFailedReason": [
1
],
"connectionParameters": [
- 431
+ 434
],
"connectionProviderId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"handle": [
1
@@ -3064,13 +3075,13 @@ export default {
1
],
"id": [
- 534
+ 537
],
"lastCredentialsRefreshedAt": [
- 212
+ 213
],
"lastSignedInAt": [
- 212
+ 213
],
"name": [
1
@@ -3079,16 +3090,16 @@ export default {
1
],
"scope": [
- 160
+ 161
],
"scopes": [
1
],
"updatedAt": [
- 212
+ 213
],
"userWorkspaceId": [
- 534
+ 537
],
"visibility": [
1
@@ -3100,19 +3111,19 @@ export default {
"ConnectedAccountScope": {},
"ConnectedImapSmtpCaldavAccount": {
"connectionParameters": [
- 309
+ 312
],
"handle": [
1
],
"id": [
- 534
+ 537
],
"provider": [
1
],
"userWorkspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -3121,7 +3132,7 @@ export default {
"ConnectionCursor": {},
"ConnectionParametersInput": {
"connectionSecurity": [
- 239
+ 240
],
"host": [
1
@@ -3151,7 +3162,7 @@ export default {
1
],
"roleIds": [
- 534
+ 537
],
"__typename": [
1
@@ -3168,7 +3179,7 @@ export default {
1
],
"modelConfiguration": [
- 324
+ 327
],
"modelId": [
1
@@ -3180,13 +3191,13 @@ export default {
1
],
"responseFormat": [
- 324
+ 327
],
"roleId": [
- 534
+ 537
],
"triggers": [
- 324
+ 327
],
"__typename": [
1
@@ -3203,7 +3214,7 @@ export default {
1
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -3211,7 +3222,7 @@ export default {
},
"CreateAppMessageChannelInput": {
"connectedAccountId": [
- 534
+ 537
],
"displayName": [
1
@@ -3220,13 +3231,13 @@ export default {
1
],
"messagingProviderUniversalIdentifier": [
- 534
+ 537
],
"participantHandleFieldUniversalIdentifier": [
- 534
+ 537
],
"visibility": [
- 361
+ 364
],
"__typename": [
1
@@ -3234,10 +3245,10 @@ export default {
},
"CreateApplicationFileUploadsResult": {
"errors": [
- 59
+ 60
],
"targets": [
- 61
+ 62
],
"__typename": [
1
@@ -3245,7 +3256,7 @@ export default {
},
"CreateApplicationRegistration": {
"applicationRegistration": [
- 73
+ 74
],
"clientSecret": [
1
@@ -3342,10 +3353,10 @@ export default {
},
"CreateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 534
+ 537
],
"availabilityType": [
- 156
+ 157
],
"conditionalAvailabilityExpression": [
1
@@ -3354,13 +3365,13 @@ export default {
1
],
"coreWorkflowVersionId": [
- 534
+ 537
],
"engineComponentKey": [
- 246
+ 247
],
"frontComponentId": [
- 534
+ 537
],
"hotKeys": [
1
@@ -3375,13 +3386,13 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 534
+ 537
],
"pageLayoutId": [
- 534
+ 537
],
"payload": [
- 324
+ 327
],
"position": [
6
@@ -3390,7 +3401,7 @@ export default {
1
],
"workflowVersionId": [
- 534
+ 537
],
"__typename": [
1
@@ -3412,7 +3423,7 @@ export default {
1
],
"messageChannel": [
- 355
+ 358
],
"__typename": [
1
@@ -3428,7 +3439,7 @@ export default {
},
"CreateFieldInput": {
"defaultValue": [
- 324
+ 327
],
"description": [
1
@@ -3470,25 +3481,25 @@ export default {
1
],
"morphRelationsCreationPayload": [
- 324
+ 327
],
"name": [
1
],
"objectMetadataId": [
- 534
+ 537
],
"options": [
- 324
+ 327
],
"relationCreationPayload": [
- 324
+ 327
],
"settings": [
- 324
+ 327
],
"type": [
- 273
+ 274
],
"__typename": [
1
@@ -3508,7 +3519,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"name": [
1
@@ -3522,7 +3533,7 @@ export default {
},
"CreateIndexFieldInput": {
"fieldMetadataId": [
- 534
+ 537
],
"subFieldName": [
1
@@ -3533,13 +3544,13 @@ export default {
},
"CreateIndexInput": {
"fields": [
- 181
+ 182
],
"indexType": [
- 317
+ 320
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -3547,40 +3558,40 @@ export default {
},
"CreateLogicFunctionFromSourceInput": {
"cronTriggerSettings": [
- 324
+ 327
],
"databaseEventTriggerSettings": [
- 324
+ 327
],
"description": [
1
],
"httpRouteTriggerSettings": [
- 324
+ 327
],
"id": [
- 534
+ 537
],
"name": [
1
],
"serverRouteTriggerSettings": [
- 324
+ 327
],
"source": [
- 324
+ 327
],
"timeoutSeconds": [
6
],
"toolTriggerSettings": [
- 324
+ 327
],
"universalIdentifier": [
- 534
+ 537
],
"workflowActionTriggerSettings": [
- 324
+ 327
],
"__typename": [
1
@@ -3588,10 +3599,10 @@ export default {
},
"CreateMcpServerInput": {
"connectionProviderId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -3614,7 +3625,7 @@ export default {
1
],
"unsubscribeTopicId": [
- 534
+ 537
],
"__typename": [
1
@@ -3622,19 +3633,19 @@ export default {
},
"CreateNavigationMenuItemInput": {
"agentChatChannelId": [
- 534
+ 537
],
"color": [
1
],
"folderId": [
- 534
+ 537
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"link": [
1
@@ -3643,25 +3654,25 @@ export default {
1
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
],
"targetObjectMetadataId": [
- 534
+ 537
],
"targetRecordId": [
- 534
+ 537
],
"type": [
- 383
+ 386
],
"userWorkspaceId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -3699,7 +3710,7 @@ export default {
1
],
"primaryKeyFieldMetadataSettings": [
- 324
+ 327
],
"shortcut": [
1
@@ -3713,7 +3724,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 179
+ 180
],
"__typename": [
1
@@ -3721,7 +3732,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 182
+ 183
],
"__typename": [
1
@@ -3729,7 +3740,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 187
+ 188
],
"__typename": [
1
@@ -3740,10 +3751,10 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"type": [
- 408
+ 411
],
"__typename": [
1
@@ -3751,10 +3762,10 @@ export default {
},
"CreatePageLayoutTabInput": {
"layoutMode": [
- 407
+ 410
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
@@ -3768,22 +3779,22 @@ export default {
},
"CreatePageLayoutWidgetInput": {
"configuration": [
- 324
+ 327
],
"objectMetadataId": [
- 534
+ 537
],
"pageLayoutTabId": [
- 534
+ 537
],
"position": [
- 324
+ 327
],
"title": [
1
],
"type": [
- 665
+ 668
],
"__typename": [
1
@@ -3791,16 +3802,16 @@ export default {
},
"CreateRecordExportInput": {
"fieldMetadataIds": [
- 534
+ 537
],
"filter": [
- 324
+ 327
],
"objectMetadataId": [
- 534
+ 537
],
"orderBy": [
- 324
+ 327
],
"__typename": [
1
@@ -3808,19 +3819,19 @@ export default {
},
"CreateRelatedRecordPathInput": {
"firstFieldMetadataId": [
- 534
+ 537
],
"isInherent": [
4
],
"objectMetadataId": [
- 534
+ 537
],
"secondFieldMetadataId": [
- 534
+ 537
],
"thirdFieldMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -3884,7 +3895,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"label": [
1
@@ -3904,7 +3915,7 @@ export default {
1
],
"visibility": [
- 538
+ 541
],
"__typename": [
1
@@ -3912,16 +3923,16 @@ export default {
},
"CreateUsageLimitInput": {
"burstValue": [
- 99
+ 100
],
"limitKind": [
1
],
"limitValue": [
- 99
+ 100
],
"operationType": [
- 623
+ 626
],
"periodCount": [
10
@@ -3930,7 +3941,7 @@ export default {
1
],
"resourceType": [
- 630
+ 633
],
"spenderId": [
1
@@ -3939,7 +3950,7 @@ export default {
1
],
"unit": [
- 632
+ 635
],
"__typename": [
1
@@ -3950,7 +3961,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 534
+ 537
],
"expression": [
1
@@ -3968,7 +3979,7 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -3976,7 +3987,7 @@ export default {
},
"CreateViewFieldGroupInput": {
"id": [
- 534
+ 537
],
"isVisible": [
4
@@ -3988,7 +3999,7 @@ export default {
6
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -3999,10 +4010,10 @@ export default {
27
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"isVisible": [
4
@@ -4014,10 +4025,10 @@ export default {
6
],
"viewFieldGroupId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -4025,19 +4036,19 @@ export default {
},
"CreateViewFilterGroupInput": {
"id": [
- 534
+ 537
],
"logicalOperator": [
- 653
+ 656
],
"parentViewFilterGroupId": [
- 534
+ 537
],
"positionInViewFilterGroup": [
6
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -4045,31 +4056,31 @@ export default {
},
"CreateViewFilterInput": {
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"operand": [
- 654
+ 657
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 534
+ 537
],
"subFieldName": [
1
],
"value": [
- 324
+ 327
],
"viewFilterGroupId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -4080,7 +4091,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isVisible": [
4
@@ -4089,7 +4100,7 @@ export default {
6
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -4100,13 +4111,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 534
+ 537
],
"calendarFieldMetadataId": [
- 534
+ 537
],
"calendarLayout": [
- 647
+ 650
],
"groupLoadLimit": [
10
@@ -4115,7 +4126,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isCompact": [
4
@@ -4124,25 +4135,25 @@ export default {
27
],
"kanbanAggregateOperationFieldMetadataId": [
- 534
+ 537
],
"kanbanColumnWidth": [
10
],
"key": [
- 656
+ 659
],
"mainGroupByFieldMetadataId": [
- 534
+ 537
],
"name": [
1
],
"objectMetadataId": [
- 534
+ 537
],
"openRecordIn": [
- 657
+ 660
],
"position": [
6
@@ -4151,10 +4162,10 @@ export default {
4
],
"type": [
- 660
+ 663
],
"visibility": [
- 661
+ 664
],
"__typename": [
1
@@ -4162,19 +4173,19 @@ export default {
},
"CreateViewSortInput": {
"direction": [
- 659
+ 662
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"subFieldName": [
1
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -4185,13 +4196,13 @@ export default {
1
],
"id": [
- 534
+ 537
],
"operations": [
1
],
"roleId": [
- 534
+ 537
],
"secret": [
1
@@ -4214,10 +4225,10 @@ export default {
1
],
"operation": [
- 623
+ 626
],
"resource": [
- 630
+ 633
],
"__typename": [
1
@@ -4225,10 +4236,10 @@ export default {
},
"CursorPaging": {
"after": [
- 162
+ 163
],
"before": [
- 162
+ 163
],
"first": [
10
@@ -4244,7 +4255,7 @@ export default {
"DateTime": {},
"DeleteApprovedAccessDomainInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4252,7 +4263,7 @@ export default {
},
"DeleteOneFieldInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4260,7 +4271,7 @@ export default {
},
"DeleteOneIndexInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4268,7 +4279,7 @@ export default {
},
"DeleteOneObjectInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4276,7 +4287,7 @@ export default {
},
"DeleteSso": {
"identityProviderId": [
- 534
+ 537
],
"__typename": [
1
@@ -4284,7 +4295,7 @@ export default {
},
"DeleteSsoInput": {
"identityProviderId": [
- 534
+ 537
],
"__typename": [
1
@@ -4300,7 +4311,7 @@ export default {
},
"DeleteViewFieldGroupInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4308,7 +4319,7 @@ export default {
},
"DeleteViewFieldInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4316,7 +4327,7 @@ export default {
},
"DeleteViewFilterInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4324,7 +4335,7 @@ export default {
},
"DeleteViewGroupInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4332,7 +4343,7 @@ export default {
},
"DeleteViewSortInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4343,16 +4354,16 @@ export default {
1
],
"id": [
- 534
+ 537
],
"name": [
- 290
+ 291
],
"userEmail": [
1
],
"userWorkspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -4360,7 +4371,7 @@ export default {
},
"DestroyViewFieldGroupInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4368,7 +4379,7 @@ export default {
},
"DestroyViewFieldInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4376,7 +4387,7 @@ export default {
},
"DestroyViewFilterInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4384,7 +4395,7 @@ export default {
},
"DestroyViewGroupInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4392,7 +4403,7 @@ export default {
},
"DestroyViewSortInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -4434,13 +4445,13 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isCustomDomainEnabled": [
4
],
"records": [
- 232
+ 233
],
"__typename": [
1
@@ -4451,10 +4462,10 @@ export default {
1
],
"id": [
- 534
+ 537
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
@@ -4477,7 +4488,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"memberCount": [
6
@@ -4497,7 +4508,7 @@ export default {
},
"EditSso": {
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -4506,10 +4517,10 @@ export default {
1
],
"status": [
- 474
+ 477
],
"type": [
- 305
+ 308
],
"__typename": [
1
@@ -4517,10 +4528,10 @@ export default {
},
"EditSsoInput": {
"id": [
- 534
+ 537
],
"status": [
- 474
+ 477
],
"__typename": [
1
@@ -4528,13 +4539,13 @@ export default {
},
"EmailAccountConnectionParameters": {
"CALDAV": [
- 163
+ 164
],
"IMAP": [
- 163
+ 164
],
"SMTP": [
- 163
+ 164
],
"name": [
1
@@ -4554,7 +4565,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -4562,31 +4573,31 @@ export default {
},
"EmailingDomain": {
"createdAt": [
- 212
+ 213
],
"domain": [
1
],
"id": [
- 534
+ 537
],
"status": [
- 243
+ 244
],
"tenantStatus": [
- 244
+ 245
],
"unsubscribeHostnameStatus": [
- 536
+ 539
],
"updatedAt": [
- 212
+ 213
],
"verificationRecords": [
- 642
+ 645
],
"verifiedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -4596,7 +4607,7 @@ export default {
"EmailingDomainTenantStatus": {},
"EmailsConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -4614,7 +4625,7 @@ export default {
1
],
"payload": [
- 324
+ 327
],
"retryLimit": [
10
@@ -4628,7 +4639,7 @@ export default {
1
],
"payload": [
- 324
+ 327
],
"__typename": [
1
@@ -4653,13 +4664,13 @@ export default {
10
],
"jobs": [
- 248
+ 249
],
"logicFunctionUniversalIdentifier": [
1
],
"payloads": [
- 324
+ 327
],
"retryLimit": [
10
@@ -4687,7 +4698,7 @@ export default {
},
"EnterpriseLicenseInfoDTO": {
"expiresAt": [
- 212
+ 213
],
"isValid": [
4
@@ -4704,13 +4715,13 @@ export default {
},
"EnterpriseSubscriptionStatusDTO": {
"cancelAt": [
- 212
+ 213
],
"currentPeriodEnd": [
- 212
+ 213
],
"expiresAt": [
- 212
+ 213
],
"isCancellationScheduled": [
4
@@ -4727,10 +4738,10 @@ export default {
},
"EventLogDateRangeInput": {
"end": [
- 212
+ 213
],
"start": [
- 212
+ 213
],
"__typename": [
1
@@ -4741,7 +4752,7 @@ export default {
1
],
"operand": [
- 256
+ 257
],
"values": [
1
@@ -4753,13 +4764,13 @@ export default {
"EventLogFilterOperand": {},
"EventLogFiltersInput": {
"dateRange": [
- 254
+ 255
],
"eventType": [
1
],
"fieldFilters": [
- 255
+ 256
],
"objectMetadataId": [
1
@@ -4790,13 +4801,13 @@ export default {
1
],
"filters": [
- 257
+ 258
],
"first": [
10
],
"table": [
- 262
+ 263
],
"__typename": [
1
@@ -4804,10 +4815,10 @@ export default {
},
"EventLogQueryResult": {
"pageInfo": [
- 258
+ 259
],
"records": [
- 261
+ 262
],
"totalCount": [
10
@@ -4827,13 +4838,13 @@ export default {
1
],
"properties": [
- 324
+ 327
],
"recordId": [
1
],
"timestamp": [
- 212
+ 213
],
"userId": [
1
@@ -4848,13 +4859,13 @@ export default {
1
],
"metadataEvents": [
- 370
+ 373
],
"objectRecordEventsWithQueryIds": [
- 398
+ 401
],
"queueJobEvents": [
- 327
+ 330
],
"__typename": [
1
@@ -4862,10 +4873,10 @@ export default {
},
"ExecuteOneLogicFunctionInput": {
"id": [
- 534
+ 537
],
"payload": [
- 324
+ 327
],
"__typename": [
1
@@ -4873,7 +4884,7 @@ export default {
},
"FeatureFlag": {
"key": [
- 266
+ 267
],
"value": [
4
@@ -4885,13 +4896,13 @@ export default {
"FeatureFlagKey": {},
"Field": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"defaultValue": [
- 324
+ 327
],
"description": [
1
@@ -4903,7 +4914,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -4936,37 +4947,37 @@ export default {
1
],
"morphId": [
- 534
+ 537
],
"morphRelations": [
- 450
+ 453
],
"name": [
1
],
"object": [
- 385
+ 388
],
"objectMetadataId": [
- 534
+ 537
],
"options": [
- 324
+ 327
],
"relation": [
- 450
+ 453
],
"settings": [
- 324
+ 327
],
"type": [
- 273
+ 274
],
"universalIdentifier": [
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -4974,10 +4985,10 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 664
+ 667
],
"fieldDisplayMode": [
- 270
+ 271
],
"fieldMetadataId": [
1
@@ -4997,10 +5008,10 @@ export default {
},
"FieldConnection": {
"edges": [
- 271
+ 272
],
"pageInfo": [
- 404
+ 407
],
"__typename": [
1
@@ -5009,10 +5020,10 @@ export default {
"FieldDisplayMode": {},
"FieldEdge": {
"cursor": [
- 162
+ 163
],
"node": [
- 267
+ 268
],
"__typename": [
1
@@ -5020,28 +5031,28 @@ export default {
},
"FieldFilter": {
"and": [
- 272
+ 273
],
"id": [
- 535
+ 538
],
"isActive": [
- 127
+ 128
],
"isSystem": [
- 127
+ 128
],
"isUIEditable": [
- 127
+ 128
],
"isUIReadOnly": [
- 127
+ 128
],
"objectMetadataId": [
- 535
+ 538
],
"or": [
- 272
+ 273
],
"__typename": [
1
@@ -5056,16 +5067,16 @@ export default {
4
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"objectMetadataId": [
- 534
+ 537
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -5079,10 +5090,10 @@ export default {
4
],
"fieldMetadataId": [
- 534
+ 537
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -5090,7 +5101,7 @@ export default {
},
"FieldRichTextConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -5098,7 +5109,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 664
+ 667
],
"newFieldDefaultVisibility": [
4
@@ -5115,10 +5126,10 @@ export default {
},
"File": {
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"path": [
1
@@ -5135,7 +5146,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -5147,10 +5158,10 @@ export default {
1
],
"expiresAt": [
- 212
+ 213
],
"fileId": [
- 534
+ 537
],
"uploadUrl": [
1
@@ -5161,10 +5172,10 @@ export default {
},
"FileWithSignedUrl": {
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"path": [
1
@@ -5181,7 +5192,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -5189,7 +5200,7 @@ export default {
},
"FindAvailableSSOIDP": {
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -5198,13 +5209,13 @@ export default {
1
],
"status": [
- 474
+ 477
],
"type": [
- 305
+ 308
],
"workspace": [
- 685
+ 688
],
"__typename": [
1
@@ -5218,13 +5229,13 @@ export default {
10
],
"reason": [
- 368
+ 371
],
"searchTerm": [
1
],
"unsubscribeTopicId": [
- 534
+ 537
],
"__typename": [
1
@@ -5232,7 +5243,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 664
+ 667
],
"fieldMetadataId": [
1
@@ -5246,16 +5257,16 @@ export default {
1
],
"applicationId": [
- 534
+ 537
],
"applicationName": [
1
],
"applicationTokenPair": [
- 78
+ 79
],
"applicationVariables": [
- 324
+ 327
],
"builtComponentChecksum": [
1
@@ -5267,7 +5278,7 @@ export default {
1
],
"createdAt": [
- 212
+ 213
],
"description": [
1
@@ -5276,7 +5287,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isHeadless": [
4
@@ -5288,16 +5299,16 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"usesSdkClient": [
4
],
"widgetAvailability": [
- 289
+ 290
],
"__typename": [
1
@@ -5305,13 +5316,13 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 664
+ 667
],
"frontComponentId": [
- 534
+ 537
],
"headerCommandMenuItemUniversalIdentifiers": [
- 534
+ 537
],
"__typename": [
1
@@ -5319,10 +5330,10 @@ export default {
},
"FrontComponentWidgetAvailability": {
"objectMetadataId": [
- 534
+ 537
],
"pageLayoutType": [
- 408
+ 411
],
"__typename": [
1
@@ -5339,54 +5350,100 @@ export default {
1
]
},
- "GetApiKeyInput": {
- "id": [
- 534
+ "GenerateInput": {
+ "input": [
+ 471
],
- "__typename": [
+ "instructions": [
1
- ]
- },
- "GetAuthorizationUrlForSSO": {
- "authorizationURL": [
+ ],
+ "modelId": [
1
],
- "id": [
- 534
+ "responseFormat": [
+ 327
],
- "type": [
- 1
+ "runId": [
+ 537
+ ],
+ "scope": [
+ 327
],
"__typename": [
1
]
},
- "GetAuthorizationUrlForSSOInput": {
- "identityProviderId": [
- 534
- ],
- "workspaceInviteHash": [
+ "GenerateResult": {
+ "error": [
1
],
- "__typename": [
- 1
- ]
- },
- "GettingStartedProgress": {
+ "object": [
+ 327
+ ],
+ "runId": [
+ 537
+ ],
+ "success": [
+ 4
+ ],
+ "text": [
+ 1
+ ],
+ "usage": [
+ 32
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GetApiKeyInput": {
+ "id": [
+ 537
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GetAuthorizationUrlForSSO": {
+ "authorizationURL": [
+ 1
+ ],
+ "id": [
+ 537
+ ],
+ "type": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GetAuthorizationUrlForSSOInput": {
+ "identityProviderId": [
+ 537
+ ],
+ "workspaceInviteHash": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GettingStartedProgress": {
"completedStepActionKeys": [
- 295
+ 298
],
"isHidden": [
4
],
"selectedStepActionKey": [
- 295
+ 298
],
"snoozedUntil": [
1
],
"steps": [
- 296
+ 299
],
"__typename": [
1
@@ -5395,7 +5452,7 @@ export default {
"GettingStartedStepActionKey": {},
"GettingStartedStepDefinition": {
"actionKey": [
- 295
+ 298
],
"description": [
1
@@ -5410,7 +5467,7 @@ export default {
1
],
"kind": [
- 297
+ 300
],
"prompt": [
1
@@ -5439,13 +5496,13 @@ export default {
},
"GettingStartedWorkflowPreview": {
"actions": [
- 300
+ 303
],
"stepActionKey": [
- 295
+ 298
],
"trigger": [
- 301
+ 304
],
"__typename": [
1
@@ -5456,7 +5513,7 @@ export default {
1
],
"type": [
- 666
+ 669
],
"__typename": [
1
@@ -5478,7 +5535,7 @@ export default {
},
"GrantApplicationCapabilitiesInput": {
"applicationId": [
- 534
+ 537
],
"capabilities": [
1
@@ -5508,7 +5565,7 @@ export default {
"IdentityProviderType": {},
"IframeConfiguration": {
"configurationType": [
- 664
+ 667
],
"url": [
1
@@ -5544,13 +5601,13 @@ export default {
},
"ImapSmtpCaldavPublicConnectionParameters": {
"CALDAV": [
- 310
+ 313
],
"IMAP": [
- 310
+ 313
],
"SMTP": [
- 310
+ 313
],
"name": [
1
@@ -5561,7 +5618,7 @@ export default {
},
"ImapSmtpCaldavPublicConnectionParams": {
"connectionSecurity": [
- 239
+ 240
],
"host": [
1
@@ -5578,10 +5635,10 @@ export default {
},
"Impersonate": {
"loginToken": [
- 84
+ 85
],
"workspace": [
- 689
+ 692
],
"__typename": [
1
@@ -5592,10 +5649,10 @@ export default {
1
],
"recordId": [
- 534
+ 537
],
"threadId": [
- 534
+ 537
],
"__typename": [
1
@@ -5603,19 +5660,19 @@ export default {
},
"Index": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"indexFieldMetadataList": [
- 315
+ 318
],
"indexType": [
- 317
+ 320
],
"indexWhereClause": [
1
@@ -5633,7 +5690,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -5641,10 +5698,10 @@ export default {
},
"IndexEdge": {
"cursor": [
- 162
+ 163
],
"node": [
- 313
+ 316
],
"__typename": [
1
@@ -5652,13 +5709,13 @@ export default {
},
"IndexField": {
"createdAt": [
- 212
+ 213
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"order": [
6
@@ -5667,7 +5724,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -5675,16 +5732,16 @@ export default {
},
"IndexFilter": {
"and": [
- 316
+ 319
],
"id": [
- 535
+ 538
],
"isCustom": [
- 127
+ 128
],
"or": [
- 316
+ 319
],
"__typename": [
1
@@ -5693,10 +5750,10 @@ export default {
"IndexType": {},
"IngestAppMessagesInput": {
"messageChannelId": [
- 534
+ 537
],
"messages": [
- 45
+ 46
],
"__typename": [
1
@@ -5704,7 +5761,7 @@ export default {
},
"IngestAppMessagesOutput": {
"messages": [
- 320
+ 323
],
"__typename": [
1
@@ -5715,10 +5772,10 @@ export default {
1
],
"messageId": [
- 534
+ 537
],
"messageThreadId": [
- 534
+ 537
],
"__typename": [
1
@@ -5777,7 +5834,7 @@ export default {
6
],
"state": [
- 326
+ 329
],
"__typename": [
1
@@ -5785,19 +5842,19 @@ export default {
},
"LineChartConfiguration": {
"aggregateFieldMetadataId": [
- 534
+ 537
],
"aggregateOperation": [
27
],
"axisNameDisplay": [
- 92
+ 93
],
"color": [
1
],
"configurationType": [
- 664
+ 667
],
"description": [
1
@@ -5809,7 +5866,7 @@ export default {
4
],
"filter": [
- 324
+ 327
],
"firstDayOfTheWeek": [
10
@@ -5821,16 +5878,16 @@ export default {
4
],
"numberFormat": [
- 142
+ 143
],
"omitNullValues": [
4
],
"primaryAxisDateGranularity": [
- 399
+ 402
],
"primaryAxisGroupByFieldMetadataId": [
- 534
+ 537
],
"primaryAxisGroupBySubFieldName": [
1
@@ -5839,7 +5896,7 @@ export default {
1
],
"primaryAxisOrderBy": [
- 303
+ 306
],
"rangeMax": [
6
@@ -5848,10 +5905,10 @@ export default {
6
],
"secondaryAxisGroupByDateGranularity": [
- 399
+ 402
],
"secondaryAxisGroupByFieldMetadataId": [
- 534
+ 537
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -5860,7 +5917,7 @@ export default {
1
],
"secondaryAxisOrderBy": [
- 303
+ 306
],
"splitMultiValueFields": [
4
@@ -5874,13 +5931,13 @@ export default {
},
"LineChartData": {
"formattedToRawLookup": [
- 324
+ 327
],
"hasTooManyGroups": [
4
],
"series": [
- 332
+ 335
],
"showDataLabels": [
4
@@ -5900,10 +5957,10 @@ export default {
},
"LineChartDataInput": {
"configuration": [
- 324
+ 327
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -5922,7 +5979,7 @@ export default {
},
"LineChartSeries": {
"data": [
- 331
+ 334
],
"key": [
1
@@ -5939,7 +5996,7 @@ export default {
1
],
"scope": [
- 160
+ 161
],
"userWorkspaceId": [
1
@@ -5953,7 +6010,7 @@ export default {
},
"ListAppMessageChannelsInput": {
"connectedAccountId": [
- 534
+ 537
],
"__typename": [
1
@@ -5961,7 +6018,7 @@ export default {
},
"ListAppMessageFoldersInput": {
"messageChannelId": [
- 534
+ 537
],
"__typename": [
1
@@ -5980,34 +6037,34 @@ export default {
},
"LogicFunction": {
"applicationId": [
- 534
+ 537
],
"canRunOnDemand": [
4
],
"createdAt": [
- 212
+ 213
],
"cronTriggerSettings": [
- 324
+ 327
],
"databaseEventTriggerSettings": [
- 324
+ 327
],
"description": [
1
],
"executionMode": [
- 338
+ 341
],
"handlerName": [
1
],
"httpRouteTriggerSettings": [
- 324
+ 327
],
"id": [
- 534
+ 537
],
"name": [
1
@@ -6022,16 +6079,16 @@ export default {
6
],
"toolTriggerSettings": [
- 324
+ 327
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"workflowActionTriggerSettings": [
- 324
+ 327
],
"__typename": [
1
@@ -6040,19 +6097,19 @@ export default {
"LogicFunctionExecutionMode": {},
"LogicFunctionExecutionResult": {
"data": [
- 324
+ 327
],
"duration": [
6
],
"error": [
- 324
+ 327
],
"logs": [
1
],
"status": [
- 340
+ 343
],
"__typename": [
1
@@ -6075,7 +6132,7 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"__typename": [
1
@@ -6083,19 +6140,19 @@ export default {
},
"LogicFunctionLogsInput": {
"applicationId": [
- 534
+ 537
],
"applicationUniversalIdentifier": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"name": [
1
],
"universalIdentifier": [
- 534
+ 537
],
"__typename": [
1
@@ -6103,7 +6160,7 @@ export default {
},
"LoginToken": {
"loginToken": [
- 84
+ 85
],
"__typename": [
1
@@ -6182,13 +6239,13 @@ export default {
1
],
"manifest": [
- 324
+ 327
],
"name": [
1
],
"objects": [
- 347
+ 350
],
"pricingDescription": [
1
@@ -6197,7 +6254,7 @@ export default {
1
],
"roles": [
- 348
+ 351
],
"screenshots": [
1
@@ -6206,7 +6263,7 @@ export default {
1
],
"sourceType": [
- 74
+ 75
],
"termsUrl": [
1
@@ -6258,7 +6315,7 @@ export default {
1
],
"fieldPermissions": [
- 349
+ 352
],
"icon": [
1
@@ -6267,7 +6324,7 @@ export default {
1
],
"objectPermissions": [
- 350
+ 353
],
"permissionFlagUniversalIdentifiers": [
1
@@ -6324,16 +6381,16 @@ export default {
},
"McpServer": {
"applicationId": [
- 534
+ 537
],
"connectionProviderId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -6345,7 +6402,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"url": [
1
@@ -6356,7 +6413,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -6364,7 +6421,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -6383,16 +6440,16 @@ export default {
},
"MessageChannel": {
"connectedAccount": [
- 159
+ 160
],
"connectedAccountId": [
- 534
+ 537
],
"contactAutoCreationPolicy": [
- 356
+ 359
],
"createdAt": [
- 212
+ 213
],
"displayName": [
1
@@ -6407,7 +6464,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"importProgress": [
10
@@ -6419,43 +6476,43 @@ export default {
4
],
"messageFolderImportPolicy": [
- 363
+ 366
],
"messagingProviderUniversalIdentifier": [
- 534
+ 537
],
"participantHandleFieldUniversalIdentifier": [
- 534
+ 537
],
"pendingGroupEmailsAction": [
- 357
+ 360
],
"syncStage": [
- 358
+ 361
],
"syncStageStartedAt": [
- 212
+ 213
],
"syncStatus": [
- 359
+ 362
],
"syncedAt": [
- 212
+ 213
],
"throttleFailureCount": [
6
],
"throttleRetryAfter": [
- 212
+ 213
],
"type": [
- 360
+ 363
],
"updatedAt": [
- 212
+ 213
],
"visibility": [
- 361
+ 364
],
"__typename": [
1
@@ -6469,13 +6526,13 @@ export default {
"MessageChannelVisibility": {},
"MessageFolder": {
"createdAt": [
- 212
+ 213
],
"externalId": [
1
],
"id": [
- 534
+ 537
],
"isSentFolder": [
4
@@ -6484,7 +6541,7 @@ export default {
4
],
"messageChannelId": [
- 534
+ 537
],
"name": [
1
@@ -6493,10 +6550,10 @@ export default {
1
],
"pendingSyncAction": [
- 364
+ 367
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -6507,22 +6564,22 @@ export default {
"MessageParticipantRole": {},
"MessageSuppression": {
"createdAt": [
- 212
+ 213
],
"emailAddress": [
1
],
"id": [
- 534
+ 537
],
"reason": [
- 368
+ 371
],
"source": [
- 369
+ 372
],
"unsubscribeTopicId": [
- 534
+ 537
],
"__typename": [
1
@@ -6530,7 +6587,7 @@ export default {
},
"MessageSuppressionList": {
"records": [
- 366
+ 369
],
"totalCount": [
10
@@ -6546,13 +6603,13 @@ export default {
1
],
"properties": [
- 397
+ 400
],
"recordId": [
1
],
"type": [
- 371
+ 374
],
"updatedCollectionHash": [
1
@@ -6573,16 +6630,16 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"property": [
1
],
"provenance": [
- 374
+ 377
],
"recordId": [
- 534
+ 537
],
"sourceValue": [
1
@@ -6611,13 +6668,13 @@ export default {
"MetadataTranslationProvenance": {},
"MetadataTranslationsInput": {
"fieldMetadataId": [
- 534
+ 537
],
"locale": [
1
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -6625,13 +6682,13 @@ export default {
},
"MinimalMetadata": {
"collectionHashes": [
- 154
+ 155
],
"objectMetadataItems": [
- 377
+ 380
],
"views": [
- 378
+ 381
],
"__typename": [
1
@@ -6645,7 +6702,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -6674,16 +6731,16 @@ export default {
},
"MinimalView": {
"id": [
- 534
+ 537
],
"key": [
- 656
+ 659
],
"objectMetadataId": [
- 534
+ 537
],
"type": [
- 660
+ 663
],
"__typename": [
1
@@ -6692,16 +6749,16 @@ export default {
"ModelFamily": {},
"Mutation": {
"activateSkill": [
- 500,
+ 503,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"activateWorkspace": [
- 670,
+ 673,
{
"data": [
0,
@@ -6717,7 +6774,7 @@ export default {
"String!"
],
"messageId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -6735,10 +6792,10 @@ export default {
4,
{
"assigneeWorkspaceMemberId": [
- 534
+ 537
],
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -6747,11 +6804,11 @@ export default {
4,
{
"agentId": [
- 534,
+ 537,
"UUID!"
],
"roleId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -6760,11 +6817,11 @@ export default {
4,
{
"apiKeyId": [
- 534,
+ 537,
"UUID!"
],
"roleId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -6773,13 +6830,13 @@ export default {
4,
{
"input": [
- 312,
+ 315,
"InboxThreadRecordInput!"
]
}
],
"authorizeApp": [
- 87,
+ 88,
{
"clientId": [
1,
@@ -6804,28 +6861,28 @@ export default {
}
],
"cancelMessageCampaign": [
- 138,
+ 139,
{
"input": [
- 137,
+ 138,
"CancelMessageCampaignInput!"
]
}
],
"cancelSwitchBillingInterval": [
- 125
+ 126
],
"cancelSwitchBillingPlan": [
- 125
+ 126
],
"cancelSwitchResourceCreditPrice": [
- 125
+ 126
],
"checkCustomDomainValidRecords": [
- 233
+ 234
],
"checkPublicDomainValidRecords": [
- 233,
+ 234,
{
"domain": [
1,
@@ -6834,14 +6891,14 @@ export default {
}
],
"checkoutSession": [
- 118,
+ 119,
{
"plan": [
- 109,
+ 110,
"BillingPlanKey!"
],
"recurringInterval": [
- 506,
+ 509,
"SubscriptionInterval!"
],
"requirePaymentMethod": [
@@ -6854,7 +6911,7 @@ export default {
}
],
"claimApplicationRegistrationOwnership": [
- 73,
+ 74,
{
"applicationRegistrationId": [
1,
@@ -6863,29 +6920,29 @@ export default {
}
],
"completeAppTarballUpload": [
- 73,
+ 74,
{
"fileId": [
- 534,
+ 537,
"UUID!"
]
}
],
"completeApplicationFileUploads": [
- 158,
+ 159,
{
"applicationUniversalIdentifier": [
1,
"String!"
],
"fileIds": [
- 534,
+ 537,
"[UUID!]!"
]
}
],
"completeBookCallOnboardingStep": [
- 402,
+ 405,
{
"hasBookedCall": [
4,
@@ -6898,7 +6955,7 @@ export default {
}
],
"completeFileUpload": [
- 282,
+ 283,
{
"fileId": [
1,
@@ -6907,7 +6964,7 @@ export default {
}
],
"completeNewWorkspaceLogoUpload": [
- 282,
+ 283,
{
"fileId": [
1,
@@ -6920,7 +6977,7 @@ export default {
}
],
"completeWorkspaceLogoUpload": [
- 282,
+ 283,
{
"fileId": [
1,
@@ -6929,7 +6986,7 @@ export default {
}
],
"completeWorkspaceMemberProfilePictureUpload": [
- 282,
+ 283,
{
"fileId": [
1,
@@ -6941,68 +6998,68 @@ export default {
5,
{
"input": [
- 165,
+ 166,
"CreateAgentChatChannelInput!"
]
}
],
"createApiKey": [
- 38,
+ 39,
{
"input": [
- 167,
+ 168,
"CreateApiKeyInput!"
]
}
],
"createAppMessageChannel": [
- 355,
+ 358,
{
"input": [
- 168,
+ 169,
"CreateAppMessageChannelInput!"
]
}
],
"createApplicationFileUploads": [
- 169,
+ 170,
{
"applicationUniversalIdentifier": [
1,
"String!"
],
"files": [
- 60,
+ 61,
"[ApplicationFileUploadRequestInput!]!"
]
}
],
"createApplicationRegistration": [
- 170,
+ 171,
{
"input": [
- 171,
+ 172,
"CreateApplicationRegistrationInput!"
]
}
],
"createApprovedAccessDomain": [
- 81,
+ 82,
{
"input": [
- 172,
+ 173,
"CreateApprovedAccessDomainInput!"
]
}
],
"createBillingPaymentMethodSetupIntent": [
- 107
+ 108
],
"createCalendarEvent": [
- 174,
+ 175,
{
"input": [
- 173,
+ 174,
"CreateCalendarEventInput!"
]
}
@@ -7011,21 +7068,21 @@ export default {
17,
{
"channelId": [
- 534
+ 537
]
}
],
"createCommandMenuItem": [
- 155,
+ 156,
{
"input": [
- 175,
+ 176,
"CreateCommandMenuItemInput!"
]
}
],
"createDevelopmentApplication": [
- 231,
+ 232,
{
"name": [
1,
@@ -7038,25 +7095,25 @@ export default {
}
],
"createEmailGroupChannel": [
- 177,
+ 178,
{
"input": [
- 176,
+ 177,
"CreateEmailGroupChannelInput!"
]
}
],
"createEmailingDomain": [
- 242,
+ 243,
{
"input": [
- 178,
+ 179,
"CreateEmailingDomainInput!"
]
}
],
"createFileUpload": [
- 281,
+ 282,
{
"fieldMetadataId": [
1
@@ -7065,7 +7122,7 @@ export default {
1
],
"fileFolder": [
- 280,
+ 281,
"FileFolder!"
],
"filename": [
@@ -7079,79 +7136,79 @@ export default {
}
],
"createFrontComponent": [
- 287,
+ 288,
{
"input": [
- 180,
+ 181,
"CreateFrontComponentInput!"
]
}
],
"createManyNavigationMenuItems": [
- 382,
+ 385,
{
"inputs": [
- 186,
+ 187,
"[CreateNavigationMenuItemInput!]!"
]
}
],
"createManyViewFieldGroups": [
- 650,
+ 653,
{
"inputs": [
- 201,
+ 202,
"[CreateViewFieldGroupInput!]!"
]
}
],
"createManyViewFields": [
- 649,
+ 652,
{
"inputs": [
- 202,
+ 203,
"[CreateViewFieldInput!]!"
]
}
],
"createManyViewGroups": [
- 655,
+ 658,
{
"inputs": [
- 205,
+ 206,
"[CreateViewGroupInput!]!"
]
}
],
"createMcpServer": [
- 351,
+ 354,
{
"input": [
- 184,
+ 185,
"CreateMcpServerInput!"
]
}
],
"createMessageSuppression": [
- 366,
+ 369,
{
"input": [
- 185,
+ 186,
"CreateMessageSuppressionInput!"
]
}
],
"createNavigationMenuItem": [
- 382,
+ 385,
{
"input": [
- 186,
+ 187,
"CreateNavigationMenuItemInput!"
]
}
],
"createNewWorkspaceLogoUpload": [
- 281,
+ 282,
{
"filename": [
1,
@@ -7168,30 +7225,30 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 497,
+ 500,
{
"input": [
- 495,
+ 498,
"SetupOIDCSsoInput!"
]
}
],
"createObjectEvent": [
- 35,
+ 36,
{
"event": [
1,
"String!"
],
"objectMetadataId": [
- 534,
+ 537,
"UUID!"
],
"properties": [
- 324
+ 327
],
"recordId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7200,85 +7257,85 @@ export default {
3,
{
"input": [
- 166,
+ 167,
"CreateAgentInput!"
]
}
],
"createOneField": [
- 267,
+ 268,
{
"input": [
- 188,
+ 189,
"CreateOneFieldMetadataInput!"
]
}
],
"createOneIndex": [
- 313,
+ 316,
{
"input": [
- 189,
+ 190,
"CreateOneIndexInput!"
]
}
],
"createOneLogicFunction": [
- 337,
+ 340,
{
"input": [
- 183,
+ 184,
"CreateLogicFunctionFromSourceInput!"
]
}
],
"createOneObject": [
- 385,
+ 388,
{
"input": [
- 190,
+ 191,
"CreateOneObjectInput!"
]
}
],
"createOneRole": [
- 457,
+ 460,
{
"createRoleInput": [
- 196,
+ 197,
"CreateRoleInput!"
]
}
],
"createPageLayout": [
- 405,
+ 408,
{
"input": [
- 191,
+ 192,
"CreatePageLayoutInput!"
]
}
],
"createPageLayoutTab": [
- 406,
+ 409,
{
"input": [
- 192,
+ 193,
"CreatePageLayoutTabInput!"
]
}
],
"createPageLayoutWidget": [
- 409,
+ 412,
{
"input": [
- 193,
+ 194,
"CreatePageLayoutWidgetInput!"
]
}
],
"createPublicDomain": [
- 428,
+ 431,
{
"applicationId": [
1,
@@ -7291,45 +7348,45 @@ export default {
}
],
"createRelatedRecordPath": [
- 449,
+ 452,
{
"input": [
- 195,
+ 196,
"CreateRelatedRecordPathInput!"
]
}
],
"createSAMLIdentityProvider": [
- 497,
+ 500,
{
"input": [
- 496,
+ 499,
"SetupSAMLSsoInput!"
]
}
],
"createSkill": [
- 500,
+ 503,
{
"input": [
- 197,
+ 198,
"CreateSkillInput!"
]
}
],
"createSubscriptionPaymentIntent": [
- 107,
+ 108,
{
"idempotencyKey": [
1,
"String!"
],
"plan": [
- 109,
+ 110,
"BillingPlanKey!"
],
"recurringInterval": [
- 506,
+ 509,
"SubscriptionInterval!"
],
"requirePaymentMethod": [
@@ -7342,109 +7399,109 @@ export default {
}
],
"createUnsubscribeTopic": [
- 537,
+ 540,
{
"input": [
- 198,
+ 199,
"CreateUnsubscribeTopicInput!"
]
}
],
"createUsageLimit": [
- 621,
+ 624,
{
"input": [
- 199,
+ 200,
"CreateUsageLimitInput!"
]
}
],
"createValidationRule": [
- 641,
+ 644,
{
"input": [
- 200,
+ 201,
"CreateValidationRuleInput!"
]
}
],
"createView": [
- 646,
+ 649,
{
"input": [
- 206,
+ 207,
"CreateViewInput!"
]
}
],
"createViewField": [
- 649,
+ 652,
{
"input": [
- 202,
+ 203,
"CreateViewFieldInput!"
]
}
],
"createViewFieldGroup": [
- 650,
+ 653,
{
"input": [
- 201,
+ 202,
"CreateViewFieldGroupInput!"
]
}
],
"createViewFilter": [
- 651,
+ 654,
{
"input": [
- 204,
+ 205,
"CreateViewFilterInput!"
]
}
],
"createViewFilterGroup": [
- 652,
+ 655,
{
"input": [
- 203,
+ 204,
"CreateViewFilterGroupInput!"
]
}
],
"createViewGroup": [
- 655,
+ 658,
{
"input": [
- 205,
+ 206,
"CreateViewGroupInput!"
]
}
],
"createViewSort": [
- 658,
+ 661,
{
"input": [
- 207,
+ 208,
"CreateViewSortInput!"
]
}
],
"createWebhook": [
- 662,
+ 665,
{
"input": [
- 208,
+ 209,
"CreateWebhookInput!"
]
}
],
"deactivateSkill": [
- 500,
+ 503,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7453,11 +7510,11 @@ export default {
4,
{
"channelId": [
- 534,
+ 537,
"UUID!"
],
"destinationChannelId": [
- 534
+ 537
]
}
],
@@ -7469,15 +7526,15 @@ export default {
"String!"
],
"scope": [
- 43
+ 44
]
}
],
"deleteAppMessageChannel": [
- 355,
+ 358,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7495,37 +7552,37 @@ export default {
4,
{
"input": [
- 213,
+ 214,
"DeleteApprovedAccessDomainInput!"
]
}
],
"deleteCommandMenuItem": [
- 155,
+ 156,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteConnectedAccount": [
- 159,
+ 160,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteCurrentWorkspace": [
- 670
+ 673
],
"deleteEmailGroupChannel": [
- 355,
+ 358,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7540,28 +7597,28 @@ export default {
}
],
"deleteFrontComponent": [
- 287,
+ 288,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteManyNavigationMenuItems": [
- 382,
+ 385,
{
"ids": [
- 534,
+ 537,
"[UUID!]!"
]
}
],
"deleteMcpServer": [
- 351,
+ 354,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7570,16 +7627,16 @@ export default {
4,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteNavigationMenuItem": [
- 382,
+ 385,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7594,37 +7651,37 @@ export default {
}
],
"deleteOneField": [
- 267,
+ 268,
{
"input": [
- 214,
+ 215,
"DeleteOneFieldInput!"
]
}
],
"deleteOneIndex": [
- 313,
+ 316,
{
"input": [
- 215,
+ 216,
"DeleteOneIndexInput!"
]
}
],
"deleteOneLogicFunction": [
- 337,
+ 340,
{
"input": [
- 341,
+ 344,
"LogicFunctionIdInput!"
]
}
],
"deleteOneObject": [
- 385,
+ 388,
{
"input": [
- 216,
+ 217,
"DeleteOneObjectInput!"
]
}
@@ -7633,7 +7690,7 @@ export default {
1,
{
"roleId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7651,43 +7708,43 @@ export default {
4,
{
"messageId": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteRelatedRecordPath": [
- 449,
+ 452,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteSSOIdentityProvider": [
- 217,
+ 218,
{
"input": [
- 218,
+ 219,
"DeleteSsoInput!"
]
}
],
"deleteSkill": [
- 500,
+ 503,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteTwoFactorAuthenticationMethod": [
- 219,
+ 220,
{
"twoFactorAuthenticationMethodId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7705,16 +7762,16 @@ export default {
4,
{
"usageLimitId": [
- 534,
+ 537,
"UUID!"
]
}
],
"deleteUser": [
- 634
+ 637
],
"deleteUserFromWorkspace": [
- 638,
+ 641,
{
"workspaceMemberIdToDelete": [
1,
@@ -7723,10 +7780,10 @@ export default {
}
],
"deleteValidationRule": [
- 641,
+ 644,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7741,28 +7798,28 @@ export default {
}
],
"deleteViewField": [
- 649,
+ 652,
{
"input": [
- 221,
+ 222,
"DeleteViewFieldInput!"
]
}
],
"deleteViewFieldGroup": [
- 650,
+ 653,
{
"input": [
- 220,
+ 221,
"DeleteViewFieldGroupInput!"
]
}
],
"deleteViewFilter": [
- 651,
+ 654,
{
"input": [
- 222,
+ 223,
"DeleteViewFilterInput!"
]
}
@@ -7777,10 +7834,10 @@ export default {
}
],
"deleteViewGroup": [
- 655,
+ 658,
{
"input": [
- 223,
+ 224,
"DeleteViewGroupInput!"
]
}
@@ -7789,16 +7846,16 @@ export default {
4,
{
"input": [
- 224,
+ 225,
"DeleteViewSortInput!"
]
}
],
"deleteWebhook": [
- 662,
+ 665,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
@@ -7849,28 +7906,28 @@ export default {
}
],
"destroyViewField": [
- 649,
+ 652,
{
"input": [
- 227,
+ 228,
"DestroyViewFieldInput!"
]
}
],
"destroyViewFieldGroup": [
- 650,
+ 653,
{
"input": [
- 226,
+ 227,
"DestroyViewFieldGroupInput!"
]
}
],
"destroyViewFilter": [
- 651,
+ 654,
{
"input": [
- 228,
+ 229,
"DestroyViewFilterInput!"
]
}
@@ -7885,10 +7942,10 @@ export default {
}
],
"destroyViewGroup": [
- 655,
+ 658,
{
"input": [
- 229,
+ 230,
"DestroyViewGroupInput!"
]
}
@@ -7897,7 +7954,7 @@ export default {
4,
{
"input": [
- 230,
+ 231,
"DestroyViewSortInput!"
]
}
@@ -7906,49 +7963,49 @@ export default {
4,
{
"input": [
- 312,
+ 315,
"InboxThreadRecordInput!"
]
}
],
"disconnectConnectedAccount": [
- 159,
+ 160,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"duplicateDashboard": [
- 234,
+ 235,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"duplicateMessageList": [
- 235,
+ 236,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"editSSOIdentityProvider": [
- 236,
+ 237,
{
"input": [
- 237,
+ 238,
"EditSsoInput!"
]
}
],
"emailPasswordResetLink": [
- 240,
+ 241,
{
"captchaToken": [
1
@@ -7958,48 +8015,57 @@ export default {
"String!"
],
"workspaceId": [
- 534
+ 537
]
}
],
"endSubscriptionTrialPeriod": [
- 102
+ 103
],
"enqueueJob": [
- 249,
+ 250,
{
"input": [
- 247,
+ 248,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 251,
+ 252,
{
"input": [
- 250,
+ 251,
"EnqueueJobsInput!"
]
}
],
"enrichWorkspaceCompany": [
- 674
+ 677
],
"executeOneLogicFunction": [
- 339,
+ 342,
{
"input": [
- 264,
+ 265,
"ExecuteOneLogicFunctionInput!"
]
}
],
+ "generate": [
+ 293,
+ {
+ "input": [
+ 292,
+ "GenerateInput!"
+ ]
+ }
+ ],
"generateApiKeyToken": [
- 40,
+ 41,
{
"apiKeyId": [
- 534,
+ 537,
"UUID!"
],
"expiresAt": [
@@ -8009,34 +8075,34 @@ export default {
}
],
"generateFrontComponentApplicationTokenPair": [
- 78,
+ 79,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
],
"generatePlaygroundToken": [
- 84
+ 85
],
"generateTransientToken": [
- 517
+ 520
],
"generateTwoFactorAuthenticationRecoveryCode": [
- 531,
+ 534,
{
"otp": [
1
],
"userId": [
- 534,
+ 537,
"UUID!"
]
}
],
"getAuthTokensFromLoginToken": [
- 86,
+ 87,
{
"loginToken": [
1,
@@ -8049,7 +8115,7 @@ export default {
}
],
"getAuthTokensFromOTP": [
- 86,
+ 87,
{
"captchaToken": [
1
@@ -8069,7 +8135,7 @@ export default {
}
],
"getAuthTokensFromSSOExchangeToken": [
- 86,
+ 87,
{
"ssoExchangeToken": [
1,
@@ -8078,7 +8144,7 @@ export default {
}
],
"getAuthTokensFromTwoFactorAuthenticationRecoveryCode": [
- 532,
+ 535,
{
"captchaToken": [
1
@@ -8098,16 +8164,16 @@ export default {
}
],
"getAuthorizationUrlForSSO": [
- 292,
+ 295,
{
"input": [
- 293,
+ 296,
"GetAuthorizationUrlForSSOInput!"
]
}
],
"getLoginTokenFromCredentials": [
- 344,
+ 347,
{
"captchaToken": [
1
@@ -8133,41 +8199,41 @@ export default {
}
],
"goBackToPreviousOnboardingStep": [
- 401
+ 404
],
"grantApplicationCapabilities": [
- 49,
+ 50,
{
"input": [
- 302,
+ 305,
"GrantApplicationCapabilitiesInput!"
]
}
],
"impersonate": [
- 311,
+ 314,
{
"userId": [
- 534,
+ 537,
"UUID!"
],
"workspaceId": [
- 534,
+ 537,
"UUID!"
]
}
],
"ingestAppMessages": [
- 319,
+ 322,
{
"input": [
- 318,
+ 321,
"IngestAppMessagesInput!"
]
}
],
"initiateOTPProvisioning": [
- 321,
+ 324,
{
"loginToken": [
1,
@@ -8180,10 +8246,10 @@ export default {
}
],
"initiateOTPProvisioningForAuthenticatedUser": [
- 321
+ 324
],
"installApplication": [
- 47,
+ 48,
{
"universalIdentifier": [
1,
@@ -8210,7 +8276,7 @@ export default {
4,
{
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8219,19 +8285,19 @@ export default {
4,
{
"channelId": [
- 534
+ 537
],
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
],
"prepareGettingStartedWorkflow": [
- 298,
+ 301,
{
"stepActionKey": [
- 295,
+ 298,
"GettingStartedStepActionKey!"
]
}
@@ -8240,7 +8306,7 @@ export default {
4
],
"releaseEnterpriseServerBinding": [
- 252
+ 253
],
"removeAgentChatMessageReaction": [
23,
@@ -8250,7 +8316,7 @@ export default {
"String!"
],
"messageId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8259,20 +8325,20 @@ export default {
4,
{
"input": [
- 452,
+ 455,
"RemoveQueryFromEventStreamInput!"
]
}
],
"removeRecordShare": [
- 444,
+ 447,
{
"principal": [
- 441,
+ 444,
"RecordSharePrincipalInput!"
],
"target": [
- 448,
+ 451,
"RecordTargetInput!"
]
}
@@ -8281,13 +8347,13 @@ export default {
4,
{
"agentId": [
- 534,
+ 537,
"UUID!"
]
}
],
"renewApplicationToken": [
- 78,
+ 79,
{
"applicationRefreshToken": [
1,
@@ -8296,7 +8362,7 @@ export default {
}
],
"renewToken": [
- 86,
+ 87,
{
"appToken": [
1,
@@ -8308,7 +8374,7 @@ export default {
4,
{
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8317,13 +8383,13 @@ export default {
4,
{
"input": [
- 453,
+ 456,
"ReportAppConnectionAuthFailureInput!"
]
}
],
"resendEmailVerificationToken": [
- 454,
+ 457,
{
"email": [
1,
@@ -8336,7 +8402,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 487,
+ 490,
{
"appTokenId": [
1,
@@ -8345,16 +8411,16 @@ export default {
}
],
"resetCommandMenuItem": [
- 155,
+ 156,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"resetPageLayoutTabToDefault": [
- 406,
+ 409,
{
"id": [
1,
@@ -8363,7 +8429,7 @@ export default {
}
],
"resetPageLayoutToDefault": [
- 405,
+ 408,
{
"id": [
1,
@@ -8372,7 +8438,7 @@ export default {
}
],
"resetPageLayoutWidgetToDefault": [
- 409,
+ 412,
{
"id": [
1,
@@ -8381,22 +8447,22 @@ export default {
}
],
"resetTimelineActivityType": [
- 512,
+ 515,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"retryChatMessage": [
- 479,
+ 482,
{
"modelId": [
1
],
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8405,10 +8471,10 @@ export default {
10
],
"revokeApiKey": [
- 38,
+ 39,
{
"input": [
- 455,
+ 458,
"RevokeApiKeyInput!"
]
}
@@ -8417,7 +8483,7 @@ export default {
4,
{
"applicationAuthorizationId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8426,7 +8492,7 @@ export default {
4,
{
"userId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -8435,13 +8501,13 @@ export default {
4,
{
"userSessionId": [
- 534,
+ 537,
"UUID!"
]
}
],
"rotateApplicationRegistrationClientSecret": [
- 459,
+ 462,
{
"id": [
1,
@@ -8450,37 +8516,37 @@ export default {
}
],
"runAgent": [
- 470,
+ 473,
{
"input": [
- 466,
+ 469,
"RunAgentInput!"
]
}
],
"runApplicationHealthCheck": [
- 63,
+ 64,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
],
"runMyApplicationHealthCheck": [
- 63,
+ 64,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
],
"saveImapSmtpCaldavAccount": [
- 308,
+ 311,
{
"connectionParameters": [
- 238,
+ 239,
"EmailAccountConnectionParameters!"
],
"handle": [
@@ -8488,38 +8554,38 @@ export default {
"String!"
],
"id": [
- 534
+ 537
]
}
],
"sendAppChannelMessage": [
- 478,
+ 481,
{
"input": [
- 477,
+ 480,
"SendAppChannelMessageInput!"
]
}
],
"sendChatMessage": [
- 479,
+ 482,
{
"browsingContext": [
- 324
+ 327
],
"channelId": [
- 534
+ 537
],
"fileAttachments": [
- 279,
+ 280,
"[FileAttachmentInput!]"
],
"mentionedWorkspaceMemberIds": [
- 534,
+ 537,
"[UUID!]"
],
"messageId": [
- 534,
+ 537,
"UUID!"
],
"modelId": [
@@ -8533,70 +8599,70 @@ export default {
"String!"
],
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
],
"sendEmail": [
- 482,
+ 485,
{
"input": [
- 481,
+ 484,
"SendEmailInput!"
]
}
],
"sendInboxMessage": [
- 486,
+ 489,
{
"input": [
- 485,
+ 488,
"SendInboxMessageInput!"
]
}
],
"sendInvitations": [
- 487,
+ 490,
{
"emails": [
1,
"[String!]!"
],
"roleId": [
- 534
+ 537
]
}
],
"sendMessageCampaign": [
- 489,
+ 492,
{
"input": [
- 488,
+ 491,
"SendMessageCampaignInput!"
]
}
],
"sendMessageCampaignTest": [
- 484,
+ 487,
{
"input": [
- 490,
+ 493,
"SendMessageCampaignTestInput!"
]
}
],
"setAppKeyValue": [
- 42,
+ 43,
{
"input": [
- 492,
+ 495,
"SetAppKeyValueInput!"
]
}
],
"setEnterpriseKey": [
- 252,
+ 253,
{
"enterpriseKey": [
1,
@@ -8605,37 +8671,37 @@ export default {
}
],
"setRecordPrivate": [
- 444,
+ 447,
{
"isPrivate": [
4,
"Boolean!"
],
"target": [
- 448,
+ 451,
"RecordTargetInput!"
]
}
],
"setRecordShare": [
- 444,
+ 447,
{
"accessLevel": [
- 440,
+ 443,
"RecordShareAccessLevel!"
],
"principal": [
- 441,
+ 444,
"RecordSharePrincipalInput!"
],
"target": [
- 448,
+ 451,
"RecordTargetInput!"
]
}
],
"setResourceCreditSubscriptionPrice": [
- 125,
+ 126,
{
"priceId": [
1,
@@ -8644,7 +8710,7 @@ export default {
}
],
"signIn": [
- 91,
+ 92,
{
"captchaToken": [
1
@@ -8674,7 +8740,7 @@ export default {
}
],
"signUp": [
- 91,
+ 92,
{
"captchaToken": [
1
@@ -8696,15 +8762,15 @@ export default {
}
],
"signUpInNewWorkspace": [
- 498,
+ 501,
{
"input": [
- 499
+ 502
]
}
],
"signUpInWorkspace": [
- 498,
+ 501,
{
"captchaToken": [
1
@@ -8724,7 +8790,7 @@ export default {
1
],
"workspaceId": [
- 534
+ 537
],
"workspaceInviteHash": [
1
@@ -8735,7 +8801,7 @@ export default {
}
],
"skipSyncEmailOnboardingStep": [
- 402,
+ 405,
{
"isAutoSkipped": [
4,
@@ -8747,32 +8813,32 @@ export default {
4,
{
"snoozedUntil": [
- 212,
+ 213,
"DateTime!"
],
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
],
"startChannelSync": [
- 141,
+ 142,
{
"connectedAccountId": [
- 534,
+ 537,
"UUID!"
]
}
],
"startWorkspaceSetupChat": [
- 502,
+ 505,
{
"companyContext": [
- 324
+ 327
],
"personContext": [
- 324
+ 327
]
}
],
@@ -8780,36 +8846,36 @@ export default {
4,
{
"threadId": [
- 534,
+ 537,
"UUID!"
]
}
],
"stopImpersonation": [
- 503
+ 506
],
"switchBillingPlan": [
- 125,
+ 126,
{
"plan": [
- 109
+ 110
]
}
],
"switchSubscriptionInterval": [
- 125
+ 126
],
"syncAppMessageFolders": [
- 362,
+ 365,
{
"input": [
- 510,
+ 513,
"SyncAppMessageFoldersInput!"
]
}
],
"syncApplication": [
- 684,
+ 687,
{
"dryRun": [
4
@@ -8818,7 +8884,7 @@ export default {
4
],
"manifest": [
- 324,
+ 327,
"JSON!"
]
}
@@ -8827,7 +8893,7 @@ export default {
4
],
"trackAnalytics": [
- 35,
+ 36,
{
"event": [
1
@@ -8836,16 +8902,16 @@ export default {
1
],
"properties": [
- 324
+ 327
],
"type": [
- 36,
+ 37,
"AnalyticsType!"
]
}
],
"transferApplicationRegistrationOwnership": [
- 73,
+ 74,
{
"applicationRegistrationId": [
1,
@@ -8858,55 +8924,55 @@ export default {
}
],
"triggerAddPeopleToMessageListJob": [
- 519,
+ 522,
{
"input": [
- 518,
+ 521,
"TriggerAddPeopleToMessageListJobInput!"
]
}
],
"triggerInstallApplication": [
- 523,
+ 526,
{
"input": [
- 520,
+ 523,
"TriggerInstallApplicationInput!"
]
}
],
"triggerInstallApplicationJob": [
- 522,
+ 525,
{
"input": [
- 521,
+ 524,
"TriggerInstallApplicationJobInput!"
]
}
],
"triggerUninstallApplication": [
- 527,
+ 530,
{
"input": [
- 524,
+ 527,
"TriggerUninstallApplicationInput!"
]
}
],
"triggerUninstallApplicationJob": [
- 526,
+ 529,
{
"input": [
- 525,
+ 528,
"TriggerUninstallApplicationJobInput!"
]
}
],
"triggerUpgradeApplication": [
- 529,
+ 532,
{
"input": [
- 528,
+ 531,
"TriggerUpgradeApplicationInput!"
]
}
@@ -8924,11 +8990,11 @@ export default {
5,
{
"channelId": [
- 534,
+ 537,
"UUID!"
],
"input": [
- 539,
+ 542,
"UpdateAgentChatChannelInput!"
]
}
@@ -8941,176 +9007,176 @@ export default {
"AgentChatInboxAction!"
],
"snoozedUntil": [
- 212
+ 213
],
"threadIds": [
- 534,
+ 537,
"[UUID!]!"
]
}
],
"updateApiKey": [
- 38,
+ 39,
{
"input": [
- 541,
+ 544,
"UpdateApiKeyInput!"
]
}
],
"updateAppMessageChannel": [
- 355,
+ 358,
{
"input": [
- 542,
+ 545,
"UpdateAppMessageChannelInput!"
]
}
],
"updateApplication": [
- 47,
+ 48,
{
"id": [
- 534,
+ 537,
"UUID!"
],
"input": [
- 543,
+ 546,
"UpdateApplicationInput!"
]
}
],
"updateApplicationRegistration": [
- 73,
+ 74,
{
"input": [
- 544,
+ 547,
"UpdateApplicationRegistrationInput!"
]
}
],
"updateApplicationRegistrationVariable": [
- 77,
+ 78,
{
"input": [
- 546,
+ 549,
"UpdateApplicationRegistrationVariableInput!"
]
}
],
"updateCalendarChannel": [
- 128,
+ 129,
{
"input": [
- 548,
+ 551,
"UpdateCalendarChannelInput!"
]
}
],
"updateCommandMenuItem": [
- 155,
+ 156,
{
"input": [
- 550,
+ 553,
"UpdateCommandMenuItemInput!"
]
}
],
"updateEmailGroupChannel": [
- 355,
+ 358,
{
"input": [
- 551,
+ 554,
"UpdateEmailGroupChannelInput!"
]
}
],
"updateFrontComponent": [
- 287,
+ 288,
{
"input": [
- 553,
+ 556,
"UpdateFrontComponentInput!"
]
}
],
"updateGettingStarted": [
- 294,
+ 297,
{
"input": [
- 555,
+ 558,
"UpdateGettingStartedInput!"
]
}
],
"updateLabPublicFeatureFlag": [
- 265,
+ 266,
{
"input": [
- 556,
+ 559,
"UpdateLabPublicFeatureFlagInput!"
]
}
],
"updateManyNavigationMenuItems": [
- 382,
+ 385,
{
"inputs": [
- 569,
+ 572,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
],
"updateManyObjects": [
- 385,
+ 388,
{
"inputs": [
- 570,
+ 573,
"[UpdateOneObjectInput!]!"
]
}
],
"updateManyViewGroups": [
- 655,
+ 658,
{
"inputs": [
- 592,
+ 595,
"[UpdateViewGroupInput!]!"
]
}
],
"updateMcpServer": [
- 351,
+ 354,
{
"input": [
- 559,
+ 562,
"UpdateMcpServerInput!"
]
}
],
"updateMessageChannel": [
- 355,
+ 358,
{
"input": [
- 561,
+ 564,
"UpdateMessageChannelInput!"
]
}
],
"updateMessageFolder": [
- 362,
+ 365,
{
"input": [
- 563,
+ 566,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 362,
+ 365,
{
"input": [
- 565,
+ 568,
"UpdateMessageFoldersInput!"
]
}
@@ -9133,10 +9199,10 @@ export default {
}
],
"updateNavigationMenuItem": [
- 382,
+ 385,
{
"input": [
- 569,
+ 572,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -9145,7 +9211,7 @@ export default {
3,
{
"input": [
- 540,
+ 543,
"UpdateAgentInput!"
]
}
@@ -9154,7 +9220,7 @@ export default {
4,
{
"applicationId": [
- 534
+ 537
],
"key": [
1,
@@ -9167,10 +9233,10 @@ export default {
}
],
"updateOneField": [
- 267,
+ 268,
{
"input": [
- 568,
+ 571,
"UpdateOneFieldMetadataInput!"
]
}
@@ -9179,83 +9245,83 @@ export default {
4,
{
"input": [
- 557,
+ 560,
"UpdateLogicFunctionFromSourceInput!"
]
}
],
"updateOneObject": [
- 385,
+ 388,
{
"input": [
- 570,
+ 573,
"UpdateOneObjectInput!"
]
}
],
"updateOneRole": [
- 457,
+ 460,
{
"updateRoleInput": [
- 577,
+ 580,
"UpdateRoleInput!"
]
}
],
"updatePageLayout": [
- 405,
+ 408,
{
"id": [
1,
"String!"
],
"input": [
- 571,
+ 574,
"UpdatePageLayoutInput!"
]
}
],
"updatePageLayoutTab": [
- 406,
+ 409,
{
"id": [
1,
"String!"
],
"input": [
- 572,
+ 575,
"UpdatePageLayoutTabInput!"
]
}
],
"updatePageLayoutWidget": [
- 409,
+ 412,
{
"id": [
1,
"String!"
],
"input": [
- 574,
+ 577,
"UpdatePageLayoutWidgetInput!"
]
}
],
"updatePageLayoutWithTabsAndWidgets": [
- 405,
+ 408,
{
"id": [
1,
"String!"
],
"input": [
- 576,
+ 579,
"UpdatePageLayoutWithTabsInput!"
]
}
],
"updatePasswordViaResetToken": [
- 322,
+ 325,
{
"newPassword": [
1,
@@ -9268,46 +9334,46 @@ export default {
}
],
"updateSkill": [
- 500,
+ 503,
{
"input": [
- 579,
+ 582,
"UpdateSkillInput!"
]
}
],
"updateTimelineActivityType": [
- 512,
+ 515,
{
"input": [
- 580,
+ 583,
"UpdateTimelineActivityTypeInput!"
]
}
],
"updateUnsubscribeTopic": [
- 537,
+ 540,
{
"input": [
- 581,
+ 584,
"UpdateUnsubscribeTopicInput!"
]
}
],
"updateUsageLimit": [
- 621,
+ 624,
{
"input": [
- 582,
+ 585,
"UpdateUsageLimitInput!"
]
}
],
"updateUserCreditsFallback": [
- 101,
+ 102,
{
"userCreditsFallback": [
- 636,
+ 639,
"UserCreditsFallback!"
]
}
@@ -9325,130 +9391,130 @@ export default {
}
],
"updateValidationRule": [
- 641,
+ 644,
{
"input": [
- 583,
+ 586,
"UpdateValidationRuleInput!"
]
}
],
"updateView": [
- 646,
+ 649,
{
"id": [
1,
"String!"
],
"input": [
- 594,
+ 597,
"UpdateViewInput!"
]
}
],
"updateViewField": [
- 649,
+ 652,
{
"input": [
- 587,
+ 590,
"UpdateViewFieldInput!"
]
}
],
"updateViewFieldGroup": [
- 650,
+ 653,
{
"input": [
- 585,
+ 588,
"UpdateViewFieldGroupInput!"
]
}
],
"updateViewFilter": [
- 651,
+ 654,
{
"input": [
- 590,
+ 593,
"UpdateViewFilterInput!"
]
}
],
"updateViewFilterGroup": [
- 652,
+ 655,
{
"id": [
1,
"String!"
],
"input": [
- 589,
+ 592,
"UpdateViewFilterGroupInput!"
]
}
],
"updateViewGroup": [
- 655,
+ 658,
{
"input": [
- 592,
+ 595,
"UpdateViewGroupInput!"
]
}
],
"updateViewSort": [
- 658,
+ 661,
{
"input": [
- 595,
+ 598,
"UpdateViewSortInput!"
]
}
],
"updateWebhook": [
- 662,
+ 665,
{
"input": [
- 597,
+ 600,
"UpdateWebhookInput!"
]
}
],
"updateWorkspace": [
- 670,
+ 673,
{
"data": [
- 601,
+ 604,
"UpdateWorkspaceInput!"
]
}
],
"updateWorkspaceAllowedEmbeddingOrigins": [
- 670,
+ 673,
{
"data": [
- 599,
+ 602,
"UpdateWorkspaceAllowedEmbeddingOriginsInput!"
]
}
],
"updateWorkspaceIframeMediaPermissions": [
- 670,
+ 673,
{
"data": [
- 600,
+ 603,
"UpdateWorkspaceIframeMediaPermissionsInput!"
]
}
],
"updateWorkspaceMemberRole": [
- 679,
+ 682,
{
"roleId": [
- 534,
+ 537,
"UUID!"
],
"workspaceMemberId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -9457,7 +9523,7 @@ export default {
4,
{
"input": [
- 602,
+ 605,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -9476,10 +9542,10 @@ export default {
}
],
"uploadAppTarball": [
- 73,
+ 74,
{
"file": [
- 603,
+ 606,
"Upload!"
],
"universalIdentifier": [
@@ -9488,18 +9554,18 @@ export default {
}
],
"uploadApplicationFile": [
- 278,
+ 279,
{
"applicationUniversalIdentifier": [
1,
"String!"
],
"file": [
- 603,
+ 606,
"Upload!"
],
"fileFolder": [
- 280,
+ 281,
"FileFolder!"
],
"filePath": [
@@ -9509,23 +9575,23 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 282,
+ 283,
{
"fieldMetadataUniversalIdentifier": [
1,
"String!"
],
"file": [
- 603,
+ 606,
"Upload!"
]
}
],
"uploadNewWorkspaceLogo": [
- 282,
+ 283,
{
"file": [
- 603,
+ 606,
"Upload!"
],
"workspaceId": [
@@ -9535,88 +9601,88 @@ export default {
}
],
"uploadWorkspaceLogo": [
- 282,
+ 283,
{
"file": [
- 603,
+ 606,
"Upload!"
]
}
],
"uploadWorkspaceMemberProfilePicture": [
- 282,
+ 283,
{
"file": [
- 603,
+ 606,
"Upload!"
]
}
],
"upsertFieldPermissions": [
- 274,
+ 275,
{
"upsertFieldPermissionsInput": [
- 604,
+ 607,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertFieldsWidget": [
- 646,
+ 649,
{
"input": [
- 607,
+ 610,
"UpsertFieldsWidgetInput!"
]
}
],
"upsertObjectPermissions": [
- 393,
+ 396,
{
"upsertObjectPermissionsInput": [
- 608,
+ 611,
"UpsertObjectPermissionsInput!"
]
}
],
"upsertPermissionFlags": [
- 458,
+ 461,
{
"upsertPermissionFlagsInput": [
- 609,
+ 612,
"UpsertPermissionFlagsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 611,
+ 614,
{
"input": [
- 610,
+ 613,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
],
"upsertViewWidget": [
- 646,
+ 649,
{
"input": [
- 612,
+ 615,
"UpsertViewWidgetInput!"
]
}
],
"validateApprovedAccessDomain": [
- 81,
+ 82,
{
"input": [
- 639,
+ 642,
"ValidateApprovedAccessDomainInput!"
]
}
],
"verifyEmailAndGetLoginToken": [
- 643,
+ 646,
{
"captchaToken": [
1
@@ -9636,7 +9702,7 @@ export default {
}
],
"verifyEmailAndGetWorkspaceAgnosticToken": [
- 91,
+ 92,
{
"captchaToken": [
1
@@ -9652,7 +9718,7 @@ export default {
}
],
"verifyEmailingDomain": [
- 242,
+ 243,
{
"id": [
1,
@@ -9661,7 +9727,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 644,
+ 647,
{
"otp": [
1,
@@ -9686,25 +9752,25 @@ export default {
},
"NavigationMenuItem": {
"agentChatChannelId": [
- 534
+ 537
],
"applicationId": [
- 534
+ 537
],
"color": [
1
],
"createdAt": [
- 212
+ 213
],
"folderId": [
- 534
+ 537
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"link": [
1
@@ -9713,31 +9779,31 @@ export default {
1
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
],
"targetObjectMetadataId": [
- 534
+ 537
],
"targetRecordId": [
- 534
+ 537
],
"targetRecordIdentifier": [
- 437
+ 440
],
"type": [
- 383
+ 386
],
"updatedAt": [
- 212
+ 213
],
"userWorkspaceId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -9746,7 +9812,7 @@ export default {
"NavigationMenuItemType": {},
"NotesConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -9754,13 +9820,13 @@ export default {
},
"Object": {
"applicationId": [
- 534
+ 537
],
"color": [
1
],
"createdAt": [
- 212
+ 213
],
"description": [
1
@@ -9772,42 +9838,42 @@ export default {
1
],
"fields": [
- 388,
+ 391,
{
"filter": [
- 272,
+ 273,
"FieldFilter!"
],
"paging": [
- 210,
+ 211,
"CursorPaging!"
]
}
],
"fieldsList": [
- 267
+ 268
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"imageIdentifierFieldMetadataId": [
- 534
+ 537
],
"indexMetadataList": [
- 313
+ 316
],
"indexMetadatas": [
- 390,
+ 393,
{
"filter": [
- 316,
+ 319,
"IndexFilter!"
],
"paging": [
- 210,
+ 211,
"CursorPaging!"
]
}
@@ -9840,7 +9906,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 534
+ 537
],
"labelPlural": [
1
@@ -9855,10 +9921,10 @@ export default {
1
],
"openRecordIn": [
- 392
+ 395
],
"searchFieldMetadataList": [
- 476
+ 479
],
"shortcut": [
1
@@ -9867,7 +9933,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -9875,10 +9941,10 @@ export default {
},
"ObjectConnection": {
"edges": [
- 387
+ 390
],
"pageInfo": [
- 404
+ 407
],
"__typename": [
1
@@ -9886,10 +9952,10 @@ export default {
},
"ObjectEdge": {
"cursor": [
- 162
+ 163
],
"node": [
- 385
+ 388
],
"__typename": [
1
@@ -9897,10 +9963,10 @@ export default {
},
"ObjectFieldsConnection": {
"edges": [
- 271
+ 272
],
"pageInfo": [
- 404
+ 407
],
"__typename": [
1
@@ -9908,37 +9974,37 @@ export default {
},
"ObjectFilter": {
"and": [
- 389
+ 392
],
"id": [
- 535
+ 538
],
"isActive": [
- 127
+ 128
],
"isRemote": [
- 127
+ 128
],
"isSearchable": [
- 127
+ 128
],
"isSystem": [
- 127
+ 128
],
"isUICreatable": [
- 127
+ 128
],
"isUIEditable": [
- 127
+ 128
],
"isUIReadOnly": [
- 127
+ 128
],
"or": [
- 389
+ 392
],
"universalIdentifier": [
- 535
+ 538
],
"__typename": [
1
@@ -9946,10 +10012,10 @@ export default {
},
"ObjectIndexMetadatasConnection": {
"edges": [
- 314
+ 317
],
"pageInfo": [
- 404
+ 407
],
"__typename": [
1
@@ -9957,7 +10023,7 @@ export default {
},
"ObjectMetadataCommandMenuItemPayload": {
"objectMetadataItemId": [
- 534
+ 537
],
"__typename": [
1
@@ -9978,16 +10044,16 @@ export default {
4
],
"objectMetadataId": [
- 534
+ 537
],
"restrictedFields": [
- 324
+ 327
],
"rowLevelPermissionPredicateGroups": [
- 461
+ 464
],
"rowLevelPermissionPredicates": [
- 460
+ 463
],
"__typename": [
1
@@ -10007,7 +10073,7 @@ export default {
4
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -10026,13 +10092,13 @@ export default {
},
"ObjectRecordEvent": {
"action": [
- 211
+ 212
],
"objectNameSingular": [
1
],
"properties": [
- 397
+ 400
],
"recordId": [
1
@@ -10049,13 +10115,13 @@ export default {
},
"ObjectRecordEventProperties": {
"after": [
- 324
+ 327
],
"before": [
- 324
+ 327
],
"diff": [
- 324
+ 327
],
"updatedFields": [
1
@@ -10066,7 +10132,7 @@ export default {
},
"ObjectRecordEventWithQueryIds": {
"objectRecordEvent": [
- 396
+ 399
],
"queryIds": [
1
@@ -10079,10 +10145,10 @@ export default {
"OnboardingStatus": {},
"OnboardingStepNavigation": {
"onboardingStatus": [
- 400
+ 403
],
"previousOnboardingStatus": [
- 400
+ 403
],
"__typename": [
1
@@ -10099,7 +10165,7 @@ export default {
"OpenRecordIn": {},
"PageInfo": {
"endCursor": [
- 162
+ 163
],
"hasNextPage": [
4
@@ -10108,7 +10174,7 @@ export default {
4
],
"startCursor": [
- 162
+ 163
],
"__typename": [
1
@@ -10116,19 +10182,19 @@ export default {
},
"PageLayout": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"defaultTabToFocusOnMobileAndSidePanelId": [
- 534
+ 537
],
"deletedAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"isFirstTabPinned": [
4
@@ -10140,19 +10206,19 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"tabs": [
- 406
+ 409
],
"type": [
- 408
+ 411
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -10160,19 +10226,19 @@ export default {
},
"PageLayoutTab": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -10184,10 +10250,10 @@ export default {
4
],
"layoutMode": [
- 407
+ 410
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
@@ -10196,13 +10262,13 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"widgets": [
- 409
+ 412
],
"__typename": [
1
@@ -10212,28 +10278,28 @@ export default {
"PageLayoutType": {},
"PageLayoutWidget": {
"applicationId": [
- 534
+ 537
],
"conditionalAvailabilityExpression": [
1
],
"conditionalDisplay": [
- 324
+ 327
],
"configuration": [
- 663
+ 666
],
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"gridPosition": [
- 304
+ 307
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -10245,25 +10311,25 @@ export default {
4
],
"objectMetadataId": [
- 534
+ 537
],
"pageLayoutTabId": [
- 534
+ 537
],
"position": [
- 412
+ 415
],
"title": [
1
],
"type": [
- 665
+ 668
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -10271,7 +10337,7 @@ export default {
},
"PageLayoutWidgetCanvasPosition": {
"layoutMode": [
- 407
+ 410
],
"__typename": [
1
@@ -10285,7 +10351,7 @@ export default {
10
],
"layoutMode": [
- 407
+ 410
],
"row": [
10
@@ -10299,13 +10365,13 @@ export default {
},
"PageLayoutWidgetPosition": {
"on_PageLayoutWidgetCanvasPosition": [
- 410
+ 413
],
"on_PageLayoutWidgetGridPosition": [
- 411
+ 414
],
"on_PageLayoutWidgetVerticalListPosition": [
- 414
+ 417
],
"__typename": [
1
@@ -10314,13 +10380,13 @@ export default {
"PageLayoutWidgetVerticalListHeightBehavior": {},
"PageLayoutWidgetVerticalListPosition": {
"heightBehavior": [
- 413
+ 416
],
"index": [
10
],
"layoutMode": [
- 407
+ 410
],
"__typename": [
1
@@ -10336,10 +10402,10 @@ export default {
},
"PermissionFlag": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"description": [
1
@@ -10348,7 +10414,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"key": [
1
@@ -10360,10 +10426,10 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -10372,7 +10438,7 @@ export default {
"PermissionFlagType": {},
"PieChartConfiguration": {
"aggregateFieldMetadataId": [
- 534
+ 537
],
"aggregateOperation": [
27
@@ -10381,10 +10447,10 @@ export default {
1
],
"configurationType": [
- 664
+ 667
],
"dateGranularity": [
- 399
+ 402
],
"description": [
1
@@ -10396,13 +10462,13 @@ export default {
4
],
"filter": [
- 324
+ 327
],
"firstDayOfTheWeek": [
10
],
"groupByFieldMetadataId": [
- 534
+ 537
],
"groupBySubFieldName": [
1
@@ -10414,10 +10480,10 @@ export default {
1
],
"numberFormat": [
- 142
+ 143
],
"orderBy": [
- 303
+ 306
],
"showCenterMetric": [
4
@@ -10434,10 +10500,10 @@ export default {
},
"PieChartData": {
"data": [
- 421
+ 424
],
"formattedToRawLookup": [
- 324
+ 327
],
"hasTooManyGroups": [
4
@@ -10457,10 +10523,10 @@ export default {
},
"PieChartDataInput": {
"configuration": [
- 324
+ 327
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -10485,7 +10551,7 @@ export default {
1
],
"location": [
- 336
+ 339
],
"postcode": [
1
@@ -10516,7 +10582,7 @@ export default {
1
],
"scheduledAt": [
- 212
+ 213
],
"__typename": [
1
@@ -10524,10 +10590,10 @@ export default {
},
"PreviewMessageCampaignSendOutputDTO": {
"audience": [
- 136
+ 137
],
"blockers": [
- 354
+ 357
],
"__typename": [
1
@@ -10535,7 +10601,7 @@ export default {
},
"PublicApplicationRegistration": {
"id": [
- 534
+ 537
],
"logoUrl": [
1
@@ -10555,7 +10621,7 @@ export default {
},
"PublicConnectionParametersOutput": {
"connectionSecurity": [
- 239
+ 240
],
"host": [
1
@@ -10572,16 +10638,16 @@ export default {
},
"PublicDomain": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"domain": [
1
],
"id": [
- 534
+ 537
],
"isValidated": [
4
@@ -10592,10 +10658,10 @@ export default {
},
"PublicFeatureFlag": {
"key": [
- 266
+ 267
],
"metadata": [
- 430
+ 433
],
"__typename": [
1
@@ -10620,13 +10686,13 @@ export default {
},
"PublicImapSmtpCaldavConnectionParameters": {
"CALDAV": [
- 427
+ 430
],
"IMAP": [
- 427
+ 430
],
"SMTP": [
- 427
+ 430
],
"__typename": [
1
@@ -10634,22 +10700,22 @@ export default {
},
"PublicWorkspaceData": {
"authBypassProviders": [
- 82
+ 83
],
"authProviders": [
- 83
+ 84
],
"displayName": [
1
],
"id": [
- 534
+ 537
],
"logo": [
1
],
"workspaceUrls": [
- 688
+ 691
],
"__typename": [
1
@@ -10660,7 +10726,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"logo": [
1
@@ -10686,7 +10752,7 @@ export default {
7
],
"channelId": [
- 534,
+ 537,
"UUID!"
],
"filter": [
@@ -10710,7 +10776,7 @@ export default {
24,
{
"agentId": [
- 534,
+ 537,
"UUID!"
],
"limit": [
@@ -10726,19 +10792,19 @@ export default {
30
],
"apiKey": [
- 38,
+ 39,
{
"input": [
- 291,
+ 294,
"GetApiKeyInput!"
]
}
],
"apiKeys": [
- 38
+ 39
],
"appConnection": [
- 41,
+ 42,
{
"id": [
18,
@@ -10747,55 +10813,55 @@ export default {
}
],
"appConnections": [
- 41,
+ 42,
{
"filter": [
- 333
+ 336
]
}
],
"appKeyValue": [
- 42,
+ 43,
{
"key": [
1,
"String!"
],
"scope": [
- 43
+ 44
]
}
],
"appMessageChannels": [
- 355,
+ 358,
{
"filter": [
- 334
+ 337
]
}
],
"appMessageFolders": [
- 362,
+ 365,
{
"filter": [
- 335
+ 338
]
}
],
"applicationConnectedAccounts": [
- 50,
+ 51,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
],
"applicationConnectionProviders": [
- 51,
+ 52,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -10819,28 +10885,28 @@ export default {
}
],
"applicationSdkClientChecksums": [
- 475,
+ 478,
{
"applicationId": [
- 534,
+ 537,
"UUID!"
]
}
],
"barChartData": [
- 94,
+ 95,
{
"input": [
- 95,
+ 96,
"BarChartDataInput!"
]
}
],
"billingPlans": [
- 108
+ 109
],
"billingPortalSession": [
- 118,
+ 119,
{
"forPaymentMethodUpdate": [
4
@@ -10851,10 +10917,10 @@ export default {
}
],
"callRecordingIdForCalendarEvent": [
- 534,
+ 537,
{
"calendarEventId": [
- 534,
+ 537,
"UUID!"
]
}
@@ -10862,18 +10928,28 @@ export default {
"chatMessages": [
21,
{
+ "agentUniversalIdentifier": [
+ 537
+ ],
"threadId": [
- 534,
- "UUID!"
- ]
+ 537
+ ],
+ "threadKey": [
+ 1
+ ]
}
],
"chatStreamCatchupChunks": [
- 144,
+ 145,
{
+ "agentUniversalIdentifier": [
+ 537
+ ],
"threadId": [
- 534,
- "UUID!"
+ 537
+ ],
+ "threadKey": [
+ 1
]
}
],
@@ -10881,13 +10957,13 @@ export default {
17,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"checkUserExists": [
- 147,
+ 148,
{
"captchaToken": [
1
@@ -10899,7 +10975,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 678,
+ 681,
{
"inviteHash": [
1,
@@ -10908,7 +10984,7 @@ export default {
}
],
"checkWorkspaceSubdomainAvailability": [
- 504,
+ 507,
{
"subdomain": [
1,
@@ -10917,28 +10993,28 @@ export default {
}
],
"commandMenuItem": [
- 155,
+ 156,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"commandMenuItems": [
- 155
+ 156
],
"currentUser": [
- 634
+ 637
],
"currentUserApplicationAuthorizations": [
- 48
+ 49
],
"currentUserSessions": [
- 637
+ 640
],
"currentWorkspace": [
- 670
+ 673
],
"enterpriseCheckoutSession": [
1,
@@ -10957,53 +11033,53 @@ export default {
}
],
"enterpriseSubscriptionStatus": [
- 253
+ 254
],
"eventLogs": [
- 260,
+ 261,
{
"input": [
- 259,
+ 260,
"EventLogQueryInput!"
]
}
],
"exportApplication": [
- 53,
+ 54,
{
"shouldIncludeDependencies": [
4
],
"universalIdentifier": [
- 534,
+ 537,
"UUID!"
]
}
],
"field": [
- 267,
+ 268,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"fields": [
- 269,
+ 270,
{
"filter": [
- 272,
+ 273,
"FieldFilter!"
],
"paging": [
- 210,
+ 211,
"CursorPaging!"
]
}
],
"findApplicationRegistrationByClientId": [
- 426,
+ 429,
{
"clientId": [
1,
@@ -11012,7 +11088,7 @@ export default {
}
],
"findApplicationRegistrationByUniversalIdentifier": [
- 73,
+ 74,
{
"universalIdentifier": [
1,
@@ -11021,37 +11097,37 @@ export default {
}
],
"findApplicationRegistrationMonitoring": [
- 65,
+ 66,
{
"id": [
1,
"String!"
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
]
}
],
"findApplicationRegistrationStats": [
- 75,
+ 76,
{
"id": [
1,
"String!"
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
]
}
],
"findApplicationRegistrationVariables": [
- 77,
+ 78,
{
"applicationRegistrationId": [
1,
@@ -11060,7 +11136,7 @@ export default {
}
],
"findClaimableApplicationRegistration": [
- 148,
+ 149,
{
"sourcePackage": [
1
@@ -11071,7 +11147,7 @@ export default {
}
],
"findInstallApplicationJobStatus": [
- 327,
+ 330,
{
"jobId": [
1
@@ -11086,16 +11162,16 @@ export default {
3
],
"findManyApplicationRegistrations": [
- 73
+ 74
],
"findManyApplications": [
- 47
+ 48
],
"findManyLogicFunctions": [
- 337
+ 340
],
"findManyMarketplaceApps": [
- 345,
+ 348,
{
"universalIdentifiers": [
1,
@@ -11104,10 +11180,10 @@ export default {
}
],
"findManyPublicDomains": [
- 428
+ 431
],
"findMarketplaceAppDetail": [
- 346,
+ 349,
{
"universalIdentifier": [
1,
@@ -11125,18 +11201,18 @@ export default {
}
],
"findOneApplication": [
- 47,
+ 48,
{
"id": [
- 534
+ 537
],
"universalIdentifier": [
- 534
+ 537
]
}
],
"findOneApplicationRegistration": [
- 73,
+ 74,
{
"id": [
1,
@@ -11145,16 +11221,16 @@ export default {
}
],
"findOneLogicFunction": [
- 337,
+ 340,
{
"input": [
- 341,
+ 344,
"LogicFunctionIdInput!"
]
}
],
"findUninstallApplicationJobStatus": [
- 327,
+ 330,
{
"jobId": [
1
@@ -11166,7 +11242,7 @@ export default {
}
],
"findUpgradeApplicationJobStatus": [
- 327,
+ 330,
{
"jobId": [
1
@@ -11178,10 +11254,10 @@ export default {
}
],
"findWorkspaceAiStats": [
- 672
+ 675
],
"findWorkspaceFromInviteHash": [
- 670,
+ 673,
{
"inviteHash": [
1,
@@ -11190,22 +11266,22 @@ export default {
}
],
"findWorkspaceInvitations": [
- 677
+ 680
],
"frontComponent": [
- 287,
+ 288,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"frontComponents": [
- 287
+ 288
],
"getAddressDetails": [
- 422,
+ 425,
{
"placeId": [
1,
@@ -11218,16 +11294,16 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 32
+ 33
],
"getApiKeyRoles": [
- 457
+ 460
],
"getApprovedAccessDomains": [
- 81
+ 82
],
"getAutoCompleteAddress": [
- 88,
+ 89,
{
"address": [
1,
@@ -11246,31 +11322,31 @@ export default {
}
],
"getAvailablePackages": [
- 324,
+ 327,
{
"input": [
- 341,
+ 344,
"LogicFunctionIdInput!"
]
}
],
"getConnectedImapSmtpCaldavAccount": [
- 161,
+ 162,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"getEmailingDomains": [
- 242
+ 243
],
"getInviteSuggestions": [
- 323
+ 326
],
"getJobs": [
- 327,
+ 330,
{
"jobIds": [
1,
@@ -11282,13 +11358,13 @@ export default {
1,
{
"input": [
- 341,
+ 344,
"LogicFunctionIdInput!"
]
}
],
"getPageLayout": [
- 405,
+ 408,
{
"id": [
1,
@@ -11297,7 +11373,7 @@ export default {
}
],
"getPageLayoutTab": [
- 406,
+ 409,
{
"id": [
1,
@@ -11306,7 +11382,7 @@ export default {
}
],
"getPageLayoutTabs": [
- 406,
+ 409,
{
"pageLayoutId": [
1,
@@ -11315,7 +11391,7 @@ export default {
}
],
"getPageLayoutWidget": [
- 409,
+ 412,
{
"id": [
1,
@@ -11324,7 +11400,7 @@ export default {
}
],
"getPageLayoutWidgets": [
- 409,
+ 412,
{
"pageLayoutTabId": [
1,
@@ -11333,21 +11409,21 @@ export default {
}
],
"getPageLayouts": [
- 405,
+ 408,
{
"objectMetadataId": [
1
],
"pageLayoutType": [
- 408
+ 411
]
}
],
"getPermissionFlags": [
- 416
+ 419
],
"getPublicWorkspaceDataByDomain": [
- 432,
+ 435,
{
"origin": [
1
@@ -11355,37 +11431,37 @@ export default {
}
],
"getPublicWorkspaceDataById": [
- 433,
+ 436,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"getResourceCreditUsage": [
- 117
+ 118
],
"getRole": [
- 457,
+ 460,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"getRoles": [
- 457
+ 460
],
"getSSOIdentityProviders": [
- 284
+ 285
],
"getToolIndex": [
- 516
+ 519
],
"getToolInputSchema": [
- 324,
+ 327,
{
"toolName": [
1,
@@ -11394,15 +11470,15 @@ export default {
}
],
"getUsageAnalytics": [
- 618,
+ 621,
{
"input": [
- 619
+ 622
]
}
],
"getView": [
- 646,
+ 649,
{
"id": [
1,
@@ -11411,7 +11487,7 @@ export default {
}
],
"getViewField": [
- 649,
+ 652,
{
"id": [
1,
@@ -11420,7 +11496,7 @@ export default {
}
],
"getViewFieldGroup": [
- 650,
+ 653,
{
"id": [
1,
@@ -11429,7 +11505,7 @@ export default {
}
],
"getViewFieldGroups": [
- 650,
+ 653,
{
"viewId": [
1,
@@ -11438,7 +11514,7 @@ export default {
}
],
"getViewFields": [
- 649,
+ 652,
{
"viewId": [
1,
@@ -11447,7 +11523,7 @@ export default {
}
],
"getViewFilter": [
- 651,
+ 654,
{
"id": [
1,
@@ -11456,7 +11532,7 @@ export default {
}
],
"getViewFilterGroup": [
- 652,
+ 655,
{
"id": [
1,
@@ -11465,7 +11541,7 @@ export default {
}
],
"getViewFilterGroups": [
- 652,
+ 655,
{
"viewId": [
1
@@ -11473,7 +11549,7 @@ export default {
}
],
"getViewFilters": [
- 651,
+ 654,
{
"viewId": [
1
@@ -11481,7 +11557,7 @@ export default {
}
],
"getViewGroup": [
- 655,
+ 658,
{
"id": [
1,
@@ -11490,7 +11566,7 @@ export default {
}
],
"getViewGroups": [
- 655,
+ 658,
{
"viewId": [
1
@@ -11498,7 +11574,7 @@ export default {
}
],
"getViewSort": [
- 658,
+ 661,
{
"id": [
1,
@@ -11507,7 +11583,7 @@ export default {
}
],
"getViewSorts": [
- 658,
+ 661,
{
"viewId": [
1
@@ -11515,25 +11591,25 @@ export default {
}
],
"getViews": [
- 646,
+ 649,
{
"objectMetadataId": [
1
],
"viewTypes": [
- 660,
+ 663,
"[ViewType!]"
]
}
],
"getWorkspaceCreationDefaults": [
- 675
+ 678
],
"gettingStartedProgress": [
- 294
+ 297
],
"gettingStartedWorkflowPreviews": [
- 299
+ 302
],
"githubClaimAuthorizationUrl": [
1,
@@ -11554,158 +11630,158 @@ export default {
}
],
"lineChartData": [
- 329,
+ 332,
{
"input": [
- 330,
+ 333,
"LineChartDataInput!"
]
}
],
"listPlans": [
- 108
+ 109
],
"mcpServer": [
- 351,
+ 354,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"mcpServers": [
- 351
+ 354
],
"messageSuppressions": [
- 367,
+ 370,
{
"input": [
- 285,
+ 286,
"FindMessageSuppressionsInput!"
]
}
],
"metadataTranslations": [
- 372,
+ 375,
{
"input": [
- 375,
+ 378,
"MetadataTranslationsInput!"
]
}
],
"minimalMetadata": [
- 376
+ 379
],
"mostlyEmptyFieldMetadataIds": [
- 534,
+ 537,
{
"objectMetadataId": [
- 534,
+ 537,
"UUID!"
]
}
],
"myApplicationPreferences": [
- 72
+ 73
],
"myCalendarChannels": [
- 128,
+ 129,
{
"connectedAccountId": [
- 534
+ 537
]
}
],
"myConnectedAccounts": [
- 159
+ 160
],
"myMessageChannels": [
- 355,
+ 358,
{
"connectedAccountId": [
- 534
+ 537
]
}
],
"myMessageFolders": [
- 362,
+ 365,
{
"messageChannelId": [
- 534
+ 537
]
}
],
"myUserApplicationVariables": [
- 680
+ 683
],
"navigationMenuItem": [
- 382,
+ 385,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"navigationMenuItems": [
- 382
+ 385
],
"object": [
- 385,
+ 388,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"objectRecordCounts": [
- 395
+ 398
],
"objects": [
- 386,
+ 389,
{
"filter": [
- 389,
+ 392,
"ObjectFilter!"
],
"paging": [
- 210,
+ 211,
"CursorPaging!"
]
}
],
"pieChartData": [
- 419,
+ 422,
{
"input": [
- 420,
+ 423,
"PieChartDataInput!"
]
}
],
"previewMessageCampaignAudience": [
- 136,
+ 137,
{
"input": [
- 423,
+ 426,
"PreviewMessageCampaignAudienceInput!"
]
}
],
"previewMessageCampaignSend": [
- 425,
+ 428,
{
"input": [
- 424,
+ 427,
"PreviewMessageCampaignSendInput!"
]
}
],
"publicMarketplaceAppDetail": [
- 346,
+ 349,
{
"universalIdentifier": [
1,
@@ -11714,76 +11790,76 @@ export default {
}
],
"publicMarketplaceApps": [
- 345
+ 348
],
"recordPermissions": [
- 439,
+ 442,
{
"targets": [
- 448,
+ 451,
"[RecordTargetInput!]!"
]
}
],
"recordSharing": [
- 444,
+ 447,
{
"target": [
- 448,
+ 451,
"RecordTargetInput!"
]
}
],
"relatedRecordPaths": [
- 449
+ 452
],
"skill": [
- 500,
+ 503,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"skills": [
- 500
+ 503
],
"timelineActivityTypes": [
- 512
+ 515
],
"twoFactorAuthenticationRecoveryStatus": [
- 533,
+ 536,
{
"userId": [
- 534,
+ 537,
"UUID!"
]
}
],
"unsubscribeTopics": [
- 537
+ 540
],
"usageLimits": [
- 621
+ 624
],
"usageQuotaDefinitions": [
- 625
+ 628
],
"usageQuotaScopeConsumption": [
- 627,
+ 630,
{
"input": [
- 628,
+ 631,
"UsageQuotaScopeInput!"
]
}
],
"usageQuotasWithConsumption": [
- 629
+ 632
],
"validatePasswordResetToken": [
- 640,
+ 643,
{
"passwordResetToken": [
1,
@@ -11792,34 +11868,34 @@ export default {
}
],
"validationRules": [
- 641,
+ 644,
{
"objectMetadataId": [
- 534,
+ 537,
"UUID!"
]
}
],
"validationRulesReadingField": [
- 641,
+ 644,
{
"fieldMetadataId": [
- 534,
+ 537,
"UUID!"
]
}
],
"webhook": [
- 662,
+ 665,
{
"id": [
- 534,
+ 537,
"UUID!"
]
}
],
"webhooks": [
- 662
+ 665
],
"__typename": [
1
@@ -11827,7 +11903,7 @@ export default {
},
"RatioAggregateConfig": {
"fieldMetadataId": [
- 534
+ 537
],
"optionValue": [
1
@@ -11847,7 +11923,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"progress": [
10
@@ -11858,7 +11934,7 @@ export default {
},
"RecordIdentifier": {
"id": [
- 534
+ 537
],
"imageIdentifier": [
1
@@ -11889,13 +11965,13 @@ export default {
},
"RecordPermissionsResult": {
"objectMetadataId": [
- 534
+ 537
],
"permissions": [
- 438
+ 441
],
"recordId": [
- 534
+ 537
],
"__typename": [
1
@@ -11904,10 +11980,10 @@ export default {
"RecordShareAccessLevel": {},
"RecordSharePrincipalInput": {
"roleId": [
- 534
+ 537
],
"workspaceMemberId": [
- 534
+ 537
],
"__typename": [
1
@@ -11929,13 +12005,13 @@ export default {
4
],
"permissions": [
- 438
+ 441
],
"roles": [
- 446
+ 449
],
"shares": [
- 445
+ 448
],
"__typename": [
1
@@ -11943,22 +12019,22 @@ export default {
},
"RecordSharingGrantDTO": {
"accessLevel": [
- 440
+ 443
],
"id": [
18
],
"principalId": [
- 534
+ 537
],
"principalRoleId": [
- 534
+ 537
],
"principalType": [
- 442
+ 445
],
"rowCause": [
- 443
+ 446
],
"__typename": [
1
@@ -11972,7 +12048,7 @@ export default {
4
],
"id": [
- 534
+ 537
],
"label": [
1
@@ -11983,7 +12059,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 664
+ 667
],
"isUIEditable": [
4
@@ -12000,10 +12076,10 @@ export default {
},
"RecordTargetInput": {
"objectMetadataId": [
- 534
+ 537
],
"recordId": [
- 534
+ 537
],
"__typename": [
1
@@ -12011,22 +12087,22 @@ export default {
},
"RelatedRecordPath": {
"firstFieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"isInherent": [
4
],
"objectMetadataId": [
- 534
+ 537
],
"secondFieldMetadataId": [
- 534
+ 537
],
"thirdFieldMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -12034,19 +12110,19 @@ export default {
},
"Relation": {
"sourceFieldMetadata": [
- 267
+ 268
],
"sourceObjectMetadata": [
- 385
+ 388
],
"targetFieldMetadata": [
- 267
+ 268
],
"targetObjectMetadata": [
- 385
+ 388
],
"type": [
- 451
+ 454
],
"__typename": [
1
@@ -12085,7 +12161,7 @@ export default {
},
"RevokeApiKeyInput": {
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -12110,10 +12186,10 @@ export default {
3
],
"apiKeys": [
- 39
+ 40
],
"applicationId": [
- 534
+ 537
],
"canAccessAllAgentChatChannels": [
4
@@ -12149,13 +12225,13 @@ export default {
1
],
"fieldPermissions": [
- 274
+ 275
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"isEditable": [
4
@@ -12164,22 +12240,22 @@ export default {
1
],
"objectPermissions": [
- 393
+ 396
],
"permissionFlags": [
- 458
+ 461
],
"rowLevelPermissionPredicateGroups": [
- 461
+ 464
],
"rowLevelPermissionPredicates": [
- 460
+ 463
],
"universalIdentifier": [
- 534
+ 537
],
"workspaceMembers": [
- 679
+ 682
],
"__typename": [
1
@@ -12190,10 +12266,10 @@ export default {
1
],
"id": [
- 534
+ 537
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -12218,7 +12294,7 @@ export default {
1
],
"operand": [
- 465
+ 468
],
"positionInRowLevelPermissionPredicateGroup": [
6
@@ -12236,7 +12312,7 @@ export default {
1
],
"value": [
- 324
+ 327
],
"workspaceMemberFieldMetadataId": [
1
@@ -12253,7 +12329,7 @@ export default {
1
],
"logicalOperator": [
- 463
+ 466
],
"objectMetadataId": [
1
@@ -12273,16 +12349,16 @@ export default {
},
"RowLevelPermissionPredicateGroupInput": {
"id": [
- 534
+ 537
],
"logicalOperator": [
- 463
+ 466
],
"objectMetadataId": [
- 534
+ 537
],
"parentRowLevelPermissionPredicateGroupId": [
- 534
+ 537
],
"positionInRowLevelPermissionPredicateGroup": [
6
@@ -12294,28 +12370,28 @@ export default {
"RowLevelPermissionPredicateGroupLogicalOperator": {},
"RowLevelPermissionPredicateInput": {
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"operand": [
- 465
+ 468
],
"positionInRowLevelPermissionPredicateGroup": [
6
],
"relationFieldMetadataId": [
- 534
+ 537
],
"rowLevelPermissionPredicateGroupId": [
- 534
+ 537
],
"subFieldName": [
1
],
"value": [
- 324
+ 327
],
"workspaceMemberFieldMetadataId": [
1
@@ -12336,22 +12412,22 @@ export default {
1
],
"input": [
- 468
+ 471
],
"messages": [
- 468
+ 471
],
"prompt": [
1
],
"responseFormat": [
- 324
+ 327
],
"runAsWorkspaceMemberId": [
- 534
+ 537
],
"thread": [
- 471
+ 474
],
"waitForCompletion": [
4
@@ -12362,7 +12438,7 @@ export default {
},
"RunAgentMessageAttachmentInput": {
"fileId": [
- 534
+ 537
],
"filename": [
1
@@ -12373,13 +12449,13 @@ export default {
},
"RunAgentMessageInput": {
"attachments": [
- 467
+ 470
],
"content": [
1
],
"role": [
- 469
+ 472
],
"__typename": [
1
@@ -12391,7 +12467,10 @@ export default {
1
],
"result": [
- 324
+ 327
+ ],
+ "runId": [
+ 537
],
"status": [
1
@@ -12400,7 +12479,7 @@ export default {
4
],
"threadId": [
- 534
+ 537
],
"__typename": [
1
@@ -12419,7 +12498,7 @@ export default {
},
"SSOConnection": {
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -12428,10 +12507,10 @@ export default {
1
],
"status": [
- 474
+ 477
],
"type": [
- 305
+ 308
],
"__typename": [
1
@@ -12439,7 +12518,7 @@ export default {
},
"SSOIdentityProvider": {
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -12448,10 +12527,10 @@ export default {
1
],
"status": [
- 474
+ 477
],
"type": [
- 305
+ 308
],
"__typename": [
1
@@ -12471,22 +12550,22 @@ export default {
},
"SearchField": {
"createdAt": [
- 212
+ 213
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"position": [
6
],
"tsVectorFieldMetadataId": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -12494,13 +12573,13 @@ export default {
},
"SendAppChannelMessageInput": {
"idempotencyKey": [
- 534
+ 537
],
"messageChannelId": [
- 534
+ 537
],
"messageThreadId": [
- 534
+ 537
],
"text": [
1
@@ -12511,10 +12590,10 @@ export default {
},
"SendAppChannelMessageOutput": {
"messageId": [
- 534
+ 537
],
"messageThreadId": [
- 534
+ 537
],
"__typename": [
1
@@ -12522,7 +12601,7 @@ export default {
},
"SendChatMessageResult": {
"mentionedParticipantWorkspaceMemberIds": [
- 534
+ 537
],
"messageId": [
1
@@ -12565,7 +12644,7 @@ export default {
1
],
"files": [
- 480
+ 483
],
"fromHandle": [
1
@@ -12577,7 +12656,7 @@ export default {
1
],
"targetRecord": [
- 483
+ 486
],
"to": [
1
@@ -12605,7 +12684,7 @@ export default {
1
],
"recordId": [
- 534
+ 537
],
"__typename": [
1
@@ -12633,10 +12712,10 @@ export default {
1
],
"toolCall": [
- 324
+ 327
],
"workspaceMemberIds": [
- 534
+ 537
],
"__typename": [
1
@@ -12644,7 +12723,7 @@ export default {
},
"SendInboxMessageResult": {
"threadId": [
- 534
+ 537
],
"__typename": [
1
@@ -12655,7 +12734,7 @@ export default {
1
],
"result": [
- 677
+ 680
],
"success": [
4
@@ -12669,7 +12748,7 @@ export default {
1
],
"scheduledAt": [
- 212
+ 213
],
"__typename": [
1
@@ -12677,7 +12756,7 @@ export default {
},
"SendMessageCampaignOutputDTO": {
"audience": [
- 136
+ 137
],
"campaignId": [
1
@@ -12731,10 +12810,10 @@ export default {
1
],
"scope": [
- 43
+ 44
],
"value": [
- 324
+ 327
],
"__typename": [
1
@@ -12742,25 +12821,25 @@ export default {
},
"SettingsMenuItem": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"frontComponentId": [
- 534
+ 537
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"position": [
6
],
"scope": [
- 494
+ 497
],
"slug": [
1
@@ -12769,10 +12848,10 @@ export default {
1
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -12804,7 +12883,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -12821,7 +12900,7 @@ export default {
},
"SetupSso": {
"id": [
- 534
+ 537
],
"issuer": [
1
@@ -12830,10 +12909,10 @@ export default {
1
],
"status": [
- 474
+ 477
],
"type": [
- 305
+ 308
],
"__typename": [
1
@@ -12841,10 +12920,10 @@ export default {
},
"SignUp": {
"loginToken": [
- 84
+ 85
],
"workspace": [
- 689
+ 692
],
"__typename": [
1
@@ -12869,13 +12948,13 @@ export default {
},
"Skill": {
"applicationId": [
- 534
+ 537
],
"content": [
1
],
"createdAt": [
- 212
+ 213
],
"description": [
1
@@ -12884,7 +12963,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -12902,7 +12981,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -12910,10 +12989,10 @@ export default {
},
"StandaloneRichTextConfiguration": {
"body": [
- 456
+ 459
],
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -12921,7 +13000,7 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 687
+ 690
],
"thread": [
17
@@ -12957,32 +13036,32 @@ export default {
},
"Subscription": {
"eventLogsLive": [
- 261,
+ 262,
{
"fieldFilters": [
- 255,
+ 256,
"[EventLogFieldFilterInput!]"
],
"table": [
- 262,
+ 263,
"EventLogTable!"
]
}
],
"exportRecords": [
- 436,
+ 439,
{
"input": [
- 194,
+ 195,
"CreateRecordExportInput!"
]
}
],
"logicFunctionLogs": [
- 342,
+ 345,
{
"input": [
- 343,
+ 346,
"LogicFunctionLogsInput!"
]
}
@@ -12990,14 +13069,22 @@ export default {
"onAgentChatEvent": [
14,
{
+ "agentUniversalIdentifier": [
+ 537
+ ],
+ "runId": [
+ 537
+ ],
"threadId": [
- 534,
- "UUID!"
+ 537
+ ],
+ "threadKey": [
+ 1
]
}
],
"onEventSubscription": [
- 263,
+ 264,
{
"eventStreamId": [
1,
@@ -13013,7 +13100,7 @@ export default {
"SubscriptionStatus": {},
"Support": {
"supportDriver": [
- 509
+ 512
],
"supportFrontChatId": [
1
@@ -13025,10 +13112,10 @@ export default {
"SupportDriver": {},
"SyncAppMessageFoldersInput": {
"folders": [
- 44
+ 45
],
"messageChannelId": [
- 534
+ 537
],
"__typename": [
1
@@ -13036,7 +13123,7 @@ export default {
},
"TasksConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -13047,22 +13134,22 @@ export default {
1
],
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"emit": [
- 513
+ 516
],
"frontComponentUniversalIdentifier": [
- 534
+ 537
],
"icon": [
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -13074,16 +13161,16 @@ export default {
1
],
"objectUniversalIdentifier": [
- 534
+ 537
],
"replacesTimelineActivityTypeUniversalIdentifier": [
- 534
+ 537
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -13091,13 +13178,13 @@ export default {
},
"TimelineActivityTypeEmit": {
"objectUniversalIdentifier": [
- 534
+ 537
],
"on": [
1
],
"through": [
- 514
+ 517
],
"__typename": [
1
@@ -13105,13 +13192,13 @@ export default {
},
"TimelineActivityTypeEmitThrough": {
"happensAtFieldUniversalIdentifier": [
- 534
+ 537
],
"relationFieldUniversalIdentifier": [
- 534
+ 537
],
"triggerFieldUniversalIdentifiers": [
- 534
+ 537
],
"__typename": [
1
@@ -13119,7 +13206,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -13139,7 +13226,7 @@ export default {
1
],
"inputSchema": [
- 324
+ 327
],
"label": [
1
@@ -13159,7 +13246,7 @@ export default {
},
"TransientToken": {
"transientToken": [
- 84
+ 85
],
"__typename": [
1
@@ -13167,10 +13254,10 @@ export default {
},
"TriggerAddPeopleToMessageListJobInput": {
"messageListId": [
- 534
+ 537
],
"personFilter": [
- 324
+ 327
],
"__typename": [
1
@@ -13275,7 +13362,7 @@ export default {
1
],
"twoFactorAuthenticationMethodId": [
- 534
+ 537
],
"__typename": [
1
@@ -13283,7 +13370,7 @@ export default {
},
"TwoFactorAuthenticationRecoveryCode": {
"expiresAt": [
- 212
+ 213
],
"recoveryCode": [
1
@@ -13297,7 +13384,7 @@ export default {
1
],
"tokens": [
- 85
+ 86
],
"__typename": [
1
@@ -13311,7 +13398,7 @@ export default {
4
],
"pendingRecoveryCodeExpiresAt": [
- 212
+ 213
],
"__typename": [
1
@@ -13320,19 +13407,19 @@ export default {
"UUID": {},
"UUIDFilterComparison": {
"eq": [
- 534
+ 537
],
"gt": [
- 534
+ 537
],
"gte": [
- 534
+ 537
],
"iLike": [
- 534
+ 537
],
"in": [
- 534
+ 537
],
"is": [
4
@@ -13341,25 +13428,25 @@ export default {
4
],
"like": [
- 534
+ 537
],
"lt": [
- 534
+ 537
],
"lte": [
- 534
+ 537
],
"neq": [
- 534
+ 537
],
"notILike": [
- 534
+ 537
],
"notIn": [
- 534
+ 537
],
"notLike": [
- 534
+ 537
],
"__typename": [
1
@@ -13368,22 +13455,22 @@ export default {
"UnsubscribeHostnameStatus": {},
"UnsubscribeTopic": {
"createdAt": [
- 212
+ 213
],
"description": [
1
],
"id": [
- 534
+ 537
],
"name": [
1
],
"updatedAt": [
- 212
+ 213
],
"visibility": [
- 538
+ 541
],
"__typename": [
1
@@ -13404,7 +13491,7 @@ export default {
6
],
"roleIds": [
- 534
+ 537
],
"__typename": [
1
@@ -13418,7 +13505,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -13427,7 +13514,7 @@ export default {
1
],
"modelConfiguration": [
- 324
+ 327
],
"modelId": [
1
@@ -13439,13 +13526,13 @@ export default {
1
],
"responseFormat": [
- 324
+ 327
],
"roleId": [
- 534
+ 537
],
"triggers": [
- 324
+ 327
],
"__typename": [
1
@@ -13456,7 +13543,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"name": [
1
@@ -13473,16 +13560,16 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isSyncEnabled": [
4
],
"messagingProviderUniversalIdentifier": [
- 534
+ 537
],
"visibility": [
- 361
+ 364
],
"__typename": [
1
@@ -13501,7 +13588,7 @@ export default {
1
],
"update": [
- 545
+ 548
],
"__typename": [
1
@@ -13526,7 +13613,7 @@ export default {
1
],
"update": [
- 547
+ 550
],
"__typename": [
1
@@ -13548,10 +13635,10 @@ export default {
},
"UpdateCalendarChannelInput": {
"id": [
- 534
+ 537
],
"update": [
- 549
+ 552
],
"__typename": [
1
@@ -13559,7 +13646,7 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"contactAutoCreationPolicy": [
- 129
+ 130
],
"excludePrivateEvents": [
4
@@ -13571,7 +13658,7 @@ export default {
4
],
"visibility": [
- 132
+ 133
],
"__typename": [
1
@@ -13579,13 +13666,13 @@ export default {
},
"UpdateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 534
+ 537
],
"availabilityType": [
- 156
+ 157
],
"engineComponentKey": [
- 246
+ 247
],
"hotKeys": [
1
@@ -13594,7 +13681,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isPinned": [
4
@@ -13603,7 +13690,7 @@ export default {
1
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
@@ -13620,7 +13707,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -13628,7 +13715,7 @@ export default {
},
"UpdateFieldInput": {
"defaultValue": [
- 324
+ 327
],
"description": [
1
@@ -13667,22 +13754,22 @@ export default {
1
],
"morphRelationsUpdatePayload": [
- 324
+ 327
],
"name": [
1
],
"objectMetadataId": [
- 534
+ 537
],
"options": [
- 324
+ 327
],
"settings": [
- 324
+ 327
],
"translations": [
- 373
+ 376
],
"universalIdentifier": [
1
@@ -13693,10 +13780,10 @@ export default {
},
"UpdateFrontComponentInput": {
"id": [
- 534
+ 537
],
"update": [
- 554
+ 557
],
"__typename": [
1
@@ -13715,13 +13802,13 @@ export default {
},
"UpdateGettingStartedInput": {
"completedStepActionKey": [
- 295
+ 298
],
"isHidden": [
4
],
"selectedStepActionKey": [
- 295
+ 298
],
"snoozedUntil": [
1
@@ -13743,10 +13830,10 @@ export default {
},
"UpdateLogicFunctionFromSourceInput": {
"id": [
- 534
+ 537
],
"update": [
- 558
+ 561
],
"__typename": [
1
@@ -13754,10 +13841,10 @@ export default {
},
"UpdateLogicFunctionFromSourceInputUpdates": {
"cronTriggerSettings": [
- 324
+ 327
],
"databaseEventTriggerSettings": [
- 324
+ 327
],
"description": [
1
@@ -13766,7 +13853,7 @@ export default {
1
],
"httpRouteTriggerSettings": [
- 324
+ 327
],
"name": [
1
@@ -13781,10 +13868,10 @@ export default {
6
],
"toolTriggerSettings": [
- 324
+ 327
],
"workflowActionTriggerSettings": [
- 324
+ 327
],
"__typename": [
1
@@ -13792,10 +13879,10 @@ export default {
},
"UpdateMcpServerInput": {
"id": [
- 534
+ 537
],
"update": [
- 560
+ 563
],
"__typename": [
1
@@ -13803,7 +13890,7 @@ export default {
},
"UpdateMcpServerInputUpdates": {
"connectionProviderId": [
- 534
+ 537
],
"isActive": [
4
@@ -13823,10 +13910,10 @@ export default {
},
"UpdateMessageChannelInput": {
"id": [
- 534
+ 537
],
"update": [
- 562
+ 565
],
"__typename": [
1
@@ -13834,7 +13921,7 @@ export default {
},
"UpdateMessageChannelInputUpdates": {
"contactAutoCreationPolicy": [
- 356
+ 359
],
"excludeGroupEmails": [
4
@@ -13849,10 +13936,10 @@ export default {
4
],
"messageFolderImportPolicy": [
- 363
+ 366
],
"visibility": [
- 361
+ 364
],
"__typename": [
1
@@ -13860,10 +13947,10 @@ export default {
},
"UpdateMessageFolderInput": {
"id": [
- 534
+ 537
],
"update": [
- 564
+ 567
],
"__typename": [
1
@@ -13879,10 +13966,10 @@ export default {
},
"UpdateMessageFoldersInput": {
"ids": [
- 534
+ 537
],
"update": [
- 564
+ 567
],
"__typename": [
1
@@ -13893,7 +13980,7 @@ export default {
1
],
"folderId": [
- 534
+ 537
],
"icon": [
1
@@ -13905,7 +13992,7 @@ export default {
1
],
"pageLayoutId": [
- 534
+ 537
],
"position": [
6
@@ -13925,7 +14012,7 @@ export default {
1
],
"imageIdentifierFieldMetadataId": [
- 534
+ 537
],
"isActive": [
4
@@ -13937,7 +14024,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 534
+ 537
],
"labelPlural": [
1
@@ -13952,13 +14039,13 @@ export default {
1
],
"openRecordIn": [
- 392
+ 395
],
"shortcut": [
1
],
"translations": [
- 373
+ 376
],
"__typename": [
1
@@ -13966,10 +14053,10 @@ export default {
},
"UpdateOneFieldMetadataInput": {
"id": [
- 534
+ 537
],
"update": [
- 552
+ 555
],
"__typename": [
1
@@ -13977,10 +14064,10 @@ export default {
},
"UpdateOneNavigationMenuItemInput": {
"id": [
- 534
+ 537
],
"update": [
- 566
+ 569
],
"__typename": [
1
@@ -13988,10 +14075,10 @@ export default {
},
"UpdateOneObjectInput": {
"id": [
- 534
+ 537
],
"update": [
- 567
+ 570
],
"__typename": [
1
@@ -14002,10 +14089,10 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"type": [
- 408
+ 411
],
"__typename": [
1
@@ -14016,7 +14103,7 @@ export default {
1
],
"layoutMode": [
- 407
+ 410
],
"position": [
6
@@ -14033,10 +14120,10 @@ export default {
1
],
"id": [
- 534
+ 537
],
"layoutMode": [
- 407
+ 410
],
"position": [
6
@@ -14045,7 +14132,7 @@ export default {
1
],
"widgets": [
- 575
+ 578
],
"__typename": [
1
@@ -14056,28 +14143,28 @@ export default {
1
],
"conditionalDisplay": [
- 324
+ 327
],
"configuration": [
- 324
+ 327
],
"isActive": [
4
],
"objectMetadataId": [
- 534
+ 537
],
"pageLayoutTabId": [
- 534
+ 537
],
"position": [
- 324
+ 327
],
"title": [
1
],
"type": [
- 665
+ 668
],
"__typename": [
1
@@ -14088,28 +14175,28 @@ export default {
1
],
"conditionalDisplay": [
- 324
+ 327
],
"configuration": [
- 324
+ 327
],
"id": [
- 534
+ 537
],
"objectMetadataId": [
- 534
+ 537
],
"pageLayoutTabId": [
- 534
+ 537
],
"position": [
- 324
+ 327
],
"title": [
1
],
"type": [
- 665
+ 668
],
"__typename": [
1
@@ -14123,13 +14210,13 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"tabs": [
- 573
+ 576
],
"type": [
- 408
+ 411
],
"__typename": [
1
@@ -14137,10 +14224,10 @@ export default {
},
"UpdateRoleInput": {
"id": [
- 534
+ 537
],
"update": [
- 578
+ 581
],
"__typename": [
1
@@ -14201,7 +14288,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -14221,7 +14308,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -14230,7 +14317,7 @@ export default {
1
],
"translations": [
- 373
+ 376
],
"__typename": [
1
@@ -14247,7 +14334,7 @@ export default {
1
],
"visibility": [
- 538
+ 541
],
"__typename": [
1
@@ -14255,10 +14342,10 @@ export default {
},
"UpdateUsageLimitInput": {
"id": [
- 534
+ 537
],
"payload": [
- 199
+ 200
],
"__typename": [
1
@@ -14266,10 +14353,10 @@ export default {
},
"UpdateValidationRuleInput": {
"id": [
- 534
+ 537
],
"update": [
- 584
+ 587
],
"__typename": [
1
@@ -14280,7 +14367,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 534
+ 537
],
"expression": [
1
@@ -14303,10 +14390,10 @@ export default {
},
"UpdateViewFieldGroupInput": {
"id": [
- 534
+ 537
],
"update": [
- 586
+ 589
],
"__typename": [
1
@@ -14331,10 +14418,10 @@ export default {
},
"UpdateViewFieldInput": {
"id": [
- 534
+ 537
],
"update": [
- 588
+ 591
],
"__typename": [
1
@@ -14354,7 +14441,7 @@ export default {
6
],
"viewFieldGroupId": [
- 534
+ 537
],
"__typename": [
1
@@ -14362,19 +14449,19 @@ export default {
},
"UpdateViewFilterGroupInput": {
"id": [
- 534
+ 537
],
"logicalOperator": [
- 653
+ 656
],
"parentViewFilterGroupId": [
- 534
+ 537
],
"positionInViewFilterGroup": [
6
],
"viewId": [
- 534
+ 537
],
"__typename": [
1
@@ -14382,10 +14469,10 @@ export default {
},
"UpdateViewFilterInput": {
"id": [
- 534
+ 537
],
"update": [
- 591
+ 594
],
"__typename": [
1
@@ -14393,25 +14480,25 @@ export default {
},
"UpdateViewFilterInputUpdates": {
"fieldMetadataId": [
- 534
+ 537
],
"operand": [
- 654
+ 657
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 534
+ 537
],
"subFieldName": [
1
],
"value": [
- 324
+ 327
],
"viewFilterGroupId": [
- 534
+ 537
],
"__typename": [
1
@@ -14419,10 +14506,10 @@ export default {
},
"UpdateViewGroupInput": {
"id": [
- 534
+ 537
],
"update": [
- 593
+ 596
],
"__typename": [
1
@@ -14430,7 +14517,7 @@ export default {
},
"UpdateViewGroupInputUpdates": {
"fieldMetadataId": [
- 534
+ 537
],
"fieldValue": [
1
@@ -14450,13 +14537,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 534
+ 537
],
"calendarFieldMetadataId": [
- 534
+ 537
],
"calendarLayout": [
- 647
+ 650
],
"groupLoadLimit": [
10
@@ -14465,7 +14552,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isCompact": [
4
@@ -14474,19 +14561,19 @@ export default {
27
],
"kanbanAggregateOperationFieldMetadataId": [
- 534
+ 537
],
"kanbanColumnWidth": [
10
],
"mainGroupByFieldMetadataId": [
- 534
+ 537
],
"name": [
1
],
"openRecordIn": [
- 657
+ 660
],
"position": [
6
@@ -14495,13 +14582,13 @@ export default {
4
],
"translations": [
- 373
+ 376
],
"type": [
- 660
+ 663
],
"visibility": [
- 661
+ 664
],
"__typename": [
1
@@ -14509,10 +14596,10 @@ export default {
},
"UpdateViewSortInput": {
"id": [
- 534
+ 537
],
"update": [
- 596
+ 599
],
"__typename": [
1
@@ -14520,7 +14607,7 @@ export default {
},
"UpdateViewSortInputUpdates": {
"direction": [
- 659
+ 662
],
"subFieldName": [
1
@@ -14531,10 +14618,10 @@ export default {
},
"UpdateWebhookInput": {
"id": [
- 534
+ 537
],
"update": [
- 598
+ 601
],
"__typename": [
1
@@ -14548,7 +14635,7 @@ export default {
1
],
"roleId": [
- 534
+ 537
],
"secret": [
1
@@ -14605,7 +14692,7 @@ export default {
1
],
"aiModelIdByTier": [
- 324
+ 327
],
"allowImpersonation": [
4
@@ -14614,7 +14701,7 @@ export default {
1
],
"defaultRoleId": [
- 534
+ 537
],
"displayName": [
1
@@ -14674,7 +14761,7 @@ export default {
6
],
"workspaceDiscoverability": [
- 676
+ 679
],
"__typename": [
1
@@ -14682,10 +14769,10 @@ export default {
},
"UpdateWorkspaceMemberSettingsInput": {
"update": [
- 324
+ 327
],
"workspaceMemberId": [
- 534
+ 537
],
"__typename": [
1
@@ -14694,10 +14781,10 @@ export default {
"Upload": {},
"UpsertFieldPermissionsInput": {
"fieldPermissions": [
- 275
+ 276
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -14705,7 +14792,7 @@ export default {
},
"UpsertFieldsWidgetFieldInput": {
"fieldMetadataId": [
- 534
+ 537
],
"isVisible": [
4
@@ -14714,7 +14801,7 @@ export default {
6
],
"viewFieldId": [
- 534
+ 537
],
"__typename": [
1
@@ -14722,10 +14809,10 @@ export default {
},
"UpsertFieldsWidgetGroupInput": {
"fields": [
- 605
+ 608
],
"id": [
- 534
+ 537
],
"isVisible": [
4
@@ -14742,13 +14829,13 @@ export default {
},
"UpsertFieldsWidgetInput": {
"fields": [
- 605
+ 608
],
"groups": [
- 606
+ 609
],
"widgetId": [
- 534
+ 537
],
"__typename": [
1
@@ -14756,10 +14843,10 @@ export default {
},
"UpsertObjectPermissionsInput": {
"objectPermissions": [
- 394
+ 397
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -14770,7 +14857,7 @@ export default {
1
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -14778,16 +14865,16 @@ export default {
},
"UpsertRowLevelPermissionPredicatesInput": {
"objectMetadataId": [
- 534
+ 537
],
"predicateGroups": [
- 462
+ 465
],
"predicates": [
- 464
+ 467
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -14795,10 +14882,10 @@ export default {
},
"UpsertRowLevelPermissionPredicatesResult": {
"predicateGroups": [
- 461
+ 464
],
"predicates": [
- 460
+ 463
],
"__typename": [
1
@@ -14806,22 +14893,22 @@ export default {
},
"UpsertViewWidgetInput": {
"view": [
- 616
+ 619
],
"viewFields": [
- 613
+ 616
],
"viewFilterGroups": [
- 614
+ 617
],
"viewFilters": [
- 615
+ 618
],
"viewSorts": [
- 617
+ 620
],
"widgetId": [
- 534
+ 537
],
"__typename": [
1
@@ -14832,7 +14919,7 @@ export default {
27
],
"fieldMetadataId": [
- 534
+ 537
],
"isVisible": [
4
@@ -14844,7 +14931,7 @@ export default {
6
],
"viewFieldId": [
- 534
+ 537
],
"__typename": [
1
@@ -14852,13 +14939,13 @@ export default {
},
"UpsertViewWidgetViewFilterGroupInput": {
"id": [
- 534
+ 537
],
"logicalOperator": [
- 653
+ 656
],
"parentViewFilterGroupId": [
- 534
+ 537
],
"positionInViewFilterGroup": [
6
@@ -14869,28 +14956,28 @@ export default {
},
"UpsertViewWidgetViewFilterInput": {
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"operand": [
- 654
+ 657
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 534
+ 537
],
"subFieldName": [
1
],
"value": [
- 324
+ 327
],
"viewFilterGroupId": [
- 534
+ 537
],
"__typename": [
1
@@ -14898,34 +14985,34 @@ export default {
},
"UpsertViewWidgetViewSettingsInput": {
"calendarEndFieldMetadataId": [
- 534
+ 537
],
"calendarFieldMetadataId": [
- 534
+ 537
],
"calendarLayout": [
- 647
+ 650
],
"kanbanAggregateOperation": [
27
],
"kanbanAggregateOperationFieldMetadataId": [
- 534
+ 537
],
"kanbanColumnWidth": [
10
],
"mainGroupByFieldMetadataId": [
- 534
+ 537
],
"openRecordIn": [
- 657
+ 660
],
"shouldHideEmptyGroups": [
4
],
"type": [
- 660
+ 663
],
"__typename": [
1
@@ -14933,13 +15020,13 @@ export default {
},
"UpsertViewWidgetViewSortInput": {
"direction": [
- 659
+ 662
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -14947,28 +15034,28 @@ export default {
},
"UsageAnalytics": {
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"timeSeries": [
- 631
+ 634
],
"usageByApplication": [
- 620
+ 623
],
"usageByModel": [
- 620
+ 623
],
"usageByOperationType": [
- 620
+ 623
],
"usageByUser": [
- 620
+ 623
],
"userDailyUsage": [
- 633
+ 636
],
"__typename": [
1
@@ -14976,13 +15063,13 @@ export default {
},
"UsageAnalyticsInput": {
"operationTypes": [
- 623
+ 626
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"userWorkspaceId": [
1
@@ -15013,22 +15100,22 @@ export default {
},
"UsageLimit": {
"burstValue": [
- 99
+ 100
],
"createdAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"limitKind": [
1
],
"limitValue": [
- 99
+ 100
],
"operationType": [
- 623
+ 626
],
"periodCount": [
10
@@ -15037,7 +15124,7 @@ export default {
1
],
"resourceType": [
- 630
+ 633
],
"spenderId": [
1
@@ -15046,10 +15133,10 @@ export default {
1
],
"unit": [
- 632
+ 635
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -15057,10 +15144,10 @@ export default {
},
"UsageLimitOperationDefinition": {
"allowedUnits": [
- 632
+ 635
],
"operationType": [
- 623
+ 626
],
"__typename": [
1
@@ -15069,7 +15156,7 @@ export default {
"UsageOperationType": {},
"UsageQuotaDefinition": {
"allowedOperations": [
- 622
+ 625
],
"allowedSpenderTypes": [
1
@@ -15078,10 +15165,10 @@ export default {
1
],
"operatorOnlyScopes": [
- 626
+ 629
],
"resourceType": [
- 630
+ 633
],
"__typename": [
1
@@ -15089,7 +15176,7 @@ export default {
},
"UsageQuotaDefinitions": {
"definitions": [
- 624
+ 627
],
"hasAllowancePeriod": [
4
@@ -15103,7 +15190,7 @@ export default {
},
"UsageQuotaOperatorOnlyScope": {
"operationType": [
- 623
+ 626
],
"periodUnit": [
1
@@ -15112,7 +15199,7 @@ export default {
1
],
"unit": [
- 632
+ 635
],
"__typename": [
1
@@ -15120,13 +15207,13 @@ export default {
},
"UsageQuotaScopeConsumption": {
"consumedValue": [
- 99
+ 100
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"__typename": [
1
@@ -15134,13 +15221,13 @@ export default {
},
"UsageQuotaScopeInput": {
"operationType": [
- 623
+ 626
],
"periodUnit": [
1
],
"resourceType": [
- 630
+ 633
],
"spenderId": [
1
@@ -15149,7 +15236,7 @@ export default {
1
],
"unit": [
- 632
+ 635
],
"__typename": [
1
@@ -15157,34 +15244,34 @@ export default {
},
"UsageQuotaWithConsumption": {
"consumedValue": [
- 99
+ 100
],
"id": [
- 534
+ 537
],
"isEnforced": [
4
],
"limitValue": [
- 99
+ 100
],
"operationType": [
- 623
+ 626
],
"periodEnd": [
- 212
+ 213
],
"periodStart": [
- 212
+ 213
],
"periodUnit": [
1
],
"remainingValue": [
- 99
+ 100
],
"resourceType": [
- 630
+ 633
],
"spenderId": [
1
@@ -15196,7 +15283,7 @@ export default {
1
],
"unit": [
- 632
+ 635
],
"__typename": [
1
@@ -15220,7 +15307,7 @@ export default {
"UsageUnit": {},
"UsageUserDaily": {
"dailyUsage": [
- 631
+ 634
],
"userWorkspaceId": [
1
@@ -15231,7 +15318,7 @@ export default {
},
"User": {
"availableWorkspaces": [
- 90
+ 91
],
"canAccessFullAdminPanel": [
4
@@ -15240,19 +15327,19 @@ export default {
4
],
"createdAt": [
- 212
+ 213
],
"currentUserWorkspace": [
- 638
+ 641
],
"currentWorkspace": [
- 670
+ 673
],
"deletedAt": [
- 212
+ 213
],
"deletedWorkspaceMembers": [
- 225
+ 226
],
"disabled": [
4
@@ -15267,7 +15354,7 @@ export default {
4
],
"id": [
- 534
+ 537
],
"isEmailVerified": [
4
@@ -15282,31 +15369,31 @@ export default {
1
],
"onboardingStatus": [
- 400
+ 403
],
"previousOnboardingStatus": [
- 400
+ 403
],
"supportUserHash": [
1
],
"updatedAt": [
- 212
+ 213
],
"userVars": [
- 325
+ 328
],
"userWorkspaces": [
- 638
+ 641
],
"workspaceMember": [
- 679
+ 682
],
"workspaceMembers": [
- 679
+ 682
],
"workspaces": [
- 638
+ 641
],
"__typename": [
1
@@ -15332,7 +15419,7 @@ export default {
1
],
"options": [
- 324
+ 327
],
"type": [
1
@@ -15356,13 +15443,13 @@ export default {
1
],
"createdAt": [
- 212
+ 213
],
"expiresAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"ipAddress": [
1
@@ -15374,7 +15461,7 @@ export default {
4
],
"lastActiveAt": [
- 212
+ 213
],
"region": [
1
@@ -15383,7 +15470,7 @@ export default {
1
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15391,13 +15478,13 @@ export default {
},
"UserWorkspace": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"isImpersonating": [
4
@@ -15406,25 +15493,25 @@ export default {
1
],
"objectPermissions": [
- 393
+ 396
],
"objectsPermissions": [
- 393
+ 396
],
"permissionFlags": [
- 417
+ 420
],
"twoFactorAuthenticationMethodSummary": [
- 530
+ 533
],
"updatedAt": [
- 212
+ 213
],
"user": [
- 634
+ 637
],
"userId": [
- 534
+ 537
],
"__typename": [
1
@@ -15432,7 +15519,7 @@ export default {
},
"ValidateApprovedAccessDomainInput": {
"approvedAccessDomainId": [
- 534
+ 537
],
"validationToken": [
1
@@ -15449,7 +15536,7 @@ export default {
4
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -15460,7 +15547,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 534
+ 537
],
"expression": [
1
@@ -15469,7 +15556,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -15481,7 +15568,7 @@ export default {
1
],
"objectMetadataId": [
- 534
+ 537
],
"__typename": [
1
@@ -15509,10 +15596,10 @@ export default {
},
"VerifyEmailAndGetLoginToken": {
"loginToken": [
- 84
+ 85
],
"workspaceUrls": [
- 688
+ 691
],
"__typename": [
1
@@ -15542,25 +15629,25 @@ export default {
1
],
"applicationId": [
- 534
+ 537
],
"calendarEndFieldMetadataId": [
- 534
+ 537
],
"calendarFieldMetadataId": [
- 534
+ 537
],
"calendarLayout": [
- 647
+ 650
],
"createdAt": [
- 212
+ 213
],
"createdByUserWorkspaceId": [
- 534
+ 537
],
"deletedAt": [
- 212
+ 213
],
"groupLoadLimit": [
10
@@ -15569,7 +15656,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -15587,25 +15674,25 @@ export default {
27
],
"kanbanAggregateOperationFieldMetadataId": [
- 534
+ 537
],
"kanbanColumnWidth": [
10
],
"key": [
- 656
+ 659
],
"mainGroupByFieldMetadataId": [
- 534
+ 537
],
"name": [
1
],
"objectMetadataId": [
- 534
+ 537
],
"openRecordIn": [
- 657
+ 660
],
"position": [
6
@@ -15614,37 +15701,37 @@ export default {
4
],
"type": [
- 660
+ 663
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"viewFieldGroups": [
- 650
+ 653
],
"viewFields": [
- 649
+ 652
],
"viewFilterGroups": [
- 652
+ 655
],
"viewFilters": [
- 651
+ 654
],
"viewGroups": [
- 655
+ 658
],
"viewSorts": [
- 658
+ 661
],
"visibility": [
- 661
+ 664
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15653,7 +15740,7 @@ export default {
"ViewCalendarLayout": {},
"ViewConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -15664,19 +15751,19 @@ export default {
27
],
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -15697,19 +15784,19 @@ export default {
6
],
"universalIdentifier": [
- 534
+ 537
],
"updatedAt": [
- 212
+ 213
],
"viewFieldGroupId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15717,13 +15804,13 @@ export default {
},
"ViewFieldGroup": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"isActive": [
4
@@ -15741,16 +15828,16 @@ export default {
6
],
"updatedAt": [
- 212
+ 213
],
"viewFields": [
- 649
+ 652
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15758,43 +15845,43 @@ export default {
},
"ViewFilter": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"operand": [
- 654
+ 657
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 534
+ 537
],
"subFieldName": [
1
],
"updatedAt": [
- 212
+ 213
],
"value": [
- 324
+ 327
],
"viewFilterGroupId": [
- 534
+ 537
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15802,31 +15889,31 @@ export default {
},
"ViewFilterGroup": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"logicalOperator": [
- 653
+ 656
],
"parentViewFilterGroupId": [
- 534
+ 537
],
"positionInViewFilterGroup": [
6
],
"updatedAt": [
- 212
+ 213
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15836,16 +15923,16 @@ export default {
"ViewFilterOperand": {},
"ViewGroup": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"fieldValue": [
1
],
"id": [
- 534
+ 537
],
"isVisible": [
4
@@ -15854,13 +15941,13 @@ export default {
6
],
"updatedAt": [
- 212
+ 213
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15870,31 +15957,31 @@ export default {
"ViewOpenRecordIn": {},
"ViewSort": {
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"direction": [
- 659
+ 662
],
"fieldMetadataId": [
- 534
+ 537
],
"id": [
- 534
+ 537
],
"subFieldName": [
1
],
"updatedAt": [
- 212
+ 213
],
"viewId": [
- 534
+ 537
],
"workspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -15905,25 +15992,25 @@ export default {
"ViewVisibility": {},
"Webhook": {
"applicationId": [
- 534
+ 537
],
"createdAt": [
- 212
+ 213
],
"deletedAt": [
- 212
+ 213
],
"description": [
1
],
"id": [
- 534
+ 537
],
"operations": [
1
],
"role": [
- 457
+ 460
],
"secret": [
1
@@ -15932,7 +16019,7 @@ export default {
1
],
"updatedAt": [
- 212
+ 213
],
"__typename": [
1
@@ -15943,88 +16030,88 @@ export default {
26
],
"on_BarChartConfiguration": [
- 93
+ 94
],
"on_CalendarConfiguration": [
- 133
+ 134
],
"on_CallRecordingSummaryConfiguration": [
- 134
+ 135
],
"on_CallRecordingTranscriptConfiguration": [
- 135
+ 136
],
"on_ChatConfiguration": [
- 143
+ 144
],
"on_ChatThreadsConfiguration": [
- 146
+ 147
],
"on_EmailThreadConfiguration": [
- 241
+ 242
],
"on_EmailsConfiguration": [
- 245
+ 246
],
"on_FieldConfiguration": [
- 268
+ 269
],
"on_FieldRichTextConfiguration": [
- 276
+ 277
],
"on_FieldsConfiguration": [
- 277
+ 278
],
"on_FilesConfiguration": [
- 283
+ 284
],
"on_FormFieldConfiguration": [
- 286
+ 287
],
"on_FrontComponentConfiguration": [
- 288
+ 289
],
"on_IframeConfiguration": [
- 306
+ 309
],
"on_LineChartConfiguration": [
- 328
+ 331
],
"on_MessageCampaignBodyConfiguration": [
- 352
+ 355
],
"on_MessageCampaignDetailsConfiguration": [
- 353
+ 356
],
"on_NotesConfiguration": [
- 384
+ 387
],
"on_PieChartConfiguration": [
- 418
+ 421
],
"on_RecordTableConfiguration": [
- 447
+ 450
],
"on_StandaloneRichTextConfiguration": [
- 501
+ 504
],
"on_TasksConfiguration": [
- 511
+ 514
],
"on_TimelineConfiguration": [
- 515
+ 518
],
"on_ViewConfiguration": [
- 648
+ 651
],
"on_WorkflowConfiguration": [
- 667
+ 670
],
"on_WorkflowRunConfiguration": [
- 668
+ 671
],
"on_WorkflowVersionConfiguration": [
- 669
+ 672
],
"__typename": [
1
@@ -16035,7 +16122,7 @@ export default {
"WorkflowActionType": {},
"WorkflowConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -16043,7 +16130,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -16051,7 +16138,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 664
+ 667
],
"__typename": [
1
@@ -16059,7 +16146,7 @@ export default {
},
"Workspace": {
"activationStatus": [
- 671
+ 674
],
"aiAdditionalInstructions": [
1
@@ -16080,7 +16167,7 @@ export default {
1
],
"aiModelIdByTier": [
- 324
+ 327
],
"allowImpersonation": [
4
@@ -16089,19 +16176,19 @@ export default {
1
],
"billingCustomer": [
- 101
+ 102
],
"billingEntitlements": [
- 103
+ 104
],
"billingSubscriptions": [
- 119
+ 120
],
"createdAt": [
- 212
+ 213
],
"currentBillingSubscription": [
- 119
+ 120
],
"customDomain": [
1
@@ -16110,10 +16197,10 @@ export default {
1
],
"defaultRole": [
- 457
+ 460
],
"deletedAt": [
- 212
+ 213
],
"displayName": [
1
@@ -16125,7 +16212,7 @@ export default {
6
],
"featureFlags": [
- 265
+ 266
],
"hasValidEnterpriseValidityToken": [
4
@@ -16134,13 +16221,13 @@ export default {
4
],
"id": [
- 534
+ 537
],
"iframeMediaPermissions": [
- 307
+ 310
],
"installedApplications": [
- 47
+ 48
],
"inviteHash": [
1
@@ -16191,7 +16278,7 @@ export default {
1
],
"logoFileId": [
- 534
+ 537
],
"metadataVersion": [
6
@@ -16203,40 +16290,40 @@ export default {
6
],
"updatedAt": [
- 212
+ 213
],
"viewFields": [
- 649
+ 652
],
"viewFilterGroups": [
- 652
+ 655
],
"viewFilters": [
- 651
+ 654
],
"viewGroups": [
- 655
+ 658
],
"viewSorts": [
- 658
+ 661
],
"views": [
- 646
+ 649
],
"workspaceCustomApplication": [
- 47
+ 48
],
"workspaceCustomApplicationId": [
1
],
"workspaceDiscoverability": [
- 676
+ 679
],
"workspaceMembersCount": [
6
],
"workspaceUrls": [
- 688
+ 691
],
"__typename": [
1
@@ -16260,19 +16347,19 @@ export default {
"WorkspaceCompanyEnrichmentOutcome": {},
"WorkspaceCompanyEnrichmentResult": {
"enrichment": [
- 324
+ 327
],
"isBookCallOnboardingStepPending": [
4
],
"outcome": [
- 673
+ 676
],
"personEnrichment": [
- 324
+ 327
],
"personOutcome": [
- 686
+ 689
],
"__typename": [
1
@@ -16295,13 +16382,13 @@ export default {
1
],
"expiresAt": [
- 212
+ 213
],
"id": [
- 534
+ 537
],
"roleId": [
- 534
+ 537
],
"__typename": [
1
@@ -16326,28 +16413,28 @@ export default {
1
],
"dateFormat": [
- 681
+ 684
],
"id": [
- 534
+ 537
],
"locale": [
1
],
"name": [
- 290
+ 291
],
"numberFormat": [
- 682
+ 685
],
"openRecordIn": [
- 403
+ 406
],
"roles": [
- 457
+ 460
],
"timeFormat": [
- 683
+ 686
],
"timeZone": [
1
@@ -16359,10 +16446,10 @@ export default {
1
],
"userId": [
- 534
+ 537
],
"userWorkspaceId": [
- 534
+ 537
],
"__typename": [
1
@@ -16370,13 +16457,13 @@ export default {
},
"WorkspaceMemberApplicationVariables": {
"userWorkspaceId": [
- 534
+ 537
],
"variables": [
- 635
+ 638
],
"workspaceMemberId": [
- 534
+ 537
],
"__typename": [
1
@@ -16387,7 +16474,7 @@ export default {
"WorkspaceMemberTimeFormatEnum": {},
"WorkspaceMigration": {
"actions": [
- 324
+ 327
],
"applicationUniversalIdentifier": [
1
@@ -16401,7 +16488,7 @@ export default {
1
],
"id": [
- 534
+ 537
],
"__typename": [
1
@@ -16422,10 +16509,10 @@ export default {
},
"WorkspaceUrlsAndId": {
"id": [
- 534
+ 537
],
"workspaceUrls": [
- 688
+ 691
],
"__typename": [
1
diff --git a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
index d91eb652505..2ec5499f3eb 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
@@ -133,7 +133,7 @@ Notes:
## Checking before you spend
-A workspace can run out of credits. When that happens your function is refused before your code starts, and the platform's own work stops too: `runAgent` returns an error instead of running, and the other AI entry points refuse outright. `sendInboxMessage` runs no model and adds no AI charge of its own, though the function calling it is refused like any other; a member's reply is charged like any chat turn. Uninstall and disconnect hooks are the exception and always run, so an app can still be removed cleanly. An execution that does get through can still fail late, on a platform call it did not write, if the workspace runs out mid-run.
+A workspace can run out of credits. When that happens your function is refused before your code starts, and the platform's own work stops too: `runAgent` returns an error instead of running, and the other AI entry points refuse outright. `sendInboxMessage` runs no model and adds no AI charge of its own, though the function calling it is refused like any other; a member's reply is charged like any chat turn. Uninstall and disconnect hooks are the exception and always run, so an app can still be removed cleanly. An execution that does get through can still fail late, on a platform call it did not write, if the workspace runs out mid-run; `ai.generate` then resolves with `success: false` and the reason in `error`.
Ask first:
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 5ae2d2de7ed..2bab63f8c2a 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -620,7 +620,7 @@ Check `context.workspaceMemberId` when a function behaves differently depending
</Note>
-The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits). `ai.generate` follows the default clients instead: it acts as the person who triggered the run, within your app's role, or as your app when nobody did.
#### Exposing a function as an AI tool or workflow action
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 a3952ebd86d..c84d5461055 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
@@ -146,7 +146,7 @@ to `defineAgent()`, and pass what you want it to work on as `input`:
```ts src/logic-functions/run-enricher.ts
import { runAgent } from 'twenty-sdk/logic-function';
-const { threadId, status, result, error, success } = await runAgent({
+const { threadId, runId, status, result, error, success } = await runAgent({
agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
input: 'Enrich House Ad <recordId>: fill empty fields from its listing URL.',
});
@@ -329,6 +329,188 @@ name a member at all.
for.
</Warning>
+### Following a conversation
+
+An app reads the conversations it holds with its agents through the same API
+as the chat: `listConversationMessages()` returns its history, and
+`streamConversation()` yields its live events, token by token. Name the
+conversation by the agent and the `thread` key you pass to `runAgent()`; you
+can start following it before the first run reaches it.
+
+```ts src/logic-functions/follow-conversation.ts
+import {
+ isAgentChatTurnEndEvent,
+ listConversationMessages,
+ streamConversation,
+} from 'twenty-sdk/logic-function';
+
+const conversation = {
+ agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
+ threadKey: `${channelId}:${threadTs}`,
+};
+const abortController = new AbortController();
+let maxCatchupSeq: number | undefined;
+
+// subscribe before reading the history, so nothing streamed in between is lost
+for await (const event of streamConversation({
+ ...conversation,
+ signal: abortController.signal,
+})) {
+ if (event.type === 'keepalive' && maxCatchupSeq === undefined) {
+ const { messages, streamCatchup } =
+ await listConversationMessages(conversation);
+
+ showMessages(messages);
+ for (const chunk of streamCatchup.chunks) showChunk(chunk);
+ maxCatchupSeq = streamCatchup.maxSeq;
+ }
+
+ if (
+ event.type === 'stream-chunk' &&
+ (event.seq ?? 0) > (maxCatchupSeq ?? 0)
+ ) {
+ // an AI SDK UIMessageChunk, such as { type: 'text-delta', delta }
+ showChunk(event.chunk);
+ }
+
+ // the reply's save, or why it stopped, such as credits-exhausted
+ if (isAgentChatTurnEndEvent(event)) {
+ abortController.abort();
+ }
+}
+```
+
+- Events are the chat's own: `stream-chunk` carries an AI SDK
+ `UIMessageChunk` and a `seq`, and notifications such as `message-persisted`
+ (a message was saved: a member's, or the reply, which carries its run's
+ `turnId`), `credits-exhausted` (the reply stopped when the workspace ran
+ out of credits), `queue-updated` or `stream-error` say when
+ to read the history again. A `keepalive` comes once connected, then every
+ few seconds: read the history on the first one, since what happened before
+ it is there.
+- To turn chunks into messages as the chat does, pipe them into
+ `readUIMessageStream()` from the `ai` package.
+- `listConversationMessages()` returns `{ messages, streamCatchup }`: the saved
+ messages as AI SDK `UIMessage`s, as the chat builds them, and the chunks of
+ a reply still streaming. Show those chunks, then skip live chunks whose
+ `seq` is at most `streamCatchup.maxSeq`, since they repeat them.
+- `runAgent()` returns `runId`, the turn the call opens: messages of that run
+ carry it as `metadata.turnId`. A run that waits goes on in later turns of
+ the conversation.
+- The stream stays open until you abort its `signal` or `break`, and throws if
+ the connection drops: stream again to resume.
+- An app reads only its own conversations. Turns a member opened elsewhere,
+ such as in the chat, show only their text, in the history, live and in the
+ agent's next run: live, their other chunks arrive as empty
+ `message-metadata` chunks, so `seq` stays gapless. Turns your app ran as a
+ member (see above) stay whole when it reads on its own.
+- Requires `"engines": { "twenty": ">=2.56.0" }`.
+
+</Accordion>
+<Accordion title="ai.generate" description="Call a model from a logic function, without an agent">
+
+`ai.generate()` calls a model from a logic function. Unlike
+`runAgent()`, it needs no `defineAgent()`: the call carries its own
+instructions, and opens no conversation. Use it for one-shot work such as
+classifying, summarizing or extracting.
+
+```ts
+import { ai } from 'twenty-sdk/logic-function';
+
+const { success, text, error } = await ai.generate({
+ instructions: 'You qualify inbound leads for a B2B CRM.',
+ input: `Is ${companyName} a good fit? Answer in one sentence.`,
+});
+```
+
+- `input` is a string, or a list of `{ role: 'user' | 'assistant', content }`
+ messages.
+- `instructions` (optional) adds the caller's system instructions.
+- `modelId` (optional) picks the model. Without it, the call uses the
+ workspace's default model.
+- `responseFormat` (optional) works as in `runAgent()`. With
+ `{ type: 'json', schema }`, the schema goes on the model request itself, so
+ a JSON answer takes one request (plus tool steps when a `scope` grants
+ tools).
+- `scope` (optional) lets the call use the database, as described below.
+
+It resolves to `{ success, text, object, error, runId, usage }`:
+
+- `text` is the reply of a text response, and `null` for a JSON one.
+- `object` is the result of a JSON response, and `null` otherwise.
+- `error` explains a failed run, when `success` is `false`. A run that fails
+ resolves this way rather than throwing; a call that cannot start a run, such
+ as one with invalid input, throws.
+- `runId` identifies the recorded run, with its model, usage and credits.
+- `usage` is `{ inputTokens, outputTokens }`: what the run spent, including the
+ steps that finished before a failure.
+
+The call acts as whoever made it: the member a user-scoped token belongs to,
+otherwise your application, otherwise the API key. From a logic function it
+follows the default clients: it acts as the person who triggered the run, or as
+your application when nobody did. It never exceeds your application's role, and
+an application without a default role cannot call it.
+
+Without `scope`, the call reads and writes no records. To let it use the
+database, pass a `scope`, written like a role's permissions:
+
+```ts
+const { object } = await ai.generate({
+ input: `Find the open opportunities of ${companyName} and rate their risk.`,
+ responseFormat: {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { risk: { type: 'string' } },
+ required: ['risk'],
+ },
+ },
+ scope: {
+ objectPermissions: [
+ { objectUniversalIdentifier: OPPORTUNITY_UID, canReadObjectRecords: true },
+ ],
+ },
+});
+```
+
+A scope only narrows: it grants nothing the caller doesn't already have.
+
+To show the reply while it is written, pass `onChunk`. The call still resolves
+to the same result, once the last chunk was handed to `onChunk`. If the
+stream's end never arrives, it stops waiting once the result is in and 5 s
+pass without a new chunk, and still hands over every chunk received by then:
+
+```ts
+const abortController = new AbortController();
+
+const { text } = await ai.generate({
+ input: `Draft a follow-up email to ${companyName}.`,
+ onChunk: (chunk) => {
+ // an AI SDK UIMessageChunk, such as { type: 'text-delta', delta }
+ },
+ signal: abortController.signal,
+});
+```
+
+- The call follows the run through the same subscription as
+ `streamConversation()`: it subscribes first, waits until the subscription is
+ live, then starts the run, so it misses no chunk.
+- Chunks are the chat's own: pipe them into `readUIMessageStream()` from the
+ `ai` package to build the message.
+- `signal` aborts the call: it rejects with the abort error and closes the
+ stream. The run itself goes on, and is recorded as usual.
+- Once the stream is live, a failure of it only stops the chunks: the call
+ still resolves with the run's result, which is billed either way. The call
+ rejects when the subscription fails before it goes live, so the run never
+ starts, or when `onChunk` throws.
+- An app follows only its own runs, so `onChunk` needs an app token.
+- Requires `"engines": { "twenty": ">=2.56.0" }`.
+
+<Note>
+ `ai.generate()` requires the AI permission flag on the app's default role,
+ like `runAgent()`.
+</Note>
+
</Accordion>
<Accordion title="sendInboxMessage" description="Start or continue a conversation in members' chats">
diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
index 4fe7c278c5d..d2b6fa329ef 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
@@ -107,7 +107,12 @@ Their inputs match the steps of the [workflow builder](/user-guide/workflows/cap
- Filter operands take `ViewFilterOperand` values, exported by `twenty-sdk/define`. Filter group operators take string values such as `'AND'` or `'OR'`.
- Form fields of type `RECORD` name their object with `settings.objectUniversalIdentifier`. Fields of type `SELECT` and `MULTI_SELECT` offer the options of an existing field of the same type, named with `settings.selectedFieldUniversalIdentifier`.
- To run your own code, use a `LOGIC_FUNCTION` step. The builder's Code step is not available.
-- `AI_AGENT` steps run one of your app's agents, named with `agentUniversalIdentifier`, and take the builder's step settings: `prompt`, `responseFormat`, `humanInputInstructions`, `conversation`, and `workspaceMemberId` for the member the agent's conversation is with.
+- `AI_AGENT` steps come in two kinds, which you can't mix:
+ - A Generate step has no agent. It carries its own `instructions`, `modelId`, `modelConfiguration` and `scope`, and runs once: no conversation, no human input, no waiting.
+ - An Agent step runs one of your app's agents, named with `agentUniversalIdentifier`, which brings its own instructions, model and permissions. Only an Agent step takes `humanInputInstructions` and `conversation`.
+
+ Both kinds take the builder's `prompt` and `responseFormat`, and `workspaceMemberId` for the member the agent's conversation is with.
+- An `AI_AGENT` step's `scope` takes a role's permissions without its identity or row-level predicates: `canReadAllObjectRecords`, `objectPermissions` and `fieldPermissions` by universal identifier, `permissionFlagUniversalIdentifiers`, and so on. It only restricts: the step's AI never reaches more than whoever runs the workflow. It resolves like a role whose all-records flags default to off: object actions and permission flags it doesn't grant are denied, system objects stay readable unless it grants more, and a field it doesn't list follows its object. A Generate step without a `scope` gets no data tools; an Agent step runs with its agent's role.
- Email and calendar steps run only if your app's role has the matching permission flag: `SystemPermissionFlag.SEND_EMAIL_TOOL` for `SEND_EMAIL` and `DRAFT_EMAIL`, `SystemPermissionFlag.CREATE_CALENDAR_EVENT_TOOL` for `CREATE_CALENDAR_EVENT`. The workspace grants it by installing the app, and the step can then use any connected account in the workspace, like a workflow built in the app.
- Connected account ids are local to each workspace, so don't hardcode one. Name the account in one of two ways:
- `connectedAccountHandle`: the account's email address, such as `'[email protected]'`. When the app is synced, the handle resolves to an account with that address that is shared with the workspace (`WORKSPACE` scope) and can run the step. A member's private account can't be named by handle: pull keeps it as its `connectedAccountId`. If several accounts share the address, for example one mailbox connected by two members or through two providers, the oldest one wins. If none matches, the sync fails and names the handle. This is not `fromHandle`, which picks an alias to send from.
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 4868435a35e..89d9df8a328 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -331,7 +331,7 @@ export type GetAgentRunsQueryVariables = Exact<{
}>;
-export type GetAgentRunsQuery = { agentRuns: Array<{ __typename: 'AgentRun', id: string, threadId: string, threadTitle: string | null, status: Types.AgentTurnStatus, errorMessage: string | null, createdAt: string, startedAt: string | null, endedAt: string | null, modelId: string | null, inputTokens: number | null, outputTokens: number | null, credits: number | null, creatorSource: string, creatorName: string, input: string | null, reply: string | null, toolNames: Array<string> }> };
+export type GetAgentRunsQuery = { agentRuns: Array<{ __typename: 'AgentRun', id: string, threadId: string | null, threadTitle: string | null, status: Types.AgentTurnStatus, errorMessage: string | null, createdAt: string, startedAt: string | null, endedAt: string | null, modelId: string | null, inputTokens: number | null, outputTokens: number | null, credits: number | null, creatorSource: string, creatorName: string, input: string | null, reply: string | null, toolNames: Array<string> }> };
export type GetAiChatUsageQueryVariables = Exact<{ [key: string]: never; }>;
@@ -362,7 +362,7 @@ export type OnAgentChatEventSubscriptionVariables = Exact<{
}>;
-export type OnAgentChatEventSubscription = { onAgentChatEvent: { __typename: 'AgentChatEvent', threadId: string, event: any } };
+export type OnAgentChatEventSubscription = { onAgentChatEvent: { __typename: 'AgentChatEvent', threadId: string | null, event: any } };
export type TrackAnalyticsMutationVariables = Exact<{
type: Types.AnalyticsType;
diff --git a/packages/twenty-front/src/generated-metadata/schema.ts b/packages/twenty-front/src/generated-metadata/schema.ts
index 16eb5157972..9938ec0556c 100644
--- a/packages/twenty-front/src/generated-metadata/schema.ts
+++ b/packages/twenty-front/src/generated-metadata/schema.ts
@@ -115,7 +115,7 @@ export enum AgentChatChannelThreadStatus {
export type AgentChatEvent = {
__typename?: 'AgentChatEvent';
event: Scalars['JSON']['output'];
- threadId: Scalars['String']['output'];
+ threadId?: Maybe<Scalars['String']['output']>;
};
export enum AgentChatInboxAction {
@@ -246,7 +246,7 @@ export type AgentRun = {
reply?: Maybe<Scalars['String']['output']>;
startedAt?: Maybe<Scalars['DateTime']['output']>;
status: AgentTurnStatus;
- threadId: Scalars['UUID']['output'];
+ threadId?: Maybe<Scalars['UUID']['output']>;
threadTitle?: Maybe<Scalars['String']['output']>;
toolNames: Array<Scalars['String']['output']>;
};
@@ -320,6 +320,12 @@ export enum AiModelTier {
smart = 'smart'
}
+export type AiRunUsage = {
+ __typename?: 'AiRunUsage';
+ inputTokens: Scalars['Int']['output'];
+ outputTokens: Scalars['Int']['output'];
+};
+
export type AiSystemPromptPreview = {
__typename?: 'AiSystemPromptPreview';
estimatedTokenCount: Scalars['Int']['output'];
@@ -2726,6 +2732,25 @@ export type FullName = {
lastName: Scalars['String']['output'];
};
+export type GenerateInput = {
+ input: Array<RunAgentMessageInput>;
+ instructions?: InputMaybe<Scalars['String']['input']>;
+ modelId?: InputMaybe<Scalars['String']['input']>;
+ responseFormat?: InputMaybe<Scalars['JSON']['input']>;
+ runId?: InputMaybe<Scalars['UUID']['input']>;
+ scope?: InputMaybe<Scalars['JSON']['input']>;
+};
+
+export type GenerateResult = {
+ __typename?: 'GenerateResult';
+ error?: Maybe<Scalars['String']['output']>;
+ object?: Maybe<Scalars['JSON']['output']>;
+ runId: Scalars['UUID']['output'];
+ success: Scalars['Boolean']['output'];
+ text?: Maybe<Scalars['String']['output']>;
+ usage: AiRunUsage;
+};
+
export type GetApiKeyInput = {
id: Scalars['UUID']['input'];
};
@@ -3615,6 +3640,7 @@ export type Mutation = {
enqueueJobs: EnqueueJobsResult;
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult;
executeOneLogicFunction: LogicFunctionExecutionResult;
+ generate: GenerateResult;
generateApiKeyToken: ApiKeyToken;
generateFrontComponentApplicationTokenPair: ApplicationTokenPair;
generatePlaygroundToken: AuthToken;
@@ -4460,6 +4486,11 @@ export type MutationExecuteOneLogicFunctionArgs = {
};
+export type MutationGenerateArgs = {
+ input: GenerateInput;
+};
+
+
export type MutationGenerateApiKeyTokenArgs = {
apiKeyId: Scalars['UUID']['input'];
expiresAt: Scalars['String']['input'];
@@ -6078,12 +6109,16 @@ export type QueryCallRecordingIdForCalendarEventArgs = {
export type QueryChatMessagesArgs = {
- threadId: Scalars['UUID']['input'];
+ agentUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
+ threadId?: InputMaybe<Scalars['UUID']['input']>;
+ threadKey?: InputMaybe<Scalars['String']['input']>;
};
export type QueryChatStreamCatchupChunksArgs = {
- threadId: Scalars['UUID']['input'];
+ agentUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
+ threadId?: InputMaybe<Scalars['UUID']['input']>;
+ threadKey?: InputMaybe<Scalars['String']['input']>;
};
@@ -6828,6 +6863,7 @@ export type RunAgentResult = {
__typename?: 'RunAgentResult';
error?: Maybe<Scalars['String']['output']>;
result?: Maybe<Scalars['JSON']['output']>;
+ runId: Scalars['UUID']['output'];
status: Scalars['String']['output'];
success: Scalars['Boolean']['output'];
threadId: Scalars['UUID']['output'];
@@ -7118,7 +7154,10 @@ export type SubscriptionLogicFunctionLogsArgs = {
export type SubscriptionOnAgentChatEventArgs = {
- threadId: Scalars['UUID']['input'];
+ agentUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
+ runId?: InputMaybe<Scalars['UUID']['input']>;
+ threadId?: InputMaybe<Scalars['UUID']['input']>;
+ threadKey?: InputMaybe<Scalars['String']['input']>;
};
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
index 98b2899fa89..03345153063 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
@@ -1,7 +1,10 @@
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
import { useStore } from 'jotai';
import { useCallback } from 'react';
-import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+import {
+ type AgentChatSubscriptionEvent,
+ mapAgentMessagesToUIMessages,
+} from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
@@ -17,7 +20,6 @@ import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoad
import { agentChatQueuedMessagesFamilyState } from '@/ai/states/agentChatQueuedMessagesFamilyState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';
-import { mapDBMessagesToUIMessages } from '@/ai/utils/mapDBMessagesToUIMessages';
import { SSE_CLIENT_RECONNECTED_EVENT_NAME } from '@/sse-db-event/constants/SseClientReconnectedEventName';
import { useQueryWithCallbacks } from '@/apollo/hooks/useQueryWithCallbacks';
import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
@@ -73,7 +75,7 @@ export const AgentChatMessagesFetchEffect = () => {
if (isGraphqlErrorOfType(error, 'NOT_FOUND')) {
return;
}
- const uiMessages = mapDBMessagesToUIMessages(data.chatMessages ?? []);
+ const uiMessages = mapAgentMessagesToUIMessages(data.chatMessages ?? []);
// A live snapshot is at least as recent as a fetch, which may have been read before it
const liveReactionRevisions = store.get(
agentChatLiveReactionRevisionsFamilyState.atomFamily({
diff --git a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts b/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts
deleted file mode 100644
index 9c4ac50d8c8..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { mapDBPartToUIMessagePart } from '@/ai/utils/mapDBPartToUIMessagePart';
-import { AGENT_MESSAGE_ROLE } from '@/ai/constants/AgentMessageRole';
-import { type ExtendedUIMessage } from 'twenty-shared/ai';
-import { isDefined } from 'twenty-shared/utils';
-import { type AgentMessage } from '~/generated-metadata/graphql';
-
-export const mapDBMessagesToUIMessages = (
- dbMessages: AgentMessage[],
-): ExtendedUIMessage[] => {
- return dbMessages.map((dbMessage) => ({
- id: dbMessage.id,
- role: dbMessage.role as ExtendedUIMessage['role'],
- status: dbMessage.status as 'queued' | 'sent',
- parts: [...dbMessage.parts]
- .sort((a, b) => a.orderIndex - b.orderIndex)
- .map(mapDBPartToUIMessagePart)
- .filter(isDefined),
- metadata: {
- createdAt: dbMessage.createdAt,
- senderWorkspaceMemberId: dbMessage.senderWorkspaceMemberId,
- ...(dbMessage.role === AGENT_MESSAGE_ROLE.ASSISTANT
- ? {
- startedAt: dbMessage.createdAt,
- // the assistant message is rewritten until its stream finishes
- finishedAt: dbMessage.processedAt ?? undefined,
- }
- : {}),
- },
- threadId: dbMessage.threadId,
- }));
-};
diff --git a/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts b/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
deleted file mode 100644
index 229e0721a11..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { type ReasoningUIPart } from 'ai';
-import {
- type ExtendedFileUIPart,
- type ExtendedUIMessagePart,
-} from 'twenty-shared/ai';
-import { type AgentMessagePart } from '~/generated-metadata/graphql';
-
-// keep in sync with packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util.ts
-
-export const mapDBPartToUIMessagePart = (
- part: AgentMessagePart,
-): ExtendedUIMessagePart | null => {
- switch (part.type) {
- case 'text':
- return {
- type: 'text',
- text: part.textContent!,
- };
- case 'reasoning':
- return {
- type: 'reasoning',
- text: part.reasoningContent ?? '',
- state: part.state as ReasoningUIPart['state'],
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'file':
- return {
- type: 'file',
- mediaType: part.fileMediaType!,
- filename: part.fileFilename!,
- url: part.fileUrl!,
- fileId: part.fileId!,
- } as ExtendedFileUIPart;
- case 'source-url':
- return {
- type: 'source-url',
- sourceId: part.sourceUrlSourceId!,
- url: part.sourceUrlUrl!,
- title: part.sourceUrlTitle!,
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'source-document':
- return {
- type: 'source-document',
- sourceId: part.sourceDocumentSourceId!,
- mediaType: part.sourceDocumentMediaType!,
- title: part.sourceDocumentTitle!,
- filename: part.sourceDocumentFilename!,
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'step-start':
- return {
- type: part.type,
- };
- default: {
- const isStaticToolPart = part.type.startsWith('tool-');
- const isDynamicToolPart = part.type === 'dynamic-tool';
-
- if (isStaticToolPart || isDynamicToolPart) {
- return {
- type: part.type as `tool-${string}` | 'dynamic-tool',
- ...(isDynamicToolPart && { toolName: part.toolName ?? '' }),
- toolCallId: part.toolCallId!,
- input: part.toolInput ?? {},
- output: part.toolOutput,
- errorText: part.errorMessage!,
- state: part.state,
- ...(part.providerExecuted != null && {
- providerExecuted: part.providerExecuted,
- }),
- ...(part.providerMetadata != null && {
- callProviderMetadata: part.providerMetadata,
- }),
- } as ExtendedUIMessagePart;
- }
-
- return null;
- }
- }
-};
diff --git a/packages/twenty-front/src/modules/marketplace/utils/buildPermissionFlagSummary.ts b/packages/twenty-front/src/modules/marketplace/utils/buildPermissionFlagSummary.ts
index 5b1fbca9372..ae97a0f6f13 100644
--- a/packages/twenty-front/src/modules/marketplace/utils/buildPermissionFlagSummary.ts
+++ b/packages/twenty-front/src/modules/marketplace/utils/buildPermissionFlagSummary.ts
@@ -1,5 +1,5 @@
import { PERMISSION_FLAG_SUMMARY_CONFIGS } from '@/marketplace/constants/PermissionFlagSummaryConfigs';
-import { PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER } from '@/marketplace/constants/PermissionFlagTypeByUniversalIdentifier';
+import { PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER } from 'twenty-shared/constants';
import { type PermissionSummaryItem } from '@/marketplace/types/PermissionSummaryItem';
import { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx
index 2a6c4ddc3ac..39d2e587700 100644
--- a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx
+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx
@@ -1,3 +1,4 @@
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { useState } from 'react';
@@ -138,7 +139,7 @@ export const CoreAgentFormContent = ({ agent }: CoreAgentFormContentProps) => {
];
const title = agent.label;
- const AgentIcon = getIcon(formValues.icon || 'IconLego');
+ const AgentIcon = getIcon(getAgentIcon(formValues.icon));
const isRoleTab = activeTabId === CORE_AGENT_DETAIL_TABS.TABS_IDS.ROLE;
const isSettingsTab =
diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentNameCell.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentNameCell.tsx
index 0741dda3821..bc0c6a22e90 100644
--- a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentNameCell.tsx
+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentNameCell.tsx
@@ -1,8 +1,8 @@
-import { isNonEmptyString } from '@sniptt/guards';
import { useIcons } from 'twenty-ui/icon/provider';
import { CoreObjectNameCell } from '@/object-core/components/cells/CoreObjectNameCell';
import { type CoreAgent } from '@/object-core/agents/types/CoreAgent';
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
type CoreAgentNameCellProps = {
agent: Pick<CoreAgent, 'id' | 'label' | 'icon'>;
@@ -16,7 +16,7 @@ export const CoreAgentNameCell = ({ agent }: CoreAgentNameCellProps) => {
name={agent.label}
avatarColorSeed={agent.id}
avatarShape="square"
- Icon={getIcon(isNonEmptyString(agent.icon) ? agent.icon : 'IconLego')}
+ Icon={getIcon(getAgentIcon(agent.icon))}
/>
);
};
diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentSettingsTab.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentSettingsTab.tsx
index 330ca354428..523153a83ba 100644
--- a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentSettingsTab.tsx
+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentSettingsTab.tsx
@@ -1,3 +1,4 @@
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
@@ -78,7 +79,7 @@ export const CoreAgentSettingsTab = ({
<StyledFormContainer>
<StyledIconNameRow>
<IconPicker
- selectedIconKey={formValues.icon || 'IconLego'}
+ selectedIconKey={getAgentIcon(formValues.icon)}
onChange={({ iconKey }) => {
onFieldChange('icon', iconKey);
}}
diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/groupCoreAgentRunsByConversation.test.ts b/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/groupCoreAgentRunsByConversation.test.ts
index ded3a2e5c43..76d62568874 100644
--- a/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/groupCoreAgentRunsByConversation.test.ts
+++ b/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/groupCoreAgentRunsByConversation.test.ts
@@ -1,6 +1,12 @@
import { groupCoreAgentRunsByConversation } from '@/object-core/agents/utils/groupCoreAgentRunsByConversation';
-const buildRun = (id: string, threadId: string) => ({
+const buildRun = ({
+ id,
+ threadId,
+}: {
+ id: string;
+ threadId: string | null;
+}) => ({
id,
threadId,
threadTitle: `Conversation ${threadId}`,
@@ -9,15 +15,19 @@ const buildRun = (id: string, threadId: string) => ({
describe('groupCoreAgentRunsByConversation', () => {
it('keeps a conversation with a single run as a plain row', () => {
expect(
- groupCoreAgentRunsByConversation([buildRun('run-1', 'thread-1')]),
- ).toEqual([{ type: 'run', run: buildRun('run-1', 'thread-1') }]);
+ groupCoreAgentRunsByConversation([
+ buildRun({ id: 'run-1', threadId: 'thread-1' }),
+ ]),
+ ).toEqual([
+ { type: 'run', run: buildRun({ id: 'run-1', threadId: 'thread-1' }) },
+ ]);
});
it('folds runs of one conversation under it, at the position of its latest run', () => {
const runs = [
- buildRun('run-3', 'thread-a'),
- buildRun('run-2', 'thread-b'),
- buildRun('run-1', 'thread-a'),
+ buildRun({ id: 'run-3', threadId: 'thread-a' }),
+ buildRun({ id: 'run-2', threadId: 'thread-b' }),
+ buildRun({ id: 'run-1', threadId: 'thread-a' }),
];
expect(groupCoreAgentRunsByConversation(runs)).toEqual([
@@ -30,4 +40,16 @@ describe('groupCoreAgentRunsByConversation', () => {
{ type: 'run', run: runs[1] },
]);
});
+
+ it('lists a run without a conversation as a plain row', () => {
+ const runs = [
+ buildRun({ id: 'run-2', threadId: null }),
+ buildRun({ id: 'run-1', threadId: null }),
+ ];
+
+ expect(groupCoreAgentRunsByConversation(runs)).toEqual([
+ { type: 'run', run: runs[0] },
+ { type: 'run', run: runs[1] },
+ ]);
+ });
});
diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/getAgentIcon.ts b/packages/twenty-front/src/modules/object-core/agents/utils/getAgentIcon.ts
new file mode 100644
index 00000000000..b8a1ce5e29b
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-core/agents/utils/getAgentIcon.ts
@@ -0,0 +1,4 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+export const getAgentIcon = (icon: string | null | undefined): string =>
+ isNonEmptyString(icon) ? icon : 'IconLego';
diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts b/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts
index f289c6561b5..76783288d57 100644
--- a/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts
+++ b/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts
@@ -1,3 +1,4 @@
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
import { type FindOneAgentQuery } from '~/generated-metadata/graphql';
import { type CoreAgentFormValues } from '@/object-core/agents/validation-schemas/coreAgentFormSchema';
import { coreAgentTriggerSchema } from '@/object-core/agents/validation-schemas/coreAgentTriggerSchema';
@@ -18,7 +19,7 @@ export const getCoreAgentInitialFormValues = (
name: agent.name,
label: agent.label,
description: agent.description,
- icon: agent.icon || 'IconLego',
+ icon: getAgentIcon(agent.icon),
modelId: agent.modelId,
role: agent.roleId,
prompt: agent.prompt,
diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/groupCoreAgentRunsByConversation.ts b/packages/twenty-front/src/modules/object-core/agents/utils/groupCoreAgentRunsByConversation.ts
index 5486fe53815..072629b3b75 100644
--- a/packages/twenty-front/src/modules/object-core/agents/utils/groupCoreAgentRunsByConversation.ts
+++ b/packages/twenty-front/src/modules/object-core/agents/utils/groupCoreAgentRunsByConversation.ts
@@ -1,3 +1,5 @@
+import { isDefined } from 'twenty-shared/utils';
+
import { type CoreAgentRun } from '@/object-core/agents/types/CoreAgentRun';
import { type CoreAgentRunListItem } from '@/object-core/agents/types/CoreAgentRunListItem';
@@ -11,6 +13,10 @@ export const groupCoreAgentRunsByConversation = <
const runsByThreadId = new Map<string, TRun[]>();
for (const run of runs) {
+ if (!isDefined(run.threadId)) {
+ continue;
+ }
+
runsByThreadId.set(run.threadId, [
...(runsByThreadId.get(run.threadId) ?? []),
run,
@@ -20,6 +26,11 @@ export const groupCoreAgentRunsByConversation = <
const listedThreadIds = new Set<string>();
return runs.flatMap((run): CoreAgentRunListItem<TRun>[] => {
+ // a one-shot run has no conversation to fold under
+ if (!isDefined(run.threadId)) {
+ return [{ type: 'run', run }];
+ }
+
if (listedThreadIds.has(run.threadId)) {
return [];
}
diff --git a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/hooks/useUpsertObjectPermission.ts b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/hooks/useUpsertObjectPermission.ts
index 2a7c085c570..06ff4beb96b 100644
--- a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/hooks/useUpsertObjectPermission.ts
+++ b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/hooks/useUpsertObjectPermission.ts
@@ -1,9 +1,8 @@
+import { applyObjectPermissionChange } from '@/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange';
import { useUpsertObjectPermissionInDraftRole } from '@/settings/roles/role-permissions/object-level-permissions/hooks/useUpsertObjectPermissionInDraftRole';
import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
import { settingsDraftRoleFamilyState } from '@/settings/roles/states/settingsDraftRoleFamilyState';
import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';
-import { isDefined } from 'twenty-shared/utils';
-import { type ObjectPermission } from '~/generated-metadata/graphql';
export const useUpsertObjectPermission = ({ roleId }: { roleId: string }) => {
const settingsDraftRole = useAtomFamilyStateValue(
@@ -24,38 +23,15 @@ export const useUpsertObjectPermission = ({ roleId }: { roleId: string }) => {
objectPermissionToFind.objectMetadataId === objectMetadataItemId,
);
- const newPermissions = { [permissionKey]: value };
-
- const isHigherPermission =
- permissionKey === 'canUpdateObjectRecords' ||
- permissionKey === 'canSoftDeleteObjectRecords' ||
- permissionKey === 'canDestroyObjectRecords';
-
- if (isHigherPermission && value !== false) {
- newPermissions.canReadObjectRecords = value;
- }
-
- if (permissionKey === 'canReadObjectRecords' && value === false) {
- newPermissions.canUpdateObjectRecords = false;
- newPermissions.canSoftDeleteObjectRecords = false;
- newPermissions.canDestroyObjectRecords = false;
- }
-
- if (!isDefined(existingObjectPermission)) {
- const newObjectPermission = {
- objectMetadataId: objectMetadataItemId,
- ...newPermissions,
- } satisfies ObjectPermission;
-
- upsertObjectPermissionInDraftRole(newObjectPermission);
- } else {
- const updatedObjectPermission = {
- ...existingObjectPermission,
- ...newPermissions,
- };
-
- upsertObjectPermissionInDraftRole(updatedObjectPermission);
- }
+ upsertObjectPermissionInDraftRole(
+ applyObjectPermissionChange({
+ objectPermission: existingObjectPermission ?? {
+ objectMetadataId: objectMetadataItemId,
+ },
+ permissionKey,
+ value,
+ }),
+ );
};
return {
diff --git a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/__tests__/applyObjectPermissionChange.test.ts b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/__tests__/applyObjectPermissionChange.test.ts
new file mode 100644
index 00000000000..cd918667c79
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/__tests__/applyObjectPermissionChange.test.ts
@@ -0,0 +1,55 @@
+import { applyObjectPermissionChange } from '@/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange';
+
+describe('applyObjectPermissionChange', () => {
+ it('grants reading along with a change', () => {
+ expect(
+ applyObjectPermissionChange({
+ objectPermission: { objectMetadataId: 'person-id' },
+ permissionKey: 'canSoftDeleteObjectRecords',
+ value: true,
+ }),
+ ).toEqual({
+ objectMetadataId: 'person-id',
+ canReadObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
+ });
+ });
+
+ it('refuses every change along with reading', () => {
+ expect(
+ applyObjectPermissionChange({
+ objectPermission: {
+ objectMetadataId: 'person-id',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ permissionKey: 'canReadObjectRecords',
+ value: false,
+ }),
+ ).toEqual({
+ objectMetadataId: 'person-id',
+ canReadObjectRecords: false,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ });
+ });
+
+ it('resets reading along with a change reset to the role default', () => {
+ expect(
+ applyObjectPermissionChange({
+ objectPermission: {
+ objectMetadataId: 'person-id',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ permissionKey: 'canUpdateObjectRecords',
+ value: null,
+ }),
+ ).toEqual({
+ objectMetadataId: 'person-id',
+ canReadObjectRecords: null,
+ canUpdateObjectRecords: null,
+ });
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange.ts b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange.ts
new file mode 100644
index 00000000000..136f88342ad
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange.ts
@@ -0,0 +1,38 @@
+import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
+
+type ObjectPermissionValues = Partial<
+ Record<SettingsRoleObjectPermissionKey, boolean | null>
+>;
+
+// changing records needs reading them, so granting a change grants reading and refusing reading refuses every change
+export const applyObjectPermissionChange = <TObjectPermission extends object>({
+ objectPermission,
+ permissionKey,
+ value,
+}: {
+ objectPermission: TObjectPermission;
+ permissionKey: SettingsRoleObjectPermissionKey;
+ value: boolean | null;
+}): TObjectPermission & ObjectPermissionValues => {
+ const changedObjectPermission: TObjectPermission & ObjectPermissionValues = {
+ ...objectPermission,
+ [permissionKey]: value,
+ };
+
+ const isReadPermission = permissionKey === 'canReadObjectRecords';
+
+ if (!isReadPermission && value !== false) {
+ return { ...changedObjectPermission, canReadObjectRecords: value };
+ }
+
+ if (isReadPermission && value === false) {
+ return {
+ ...changedObjectPermission,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ };
+ }
+
+ return changedObjectPermission;
+};
diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelWorkflowStepInfo.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelWorkflowStepInfo.tsx
index 47ccbe82a7f..7ac51bb346c 100644
--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelWorkflowStepInfo.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelWorkflowStepInfo.tsx
@@ -9,11 +9,9 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { flowComponentState } from '@/workflow/states/flowComponentState';
import { useWorkflowWithCurrentVersion } from '@/workflow/hooks/useWorkflowWithCurrentVersion';
-import { getAgentIdFromStep } from '@/workflow/utils/getAgentIdFromStep';
import { getStepDefinitionOrThrow } from '@/workflow/utils/getStepDefinitionOrThrow';
import { getWorkflowStepDisplayName } from '@/workflow/utils/getWorkflowStepDisplayName';
import { getWorkflowVisualizerComponentInstanceId } from '@/workflow/utils/getWorkflowVisualizerComponentInstanceId';
-import { useUpdateAgentLabel } from '@/workflow/workflow-steps/hooks/useUpdateAgentLabel';
import { useUpdateStep } from '@/workflow/workflow-steps/hooks/useUpdateStep';
import { useUpdateTrigger } from '@/workflow/workflow-trigger/hooks/useUpdateTrigger';
import { useWorkflowVersionContent } from '@/workflow/workflow-version/hooks/useWorkflowVersionContent';
@@ -94,8 +92,6 @@ export const SidePanelWorkflowStepInfo = ({
const thirdPartyApplicationInformation =
useLogicFunctionThirdPartyApplicationInformation(logicFunctionId);
- const agentId = getAgentIdFromStep(stepDefinition);
- const { updateAgentLabel } = useUpdateAgentLabel(agentId);
const stepName =
isDefined(stepDefinition) && isDefined(stepDefinition.definition)
? isTrigger
@@ -157,7 +153,7 @@ export const SidePanelWorkflowStepInfo = ({
const Icon = getIcon(headerIcon ?? 'IconDefault');
- const saveTitle = async () => {
+ const saveTitle = () => {
if (!isDefined(workflowVersionId) || !isDefined(workflowId)) {
return;
}
@@ -177,10 +173,6 @@ export const SidePanelWorkflowStepInfo = ({
...stepDefinition.definition,
name: title,
});
-
- if (isDefined(agentId)) {
- await updateAgentLabel(title);
- }
}
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/AgentMenuItem.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/AgentMenuItem.tsx
new file mode 100644
index 00000000000..aba9ca3a490
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/AgentMenuItem.tsx
@@ -0,0 +1,29 @@
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
+import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
+import { ListItemIconContainer } from '@/ui/navigation/list-item/components/ListItemIconContainer';
+import { getActionIconColorOrThrow } from '@/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow';
+import { ListItemButton } from 'twenty-ui/components/navigation';
+import { useIcons } from 'twenty-ui/icon/provider';
+
+type AgentMenuItemProps = {
+ agent: Pick<FlatAgent, 'label' | 'icon'>;
+ onClick: () => void;
+};
+
+export const AgentMenuItem = ({ agent, onClick }: AgentMenuItemProps) => {
+ const { getIcon } = useIcons();
+ const Icon = getIcon(getAgentIcon(agent.icon));
+
+ return (
+ <ListItemButton
+ startIcon={
+ <ListItemIconContainer>
+ <Icon color={getActionIconColorOrThrow('AI_AGENT')} size={16} />
+ </ListItemIconContainer>
+ }
+ onClick={onClick}
+ >
+ {agent.label}
+ </ListItemButton>
+ );
+};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
index f6b578c5003..153879b01d7 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
@@ -2,6 +2,7 @@ import { aiEvaluationModelsState } from '@/client-config/states/aiEvaluationMode
import { isWorkspaceCustomApplication } from '@/applications/utils/isWorkspaceCustomApplication';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { logicFunctionsSelector } from '@/logic-functions/states/logicFunctionsSelector';
+import { AgentMenuItem } from '@/side-panel/pages/workflow/action/components/AgentMenuItem';
import { ToolMenuItem } from '@/side-panel/pages/workflow/action/components/ToolMenuItem';
import { WorkflowActionMenuItems } from '@/side-panel/pages/workflow/action/components/WorkflowActionMenuItems';
import { sortWorkflowActionLogicFunctions } from '@/side-panel/pages/workflow/action/utils/sortWorkflowActionLogicFunctions';
@@ -16,10 +17,15 @@ import { CORE_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constan
import { FLOW_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/FlowActions';
import { HUMAN_INPUT_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/HumanInputActions';
import { RECORD_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/RecordActions';
+import { isAgentSelectableAsWorkflowStep } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep';
+import { useQuery } from '@apollo/client/react';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
import { WORKFLOW_ACTION_FEATURE_FLAGS } from 'twenty-shared/workflow';
-import { FeatureFlagKey } from '~/generated-metadata/graphql';
+import {
+ FeatureFlagKey,
+ FindManyAgentsDocument,
+} from '~/generated-metadata/graphql';
export type WorkflowActionSelection = {
type: WorkflowActionType;
@@ -77,10 +83,25 @@ export const SidePanelWorkflowSelectAction = ({
installedApplications: currentWorkspace?.installedApplications ?? [],
});
+ const { data: agentsData } = useQuery(FindManyAgentsDocument, {
+ fetchPolicy: 'cache-and-network',
+ });
+
+ const stepAgents = (agentsData?.findManyAgents ?? []).filter(
+ isAgentSelectableAsWorkflowStep,
+ );
+
const handleActionClick = (actionType: WorkflowActionType) => {
onActionSelected({ type: actionType });
};
+ const handleAgentClick = (agentId: string) => {
+ onActionSelected({
+ type: 'AI_AGENT',
+ defaultSettings: { input: { agentId } },
+ });
+ };
+
const handleFunctionClick = (logicFunctionId: string) => {
onActionSelected({
type: 'LOGIC_FUNCTION',
@@ -108,6 +129,21 @@ export const SidePanelWorkflowSelectAction = ({
onClick={handleActionClick}
/>
+ {stepAgents.length > 0 && (
+ <>
+ <SidePanelWorkflowSelectStepTitle>
+ {t`Agents`}
+ </SidePanelWorkflowSelectStepTitle>
+ {stepAgents.map((agent) => (
+ <AgentMenuItem
+ key={agent.id}
+ agent={agent}
+ onClick={() => handleAgentClick(agent.id)}
+ />
+ ))}
+ </>
+ )}
+
<SidePanelWorkflowSelectStepTitle>
{t`Flow`}
</SidePanelWorkflowSelectStepTitle>
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
index 87a9c7c9286..296445c2083 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
@@ -1,6 +1,8 @@
+import { MockedProvider } from '@apollo/client/testing/react';
import { i18n, type MessageDescriptor } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { Provider as JotaiProvider } from 'jotai';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
@@ -9,7 +11,10 @@ import {
jotaiStore,
resetJotaiStore,
} from '@/ui/utilities/state/jotai/jotaiStore';
-import { FeatureFlagKey } from '~/generated-metadata/graphql';
+import {
+ FeatureFlagKey,
+ FindManyAgentsDocument,
+} from '~/generated-metadata/graphql';
import { messages } from '~/locales/generated/en';
i18n.load({ [SOURCE_LOCALE]: messages });
@@ -45,12 +50,68 @@ jest.mock(
}),
);
-const renderPicker = () =>
+const buildAgent = ({
+ id,
+ label,
+ responseFormat,
+}: {
+ id: string;
+ label: string;
+ responseFormat: object | null;
+}) => ({
+ __typename: 'Agent' as const,
+ id,
+ name: id,
+ label,
+ description: null,
+ icon: null,
+ prompt: 'Prompt',
+ modelId: 'workspace-default-model',
+ responseFormat,
+ roleId: null,
+ isSystem: false,
+ isActive: true,
+ modelConfiguration: null,
+ triggers: [],
+ applicationId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+});
+
+const FIND_MANY_AGENTS_MOCK = {
+ request: { query: FindManyAgentsDocument },
+ result: {
+ data: {
+ findManyAgents: [
+ buildAgent({
+ id: 'lead-scorer',
+ label: 'Lead scorer',
+ responseFormat: {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { score: { type: 'number' } },
+ },
+ },
+ }),
+ buildAgent({
+ id: 'chat-helper',
+ label: 'Chat helper',
+ responseFormat: { type: 'text' },
+ }),
+ ],
+ },
+ },
+};
+
+const renderPicker = (onActionSelected = jest.fn()) =>
render(
<JotaiProvider store={jotaiStore}>
- <I18nProvider i18n={i18n}>
- <SidePanelWorkflowSelectAction onActionSelected={jest.fn()} />
- </I18nProvider>
+ <MockedProvider mocks={[FIND_MANY_AGENTS_MOCK]}>
+ <I18nProvider i18n={i18n}>
+ <SidePanelWorkflowSelectAction onActionSelected={onActionSelected} />
+ </I18nProvider>
+ </MockedProvider>
</JotaiProvider>,
);
@@ -74,4 +135,24 @@ describe('SidePanelWorkflowSelectAction', () => {
expect(screen.getByText('Wait for Event')).toBeInTheDocument();
});
+
+ it('offers a Generate step', () => {
+ renderPicker();
+
+ expect(screen.getByText('Generate')).toBeInTheDocument();
+ });
+
+ it('lists only the agents with a JSON output, each creating a step that runs it', async () => {
+ const onActionSelected = jest.fn();
+
+ renderPicker(onActionSelected);
+
+ await userEvent.click(await screen.findByText('Lead scorer'));
+
+ expect(screen.queryByText('Chat helper')).not.toBeInTheDocument();
+ expect(onActionSelected).toHaveBeenCalledWith({
+ type: 'AI_AGENT',
+ defaultSettings: { input: { agentId: 'lead-scorer' } },
+ });
+ });
});
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/step/edit/components/SidePanelWorkflowEditStepTypeContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/step/edit/components/SidePanelWorkflowEditStepTypeContent.tsx
index 7e8be93ff86..a4611e342ee 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/step/edit/components/SidePanelWorkflowEditStepTypeContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/step/edit/components/SidePanelWorkflowEditStepTypeContent.tsx
@@ -17,7 +17,8 @@ import { workflowSelectedNodeComponentState } from '@/workflow/workflow-diagram/
import { useUpdateStep } from '@/workflow/workflow-steps/hooks/useUpdateStep';
import { getActionIcon } from '@/workflow/workflow-steps/workflow-actions/utils/getActionIcon';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
-import { isDefined } from 'twenty-shared/utils';
+import { isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
import { doNotTranslate } from 'twenty-shared/i18n';
import { useIcons } from 'twenty-ui/icon/provider';
@@ -56,10 +57,28 @@ export const SidePanelWorkflowEditStepTypeContent = () => {
throw new Error(doNotTranslate('Step not found'));
}
+ const selectedInput = selection.defaultSettings?.input;
+ const selectedAgentId =
+ isPlainObject(selectedInput) && isString(selectedInput.agentId)
+ ? selectedInput.agentId
+ : undefined;
+
+ // both AI step kinds share one type, so the agent picked (none for Generate) tells the server which to rebuild into
+ const settings =
+ existingStep.type === 'AI_AGENT' && selection.type === 'AI_AGENT'
+ ? {
+ ...existingStep.settings,
+ input: {
+ ...existingStep.settings.input,
+ agentId: selectedAgentId,
+ },
+ }
+ : (selection.defaultSettings ?? existingStep.settings);
+
const stepUpdate = {
...existingStep,
type: selection.type,
- settings: selection.defaultSettings ?? existingStep.settings,
+ settings,
};
const { updatedStep } = await updateStepNow(stepUpdate as WorkflowAction);
diff --git a/packages/twenty-front/src/modules/workflow/constants/WorkflowStepDefaultNames.ts b/packages/twenty-front/src/modules/workflow/constants/WorkflowStepDefaultNames.ts
index 4a562202a2d..03a501af0fa 100644
--- a/packages/twenty-front/src/modules/workflow/constants/WorkflowStepDefaultNames.ts
+++ b/packages/twenty-front/src/modules/workflow/constants/WorkflowStepDefaultNames.ts
@@ -28,6 +28,7 @@ import { WEBHOOK_TRIGGER } from '@/workflow/workflow-trigger/constants/triggers/
import { type MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
import { doNotTranslate } from 'twenty-shared/i18n';
+import { WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME } from 'twenty-shared/workflow';
export const WORKFLOW_STEP_DEFAULT_NAMES: Array<{
type: WorkflowActionType | WorkflowTriggerType;
@@ -106,7 +107,7 @@ export const WORKFLOW_STEP_DEFAULT_NAMES: Array<{
},
{
type: 'AI_AGENT',
- name: 'Agent',
+ name: WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME,
label: AI_AGENT_ACTION.defaultLabel,
},
{
diff --git a/packages/twenty-front/src/modules/workflow/utils/__tests__/getAgentIdFromStep.test.ts b/packages/twenty-front/src/modules/workflow/utils/__tests__/getAgentIdFromStep.test.ts
deleted file mode 100644
index 1933af3e0bf..00000000000
--- a/packages/twenty-front/src/modules/workflow/utils/__tests__/getAgentIdFromStep.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { getAgentIdFromStep } from '@/workflow/utils/getAgentIdFromStep';
-
-describe('getAgentIdFromStep', () => {
- it('should return undefined when stepDefinition is undefined', () => {
- const result = getAgentIdFromStep(undefined);
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when stepDefinition type is trigger', () => {
- const result = getAgentIdFromStep({
- type: 'trigger',
- definition: { type: 'DATABASE_EVENT' },
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when definition is undefined', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: undefined,
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when definition type is not AI_AGENT', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: { type: 'CREATE_RECORD' },
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when settings is missing', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: { type: 'AI_AGENT' },
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when settings.input is missing', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: {
- type: 'AI_AGENT',
- settings: {},
- },
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return undefined when settings.input.agentId is missing', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: {
- type: 'AI_AGENT',
- settings: {
- input: {},
- },
- },
- });
-
- expect(result).toBeUndefined();
- });
-
- it('should return agentId when all conditions are met', () => {
- const result = getAgentIdFromStep({
- type: 'action',
- definition: {
- type: 'AI_AGENT',
- settings: {
- input: {
- agentId: 'agent-123',
- },
- },
- },
- });
-
- expect(result).toBe('agent-123');
- });
-});
diff --git a/packages/twenty-front/src/modules/workflow/utils/getAgentIdFromStep.ts b/packages/twenty-front/src/modules/workflow/utils/getAgentIdFromStep.ts
deleted file mode 100644
index 804278c497b..00000000000
--- a/packages/twenty-front/src/modules/workflow/utils/getAgentIdFromStep.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-type StepDefinition = {
- type: 'trigger' | 'action';
- definition: any;
-};
-
-export const getAgentIdFromStep = (
- stepDefinition: StepDefinition | undefined,
-): string | undefined => {
- if (!isDefined(stepDefinition)) {
- return undefined;
- }
-
- if (stepDefinition.type === 'trigger') {
- return undefined;
- }
-
- const definition = stepDefinition.definition;
- if (!isDefined(definition)) {
- return undefined;
- }
-
- if (definition.type !== 'AI_AGENT') {
- return undefined;
- }
-
- if (
- !('settings' in definition) ||
- !isDefined(definition.settings) ||
- !('input' in definition.settings) ||
- !isDefined(definition.settings.input) ||
- !('agentId' in definition.settings.input)
- ) {
- return undefined;
- }
-
- return definition.settings.input.agentId;
-};
diff --git a/packages/twenty-front/src/modules/workflow/utils/keepServerStepResourceIds.ts b/packages/twenty-front/src/modules/workflow/utils/keepServerStepResourceIds.ts
index 85fa9acead2..ec7c75fde36 100644
--- a/packages/twenty-front/src/modules/workflow/utils/keepServerStepResourceIds.ts
+++ b/packages/twenty-front/src/modules/workflow/utils/keepServerStepResourceIds.ts
@@ -1,24 +1,4 @@
-import {
- type WorkflowAction,
- type WorkflowAiAgentAction,
- type WorkflowCodeAction,
-} from '@/workflow/types/Workflow';
-
-const withStepInput = <
- TStep extends WorkflowCodeAction | WorkflowAiAgentAction,
->({
- step,
- input,
-}: {
- step: TStep;
- input: Partial<TStep['settings']['input']>;
-}): TStep => ({
- ...step,
- settings: {
- ...step.settings,
- input: { ...step.settings.input, ...input },
- },
-});
+import { type WorkflowAction } from '@/workflow/types/Workflow';
export const keepServerStepResourceIds = ({
localStep,
@@ -26,20 +6,16 @@ export const keepServerStepResourceIds = ({
}: {
localStep: WorkflowAction;
serverStep: WorkflowAction;
-}): WorkflowAction => {
- if (localStep.type === 'CODE' && serverStep.type === 'CODE') {
- return withStepInput({
- step: localStep,
- input: { logicFunctionId: serverStep.settings.input.logicFunctionId },
- });
- }
-
- if (localStep.type === 'AI_AGENT' && serverStep.type === 'AI_AGENT') {
- return withStepInput({
- step: localStep,
- input: { agentId: serverStep.settings.input.agentId },
- });
- }
-
- return localStep;
-};
+}): WorkflowAction =>
+ localStep.type === 'CODE' && serverStep.type === 'CODE'
+ ? {
+ ...localStep,
+ settings: {
+ ...localStep.settings,
+ input: {
+ ...localStep.settings.input,
+ logicFunctionId: serverStep.settings.input.logicFunctionId,
+ },
+ },
+ }
+ : localStep;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepFooter.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepFooter.tsx
index 4c7b5d4aefb..05c07d7c072 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepFooter.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepFooter.tsx
@@ -5,26 +5,23 @@ import { SidePanelFooter } from '@/ui/layout/side-panel/components/SidePanelFoot
import { WorkflowStepOptionsMenuItems } from '@/workflow/workflow-steps/components/WorkflowStepOptionsMenuItems';
import { useDeleteStep } from '@/workflow/workflow-steps/hooks/useDeleteStep';
import { useDuplicateStep } from '@/workflow/workflow-steps/hooks/useDuplicateStep';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
import { useLingui } from '@lingui/react/macro';
import { useId } from 'react';
import { Dropdown } from 'twenty-ui/components/navigation';
-import { AppPath, SettingsPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { TRIGGER_STEP_ID } from 'twenty-shared/workflow';
-import { IconLego, IconSettings, IconTrash, IconUsers } from 'twenty-ui/icon';
+import { IconSettings, IconTrash } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
-import { useNavigateApp } from '~/hooks/useNavigateApp';
-import { useNavigateSettings } from '~/hooks/useNavigateSettings';
+
+type WorkflowStepFooterProps = {
+ stepId: string;
+ additionalActions?: React.ReactNode[];
+};
export const WorkflowStepFooter = ({
stepId,
additionalActions,
-}: {
- stepId: string;
- additionalActions?: React.ReactNode[];
-}) => {
+}: WorkflowStepFooterProps) => {
const dropdownId = useId();
const { t } = useLingui();
const { duplicateStep } = useDuplicateStep();
@@ -35,18 +32,9 @@ export const WorkflowStepFooter = ({
openWorkflowTriggerTypeInSidePanel,
} = useSidePanelWorkflowNavigation();
const { deleteStep } = useDeleteStep();
- const navigateApp = useNavigateApp();
- const navigateSettings = useNavigateSettings();
- const workflowAiAgentActionAgent = useAtomStateValue(
- workflowAiAgentActionAgentState,
- );
const shouldPinDeleteButton =
!isDefined(additionalActions) || additionalActions.length === 0;
- const agentId = workflowAiAgentActionAgent?.id;
- const hasViewAgentOption = isDefined(agentId);
- const hasViewRoleOption = isDefined(workflowAiAgentActionAgent?.roleId);
-
const handleChangeNodeType = () => {
if (stepId === TRIGGER_STEP_ID) {
openWorkflowTriggerTypeInSidePanel(workflowId);
@@ -68,20 +56,6 @@ export const WorkflowStepFooter = ({
openWorkflowStepSettingsInSidePanel({ workflowId, stepId });
};
- const handleViewAgent = () => {
- if (isDefined(agentId)) {
- navigateApp(AppPath.AgentShowPage, { agentId });
- }
- };
-
- const handleViewRole = () => {
- if (isDefined(workflowAiAgentActionAgent?.roleId)) {
- navigateSettings(SettingsPath.RoleDetail, {
- roleId: workflowAiAgentActionAgent.roleId,
- });
- }
- };
-
const OptionsDropdown = (
<SidePanelOptionsDropdown dropdownId={dropdownId}>
<WorkflowStepOptionsMenuItems
@@ -100,22 +74,6 @@ export const WorkflowStepFooter = ({
{t`Node settings`}
</Dropdown.ActionItem>
) : null}
- {hasViewAgentOption ? (
- <Dropdown.ActionItem
- onClick={handleViewAgent}
- startIcon={<IconLego />}
- >
- {t`View Agent`}
- </Dropdown.ActionItem>
- ) : null}
- {hasViewRoleOption ? (
- <Dropdown.ActionItem
- onClick={handleViewRole}
- startIcon={<IconUsers />}
- >
- {t`View Role`}
- </Dropdown.ActionItem>
- ) : null}
</WorkflowStepOptionsMenuItems>
</SidePanelOptionsDropdown>
);
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/__tests__/useUpdateAgentLabel.test.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/__tests__/useUpdateAgentLabel.test.tsx
deleted file mode 100644
index e1618792a92..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/__tests__/useUpdateAgentLabel.test.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { renderHook } from '@testing-library/react';
-import { useUpdateAgentLabel } from '@/workflow/workflow-steps/hooks/useUpdateAgentLabel';
-
-const mockUpdateAgent = jest.fn();
-const mockUseFindOneAgentQuery = jest.fn();
-
-jest.mock('@apollo/client/react', () => ({
- ...jest.requireActual('@apollo/client/react'),
- useQuery: (...args: unknown[]) => mockUseFindOneAgentQuery(...args),
- useMutation: () => [mockUpdateAgent],
-}));
-
-describe('useUpdateAgentLabel', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockUseFindOneAgentQuery.mockReturnValue({
- data: undefined,
- });
- });
-
- it('should skip query when agentId is undefined', () => {
- renderHook(() => useUpdateAgentLabel(undefined));
-
- expect(mockUseFindOneAgentQuery).toHaveBeenCalledWith(expect.anything(), {
- variables: { id: '' },
- skip: true,
- });
- });
-
- it('should fetch agent when agentId is provided', () => {
- const mockAgent = {
- id: 'agent-123',
- label: 'Original Label',
- };
-
- mockUseFindOneAgentQuery.mockReturnValue({
- data: {
- findOneAgent: mockAgent,
- },
- });
-
- renderHook(() => useUpdateAgentLabel('agent-123'));
-
- expect(mockUseFindOneAgentQuery).toHaveBeenCalledWith(expect.anything(), {
- variables: { id: 'agent-123' },
- skip: false,
- });
- });
-
- it('should update agent label when agent is defined', async () => {
- const mockAgent = {
- id: 'agent-123',
- label: 'Original Label',
- };
-
- mockUseFindOneAgentQuery.mockReturnValue({
- data: {
- findOneAgent: mockAgent,
- },
- });
-
- mockUpdateAgent.mockResolvedValue({});
-
- const { result } = renderHook(() => useUpdateAgentLabel('agent-123'));
-
- await result.current.updateAgentLabel('New Label');
-
- expect(mockUpdateAgent).toHaveBeenCalledWith({
- variables: {
- input: {
- id: 'agent-123',
- label: 'New Label',
- },
- },
- refetchQueries: ['FindOneAgent'],
- });
- });
-
- it('should not update agent label when agent is undefined', async () => {
- mockUseFindOneAgentQuery.mockReturnValue({
- data: {
- findOneAgent: undefined,
- },
- });
-
- const { result } = renderHook(() => useUpdateAgentLabel('agent-123'));
-
- await result.current.updateAgentLabel('New Label');
-
- expect(mockUpdateAgent).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/useUpdateAgentLabel.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/useUpdateAgentLabel.ts
deleted file mode 100644
index d1437f33ca0..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/hooks/useUpdateAgentLabel.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-import { useQuery, useMutation } from '@apollo/client/react';
-import {
- FindOneAgentDocument,
- UpdateOneAgentDocument,
-} from '~/generated-metadata/graphql';
-
-export const useUpdateAgentLabel = (agentId: string | undefined) => {
- const { data: agentData } = useQuery(FindOneAgentDocument, {
- variables: { id: agentId || '' },
- skip: !isDefined(agentId),
- });
-
- const [updateAgent] = useMutation(UpdateOneAgentDocument);
-
- const agent = agentData?.findOneAgent;
-
- const updateAgentLabel = async (newLabel: string) => {
- if (!isDefined(agent)) {
- return;
- }
-
- await updateAgent({
- variables: {
- input: {
- id: agent.id,
- label: newLabel,
- },
- },
- refetchQueries: ['FindOneAgent'],
- });
- };
-
- return { updateAgentLabel };
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentAgentStepPromptTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentAgentStepPromptTab.tsx
new file mode 100644
index 00000000000..05464f8f4aa
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentAgentStepPromptTab.tsx
@@ -0,0 +1,43 @@
+import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
+import { WorkflowAiAgentOutputFormatField } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentOutputFormatField';
+import { WorkflowAiAgentConversationFields } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentConversationFields';
+import { WorkflowAiAgentPromptField } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptField';
+import { WorkflowAiAgentStepAgentField } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentStepAgentField';
+import { type WorkflowAiAgentStepPanelProps } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps';
+
+type WorkflowAiAgentAgentStepPromptTabProps = WorkflowAiAgentStepPanelProps & {
+ agent: FlatAgent;
+};
+
+export const WorkflowAiAgentAgentStepPromptTab = ({
+ agent,
+ stepId,
+ input,
+ readonly,
+ onInputChange,
+}: WorkflowAiAgentAgentStepPromptTabProps) => (
+ <>
+ <WorkflowAiAgentStepAgentField agent={agent} />
+
+ <WorkflowAiAgentPromptField
+ prompt={input.prompt}
+ readonly={readonly}
+ onPromptChange={(prompt) => onInputChange({ prompt })}
+ />
+
+ <WorkflowAiAgentConversationFields
+ stepId={stepId}
+ input={input}
+ readonly={readonly}
+ onInputChange={onInputChange}
+ />
+
+ <WorkflowAiAgentOutputFormatField
+ responseFormat={input.responseFormat ?? agent.responseFormat}
+ readonly={readonly}
+ onResponseFormatChange={(responseFormat) =>
+ onInputChange({ responseFormat })
+ }
+ />
+ </>
+);
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentConversationFields.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentConversationFields.tsx
new file mode 100644
index 00000000000..e78e5621469
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentConversationFields.tsx
@@ -0,0 +1,64 @@
+import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
+import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
+import { type WorkflowAiAgentStepPanelProps } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps';
+import { WorkflowConversationFields } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields';
+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
+import { t } from '@lingui/core/macro';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { FeatureFlagKey } from '~/generated-metadata/graphql';
+
+type WorkflowAiAgentConversationFieldsProps = WorkflowAiAgentStepPanelProps;
+
+export const WorkflowAiAgentConversationFields = ({
+ stepId,
+ input,
+ readonly,
+ onInputChange,
+}: WorkflowAiAgentConversationFieldsProps) => {
+ const isAiChatInboxEnabled = useIsFeatureEnabled(
+ FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,
+ );
+
+ return (
+ <>
+ <FormTextFieldInput
+ multiline
+ label={t`Ask for human input`}
+ placeholder={t`When should the agent stop and ask you? E.g. before sending any email or changing a deal's amount. Leave empty to never stop.`}
+ defaultValue={input.humanInputInstructions ?? ''}
+ onChange={(humanInputInstructions) =>
+ onInputChange({ humanInputInstructions })
+ }
+ readonly={readonly}
+ />
+
+ {isAiChatInboxEnabled && (
+ <>
+ <FormSingleRecordPicker
+ label={t`Recipient`}
+ objectNameSingulars={[CoreObjectNameSingular.WorkspaceMember]}
+ defaultValue={input.workspaceMemberId}
+ onChange={(workspaceMemberId) =>
+ onInputChange({
+ workspaceMemberId: workspaceMemberId ?? undefined,
+ })
+ }
+ disabled={readonly}
+ testId="workflow-edit-action-ai-agent-recipient"
+ VariablePicker={WorkflowVariablePicker}
+ />
+
+ <WorkflowConversationFields
+ dropdownId={`workflow-ai-agent-conversation-${stepId}`}
+ conversation={input.conversation}
+ defaultScope="STEP"
+ description={t`With the recipient, or the workflow creator when empty. It stays out of their inbox until the agent needs them.`}
+ readonly={readonly}
+ onChange={(conversation) => onInputChange({ conversation })}
+ />
+ </>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentGenerateStepPromptTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentGenerateStepPromptTab.tsx
new file mode 100644
index 00000000000..d0d92e6d2aa
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentGenerateStepPromptTab.tsx
@@ -0,0 +1,69 @@
+import { AiModelPicker } from '@/ai/components/AiModelPicker';
+import { SettingsAgentModelCapabilities } from '@/ai/components/SettingsAgentModelCapabilities';
+import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
+import { WorkflowAiAgentOutputFormatField } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentOutputFormatField';
+import { WorkflowAiAgentPromptField } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptField';
+import { type WorkflowAiAgentStepPanelProps } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps';
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useState } from 'react';
+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
+
+type WorkflowAiAgentGenerateStepPromptTabProps = WorkflowAiAgentStepPanelProps;
+
+export const WorkflowAiAgentGenerateStepPromptTab = ({
+ input,
+ readonly,
+ onInputChange,
+}: WorkflowAiAgentGenerateStepPromptTabProps) => {
+ const selectedModelId =
+ input.modelId ?? AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID;
+ // decided once, so clearing the instructions does not remove the field being edited
+ const [hasInstructionsField] = useState(() =>
+ isNonEmptyString(input.instructions),
+ );
+
+ return (
+ <>
+ <AiModelPicker
+ modelId={selectedModelId}
+ onModelIdChange={(modelId) => onInputChange({ modelId })}
+ disabled={readonly}
+ />
+
+ {hasInstructionsField && (
+ <FormTextFieldInput
+ multiline
+ label={t`Instructions`}
+ placeholder={t`Describe the role of the AI and how it should do the task...`}
+ defaultValue={input.instructions ?? ''}
+ onChange={(instructions) => onInputChange({ instructions })}
+ readonly={readonly}
+ />
+ )}
+
+ <WorkflowAiAgentPromptField
+ prompt={input.prompt}
+ readonly={readonly}
+ onPromptChange={(prompt) => onInputChange({ prompt })}
+ />
+
+ <SettingsAgentModelCapabilities
+ selectedModelId={selectedModelId}
+ modelConfiguration={input.modelConfiguration ?? {}}
+ onConfigurationChange={(modelConfiguration) =>
+ onInputChange({ modelConfiguration })
+ }
+ disabled={readonly}
+ />
+
+ <WorkflowAiAgentOutputFormatField
+ responseFormat={input.responseFormat}
+ readonly={readonly}
+ onResponseFormatChange={(responseFormat) =>
+ onInputChange({ responseFormat })
+ }
+ />
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentOutputFormatField.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentOutputFormatField.tsx
new file mode 100644
index 00000000000..13d04e54ac0
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentOutputFormatField.tsx
@@ -0,0 +1,48 @@
+import { AgentOutputSchemaBuilder } from '@/ai/components/AgentOutputSchemaBuilder';
+import { type OutputSchemaField } from '@/ai/types/OutputSchemaField';
+import { createDefaultOutputSchemaField } from '@/ai/utils/createDefaultOutputSchemaField';
+import { fieldsToSchema } from '@/ai/utils/fieldsToSchema';
+import { schemaToFields } from '@/ai/utils/schemaToFields';
+import { useState } from 'react';
+import { type AgentResponseFormat } from 'twenty-shared/ai';
+
+type WorkflowAiAgentOutputFormatFieldProps = {
+ responseFormat: AgentResponseFormat | null | undefined;
+ readonly: boolean;
+ onResponseFormatChange: (responseFormat: AgentResponseFormat) => void;
+};
+
+export const WorkflowAiAgentOutputFormatField = ({
+ responseFormat,
+ readonly,
+ onResponseFormatChange,
+}: WorkflowAiAgentOutputFormatFieldProps) => {
+ const [outputSchemaFields, setOutputSchemaFields] = useState<
+ OutputSchemaField[]
+ >(() => {
+ const existingFields =
+ responseFormat?.type === 'json'
+ ? schemaToFields(responseFormat.schema)
+ : [];
+
+ return existingFields.length > 0
+ ? existingFields
+ : [createDefaultOutputSchemaField()];
+ });
+
+ const handleOutputSchemaChange = (updatedFields: OutputSchemaField[]) => {
+ setOutputSchemaFields(updatedFields);
+ onResponseFormatChange({
+ type: 'json',
+ schema: fieldsToSchema(updatedFields),
+ });
+ };
+
+ return (
+ <AgentOutputSchemaBuilder
+ fields={outputSchemaFields}
+ onChange={handleOutputSchemaChange}
+ readonly={readonly}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionList.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionList.tsx
index e68a3a095a4..a5ecb3577c1 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionList.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionList.tsx
@@ -2,7 +2,9 @@ import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilte
import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
import { SidePanelGroup } from '@/side-panel/components/SidePanelGroup';
import { t } from '@lingui/core/macro';
-import { type ObjectPermission } from '~/generated-metadata/graphql';
+import { isDefined } from 'twenty-shared/utils';
+import { type WorkflowAiAgentObjectPermissionChange } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange';
+import { type WorkflowAiAgentObjectPermission } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission';
import { filterBySearchQuery } from '~/utils/filterBySearchQuery';
import { CRUD_PERMISSIONS } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentCrudPermissions';
import { WorkflowAiAgentPermissionsPermissionRow } from './WorkflowAiAgentPermissionsPermissionRow';
@@ -19,11 +21,8 @@ const CRUD_PERMISSION_ORDER = CRUD_PERMISSIONS.reduce<
type WorkflowAiAgentPermissionListProps = {
readonly: boolean;
- objectPermissions: ObjectPermission[];
- onDeletePermission: (
- objectMetadataId: string,
- permissionKey: SettingsRoleObjectPermissionKey,
- ) => void;
+ objectPermissions: WorkflowAiAgentObjectPermission[];
+ onDeletePermission?: (change: WorkflowAiAgentObjectPermissionChange) => void;
searchQuery: string;
};
@@ -36,20 +35,24 @@ export const WorkflowAiAgentPermissionList = ({
const { activeObjectMetadataItems: objectMetadataItems } =
useFilteredObjectMetadataItems();
+ const allObjectsLabel = t`all objects`;
+
const sortedExistingPermissions = objectPermissions
.reduce<
Array<{
- objectMetadataId: string;
+ objectMetadataId: string | null;
objectLabel: string;
permissionKey: SettingsRoleObjectPermissionKey;
permissionLabel: string;
}>
>((permissions, objectPermission) => {
- const objectMetadata = objectMetadataItems.find(
- (item) => item.id === objectPermission.objectMetadataId,
- );
+ const objectLabel = isDefined(objectPermission.objectMetadataId)
+ ? objectMetadataItems.find(
+ (item) => item.id === objectPermission.objectMetadataId,
+ )?.labelPlural
+ : allObjectsLabel;
- if (!objectMetadata) {
+ if (!isDefined(objectLabel)) {
return permissions;
}
@@ -57,9 +60,9 @@ export const WorkflowAiAgentPermissionList = ({
if (objectPermission[crud.key] === true) {
permissions.push({
objectMetadataId: objectPermission.objectMetadataId,
- objectLabel: objectMetadata.labelPlural,
+ objectLabel,
permissionKey: crud.key,
- permissionLabel: crud.label(objectMetadata.labelPlural),
+ permissionLabel: crud.label(objectLabel),
});
}
});
@@ -77,6 +80,16 @@ export const WorkflowAiAgentPermissionList = ({
);
}
+ const isPermissionAOnAllObjects = !isDefined(
+ permissionA.objectMetadataId,
+ );
+
+ if (
+ isPermissionAOnAllObjects !== !isDefined(permissionB.objectMetadataId)
+ ) {
+ return isPermissionAOnAllObjects ? -1 : 1;
+ }
+
return permissionA.objectLabel.localeCompare(permissionB.objectLabel);
});
@@ -104,11 +117,12 @@ export const WorkflowAiAgentPermissionList = ({
}}
isEnabled={true}
readonly={readonly}
+ shouldShowDeleteButton={!readonly && isDefined(onDeletePermission)}
onDelete={() =>
- onDeletePermission(
- permission.objectMetadataId,
- permission.permissionKey,
- )
+ onDeletePermission?.({
+ objectMetadataId: permission.objectMetadataId,
+ permissionKey: permission.permissionKey,
+ })
}
/>
))}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsCrudList.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsCrudList.tsx
index 07ef980a22e..344f51f2952 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsCrudList.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsCrudList.tsx
@@ -1,7 +1,8 @@
import { SidePanelGroup } from '@/side-panel/components/SidePanelGroup';
import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
import { t } from '@lingui/core/macro';
-import { type ObjectPermission } from '~/generated-metadata/graphql';
+import { type WorkflowAiAgentObjectPermissionChange } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange';
+import { type WorkflowAiAgentObjectPermission } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission';
import { WorkflowAiAgentPermissionsPermissionRow } from './WorkflowAiAgentPermissionsPermissionRow';
type WorkflowAiAgentPermissionsCrudListProps = {
@@ -9,12 +10,9 @@ type WorkflowAiAgentPermissionsCrudListProps = {
key: SettingsRoleObjectPermissionKey;
label: string;
}>;
- objectPermissions?: ObjectPermission;
+ objectPermissions?: WorkflowAiAgentObjectPermission;
readonly: boolean;
- onAddPermission: (
- objectMetadataId: string,
- permissionKey: SettingsRoleObjectPermissionKey,
- ) => void;
+ onAddPermission?: (change: WorkflowAiAgentObjectPermissionChange) => void;
objectMetadataId: string;
};
@@ -36,9 +34,14 @@ export const WorkflowAiAgentPermissionsCrudList = ({
permission={permission}
isEnabled={isEnabled}
readonly={readonly}
- showDeleteButton={false}
+ shouldShowDeleteButton={false}
alwaysShowGranted={true}
- onAdd={() => onAddPermission(objectMetadataId, permission.key)}
+ onAdd={() =>
+ onAddPermission?.({
+ objectMetadataId,
+ permissionKey: permission.key,
+ })
+ }
/>
);
})}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagList.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagList.tsx
index e21991c1347..155412d4e10 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagList.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagList.tsx
@@ -7,7 +7,7 @@ type WorkflowAiAgentPermissionsFlagListProps = {
permissions: SettingsRolePermissionsSettingPermission[];
enabledPermissionFlagKeys: string[];
readonly: boolean;
- showDeleteButton?: boolean;
+ shouldShowDeleteButton?: boolean;
onAddPermissionFlag?: (permissionKey: string) => void;
onDeletePermissionFlag?: (permissionKey: string) => void;
};
@@ -17,7 +17,7 @@ export const WorkflowAiAgentPermissionsFlagList = ({
permissions,
enabledPermissionFlagKeys,
readonly,
- showDeleteButton = false,
+ shouldShowDeleteButton = false,
onAddPermissionFlag,
onDeletePermissionFlag,
}: WorkflowAiAgentPermissionsFlagListProps) => {
@@ -36,7 +36,7 @@ export const WorkflowAiAgentPermissionsFlagList = ({
permission={permission}
isEnabled={isEnabled}
readonly={readonly}
- showDeleteButton={showDeleteButton}
+ shouldShowDeleteButton={shouldShowDeleteButton}
onAdd={() => onAddPermissionFlag?.(permission.key)}
onDelete={() => onDeletePermissionFlag?.(permission.key)}
/>
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagRow.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagRow.tsx
index 2a2af0e9dcb..c7d3b26f124 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagRow.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsFlagRow.tsx
@@ -12,7 +12,7 @@ type WorkflowAiAgentPermissionsFlagRowProps = {
permission: SettingsRolePermissionsSettingPermission;
isEnabled: boolean;
readonly: boolean;
- showDeleteButton?: boolean;
+ shouldShowDeleteButton?: boolean;
onAdd?: () => void;
onDelete?: () => void;
};
@@ -21,14 +21,14 @@ export const WorkflowAiAgentPermissionsFlagRow = ({
permission,
isEnabled,
readonly,
- showDeleteButton = false,
+ shouldShowDeleteButton = false,
onAdd,
onDelete,
}: WorkflowAiAgentPermissionsFlagRowProps) => {
const theme = useTheme();
const isClickable = !readonly && !isEnabled && isDefined(onAdd);
- const isDisabled = isEnabled && !showDeleteButton;
- const showTrashButton = isEnabled && showDeleteButton;
+ const isDisabled = isEnabled && !shouldShowDeleteButton;
+ const shouldShowTrashButton = isEnabled && shouldShowDeleteButton;
const Icon = permission.Icon;
const startIcon = (
@@ -50,7 +50,7 @@ export const WorkflowAiAgentPermissionsFlagRow = ({
startIcon={startIcon}
disabled={isDisabled}
actions={
- showTrashButton && (
+ shouldShowTrashButton && (
<LightIconButton aria-label={t`Remove permission`} onClick={onDelete}>
<IconTrash />
</LightIconButton>
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsPermissionRow.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsPermissionRow.tsx
index 27b1195832e..c74306dbe40 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsPermissionRow.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsPermissionRow.tsx
@@ -14,7 +14,7 @@ type WorkflowAiAgentPermissionsPermissionRowProps = {
};
isEnabled: boolean;
readonly: boolean;
- showDeleteButton?: boolean;
+ shouldShowDeleteButton?: boolean;
alwaysShowGranted?: boolean;
onAdd?: () => void;
onDelete?: () => void;
@@ -24,14 +24,14 @@ export const WorkflowAiAgentPermissionsPermissionRow = ({
permission,
isEnabled,
readonly,
- showDeleteButton = true,
+ shouldShowDeleteButton = true,
alwaysShowGranted = false,
onAdd,
onDelete,
}: WorkflowAiAgentPermissionsPermissionRowProps) => {
const isClickable = !readonly && !isEnabled && isDefined(onAdd);
- const isDisabled = isEnabled && !showDeleteButton;
- const showTrashButton = isEnabled && showDeleteButton;
+ const isDisabled = isEnabled && !shouldShowDeleteButton;
+ const shouldShowTrashButton = isEnabled && shouldShowDeleteButton;
const startIcon = (
<PermissionIcon
@@ -53,7 +53,7 @@ export const WorkflowAiAgentPermissionsPermissionRow = ({
startIcon={startIcon}
disabled={isDisabled}
actions={
- showTrashButton && (
+ shouldShowTrashButton && (
<LightIconButton aria-label={t`Remove permission`} onClick={onDelete}>
<IconTrash />
</LightIconButton>
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsTab.tsx
index f22defad26a..9dfa446add5 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsTab.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsTab.tsx
@@ -1,32 +1,30 @@
import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
import { useActionRolePermissionFlagConfig } from '@/settings/roles/role-permissions/permission-flags/hooks/useActionRolePermissionFlagConfig';
+import { useSettingsRolePermissionFlagConfig } from '@/settings/roles/role-permissions/permission-flags/hooks/useSettingsRolePermissionFlagConfig';
+import { SidePanelGroup } from '@/side-panel/components/SidePanelGroup';
import { SidePanelSubPageNavigationHeader } from '@/side-panel/pages/common/components/SidePanelSubPageNavigationHeader';
import { TextInput } from '@/ui/input/components/TextInput';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { useWorkflowAiAgentPermissionActions } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentPermissionActions';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
import { workflowAiAgentPermissionsIsAddingPermissionState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsAddingPermissionState';
import { workflowAiAgentPermissionsIsSystemObjectsListOpenState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsSystemObjectsListOpenState';
import { workflowAiAgentPermissionsSelectedObjectIdState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsSelectedObjectIdState';
-import { useQuery } from '@apollo/client/react';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { useState } from 'react';
+import { type AiRunScope } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
-import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
-import { GetRoleDocument } from '~/generated-metadata/graphql';
-import { SidePanelSkeletonLoader } from '~/loading/components/SidePanelSkeletonLoader';
import { filterBySearchQuery } from '~/utils/filterBySearchQuery';
import { isNonTextWritingKey } from '@/ui/utilities/hotkey/utils/isNonTextWritingKey';
+import { useWorkflowAiAgentScopePermissionActions } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentScopePermissionActions';
+import { getWorkflowAiAgentScopePermissions } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/getWorkflowAiAgentScopePermissions';
import { WorkflowAiAgentPermissionList } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionList';
import { CRUD_PERMISSIONS } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentCrudPermissions';
+import { ListItem } from 'twenty-ui/primitives/navigation';
import { themeCssVariables } from 'twenty-ui/theme';
import { WorkflowAiAgentPermissionsCrudList } from './WorkflowAiAgentPermissionsCrudList';
import { WorkflowAiAgentPermissionsFlagList } from './WorkflowAiAgentPermissionsFlagList';
import { WorkflowAiAgentPermissionsObjectsList } from './WorkflowAiAgentPermissionsObjectsList';
-import { getFilteredPermissions } from './workflowAiAgentPermissions.utils';
const StyledSearchInputContainer = styled.div`
background-color: ${themeCssVariables.background.transparent.lighter};
@@ -61,22 +59,16 @@ const StyledGroupsContainer = styled.div`
`;
type WorkflowAiAgentPermissionsTabProps = {
- stepId: string;
+ scope: AiRunScope | undefined;
readonly: boolean;
- isAgentLoading: boolean;
- refetchAgent: () => Promise<{ data?: { findOneAgent?: FlatAgent } }>;
+ onScopeChange: (scope: AiRunScope) => void;
};
export const WorkflowAiAgentPermissionsTab = ({
- stepId,
+ scope,
readonly,
- isAgentLoading,
- refetchAgent,
+ onScopeChange,
}: WorkflowAiAgentPermissionsTabProps) => {
- const workflowAiAgentActionAgent = useAtomStateValue(
- workflowAiAgentActionAgentState,
- );
-
const [
workflowAiAgentPermissionsSelectedObjectId,
setWorkflowAiAgentPermissionsSelectedObjectId,
@@ -94,6 +86,17 @@ export const WorkflowAiAgentPermissionsTab = ({
alphaSortedActiveNonSystemObjectMetadataItems: objectMetadataItems,
objectMetadataItems: allObjectMetadataItems,
} = useFilteredObjectMetadataItems();
+ const { objectPermissions, permissionFlagKeys, otherPermissionLabels } =
+ getWorkflowAiAgentScopePermissions({
+ scope,
+ objectMetadataItems: allObjectMetadataItems,
+ });
+ const {
+ onAddPermission,
+ onDeletePermission,
+ onAddPermissionFlag,
+ onDeletePermissionFlag,
+ } = useWorkflowAiAgentScopePermissionActions({ scope, onScopeChange });
const systemObjectMetadataItems = allObjectMetadataItems
.filter((item) => item.isActive && item.isSystem)
@@ -101,27 +104,18 @@ export const WorkflowAiAgentPermissionsTab = ({
itemA.nameSingular.localeCompare(itemB.nameSingular),
);
- const agentRoleId = workflowAiAgentActionAgent?.roleId;
- const {
- data: roleData,
- loading: roleLoading,
- refetch: refetchRole,
- } = useQuery(GetRoleDocument, {
- variables: { id: agentRoleId ?? '' },
- skip: !isDefined(agentRoleId),
- });
-
const [searchQuery, setSearchQuery] = useState('');
- const role = roleData?.getRole;
- const objectPermissions = role?.objectPermissions || [];
- const permissionFlagKeys =
- role?.permissionFlags?.map((permissionFlag) => permissionFlag.flag) ?? [];
- const hasRoleWithPermissions =
- isDefined(workflowAiAgentActionAgent?.roleId) &&
- (objectPermissions.length > 0 || permissionFlagKeys.length > 0);
- const actionPermissionsConfig = useActionRolePermissionFlagConfig({
+ const hasPermissions =
+ permissionFlagKeys.length > 0 ||
+ otherPermissionLabels.length > 0 ||
+ objectPermissions.some((objectPermission) =>
+ CRUD_PERMISSIONS.some(({ key }) => objectPermission[key]),
+ );
+ const agentActionPermissionsConfig = useActionRolePermissionFlagConfig({
assignmentCapabilities: { canBeAssignedToAgents: true },
});
+ const actionPermissionsConfig = useActionRolePermissionFlagConfig();
+ const settingsPermissionsConfig = useSettingsRolePermissionFlagConfig();
type ObjectMetadataListItem = (typeof objectMetadataItems)[number];
const filteredObjects = filterBySearchQuery<ObjectMetadataListItem>({
@@ -136,47 +130,23 @@ export const WorkflowAiAgentPermissionsTab = ({
getSearchableValues: (item) => [item.labelSingular, item.labelPlural],
});
- const {
- filteredPermissions: filteredActionPermissions,
- filteredEnabledPermissions: filteredEnabledActionPermissions,
- } = getFilteredPermissions({
- permissions: actionPermissionsConfig,
- permissionFlagKeys,
- searchQuery,
- });
-
- const refetchAgentAndRoles = async () => {
- const result = await refetchAgent();
- const refetchedAgent = result?.data?.findOneAgent;
-
- // The role may have just been created, so the query can still be skipped or bound to a stale id
- if (isDefined(refetchedAgent?.roleId)) {
- await refetchRole({ id: refetchedAgent.roleId });
- }
-
- return { refetchedAgent };
- };
-
- const {
- handleAddPermission,
- handleDeletePermission,
- handleAddPermissionFlag,
- handleDeletePermissionFlag,
- } = useWorkflowAiAgentPermissionActions({
- stepId,
- readonly,
- objectPermissions,
- permissionFlagKeys,
- refetchAgentAndRoles,
- });
-
- if (isAgentLoading || roleLoading) {
- return <SidePanelSkeletonLoader />;
- }
-
- if (!isDefined(workflowAiAgentActionAgent)) {
- return null;
- }
+ const filterPermissionsBySearchQuery = (
+ permissions: typeof actionPermissionsConfig,
+ ) =>
+ filterBySearchQuery({
+ items: permissions,
+ searchQuery,
+ getSearchableValues: (permission) => [permission.name],
+ });
+
+ const filterEnabledPermissions = (
+ permissions: typeof actionPermissionsConfig,
+ ) =>
+ filterPermissionsBySearchQuery(
+ permissions.filter((permission) =>
+ permissionFlagKeys.includes(permission.key),
+ ),
+ );
const selectedObject = isDefined(workflowAiAgentPermissionsSelectedObjectId)
? allObjectMetadataItems.find(
@@ -214,10 +184,10 @@ export const WorkflowAiAgentPermissionsTab = ({
workflowAiAgentPermissionsIsAddingPermission;
const shouldShowCrudList = isDefined(selectedObject);
const shouldShowSelectionLists =
- (!hasRoleWithPermissions || workflowAiAgentPermissionsIsAddingPermission) &&
+ (!hasPermissions || workflowAiAgentPermissionsIsAddingPermission) &&
!isDefined(selectedObject);
const shouldShowExistingPermissions =
- hasRoleWithPermissions && !workflowAiAgentPermissionsIsAddingPermission;
+ hasPermissions && !workflowAiAgentPermissionsIsAddingPermission;
return (
<StyledContainer>
@@ -257,7 +227,7 @@ export const WorkflowAiAgentPermissionsTab = ({
})}
objectPermissions={objectPermissionForSelected}
readonly={readonly}
- onAddPermission={handleAddPermission}
+ onAddPermission={onAddPermission}
objectMetadataId={selectedObject.id}
/>
)}
@@ -282,10 +252,12 @@ export const WorkflowAiAgentPermissionsTab = ({
/>
<WorkflowAiAgentPermissionsFlagList
title={t`Actions`}
- permissions={filteredActionPermissions}
+ permissions={filterPermissionsBySearchQuery(
+ agentActionPermissionsConfig,
+ )}
enabledPermissionFlagKeys={permissionFlagKeys}
readonly={readonly}
- onAddPermissionFlag={handleAddPermissionFlag}
+ onAddPermissionFlag={onAddPermissionFlag}
/>
</>
))}
@@ -295,17 +267,34 @@ export const WorkflowAiAgentPermissionsTab = ({
<WorkflowAiAgentPermissionList
readonly={readonly}
objectPermissions={objectPermissions}
- onDeletePermission={handleDeletePermission}
+ onDeletePermission={onDeletePermission}
searchQuery={searchQuery}
/>
<WorkflowAiAgentPermissionsFlagList
title={t`Actions`}
- permissions={filteredEnabledActionPermissions}
+ permissions={filterEnabledPermissions(actionPermissionsConfig)}
+ enabledPermissionFlagKeys={permissionFlagKeys}
+ readonly={readonly}
+ shouldShowDeleteButton={!readonly}
+ onDeletePermissionFlag={onDeletePermissionFlag}
+ />
+ <WorkflowAiAgentPermissionsFlagList
+ title={t`Settings`}
+ permissions={filterEnabledPermissions(settingsPermissionsConfig)}
enabledPermissionFlagKeys={permissionFlagKeys}
readonly={readonly}
- showDeleteButton={!readonly}
- onDeletePermissionFlag={handleDeletePermissionFlag}
+ shouldShowDeleteButton={!readonly}
+ onDeletePermissionFlag={onDeletePermissionFlag}
/>
+ {otherPermissionLabels.length > 0 && (
+ <SidePanelGroup heading={t`Other permissions`}>
+ {otherPermissionLabels.map((label) => (
+ <ListItem key={label} disabled>
+ {label}
+ </ListItem>
+ ))}
+ </SidePanelGroup>
+ )}
</>
)}
</StyledGroupsContainer>
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptField.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptField.tsx
new file mode 100644
index 00000000000..ed57b08a884
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptField.tsx
@@ -0,0 +1,25 @@
+import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { t } from '@lingui/core/macro';
+
+type WorkflowAiAgentPromptFieldProps = {
+ prompt: string | undefined;
+ readonly: boolean;
+ onPromptChange: (prompt: string) => void;
+};
+
+export const WorkflowAiAgentPromptField = ({
+ prompt,
+ readonly,
+ onPromptChange,
+}: WorkflowAiAgentPromptFieldProps) => (
+ <FormTextFieldInput
+ multiline
+ VariablePicker={WorkflowVariablePicker}
+ label={t`Prompt`}
+ placeholder={t`Describe what you want the AI to do...`}
+ defaultValue={prompt ?? ''}
+ onChange={onPromptChange}
+ readonly={readonly}
+ />
+);
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx
deleted file mode 100644
index 450ebb84a68..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { SettingsAgentModelCapabilities } from '@/ai/components/SettingsAgentModelCapabilities';
-import { type OutputSchemaField } from '@/ai/types/OutputSchemaField';
-import { AiModelPicker } from '@/ai/components/AiModelPicker';
-import { createDefaultOutputSchemaField } from '@/ai/utils/createDefaultOutputSchemaField';
-import { fieldsToSchema } from '@/ai/utils/fieldsToSchema';
-import { schemaToFields } from '@/ai/utils/schemaToFields';
-import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
-import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
-import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
-import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
-import { useGetUpdatableWorkflowVersionOrThrow } from '@/workflow/hooks/useGetUpdatableWorkflowVersionOrThrow';
-import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';
-import { WorkflowConversationFields } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields';
-import { AgentOutputSchemaBuilder } from '@/ai/components/AgentOutputSchemaBuilder';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
-import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
-import { useMutation } from '@apollo/client/react';
-import { t } from '@lingui/core/macro';
-import { useState } from 'react';
-import {
- type AgentResponseSchema,
- type ModelConfiguration,
-} from 'twenty-shared/ai';
-import { doNotTranslate } from 'twenty-shared/i18n';
-import { CoreObjectNameSingular } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-import { type WorkflowConversation } from 'twenty-shared/workflow';
-import {
- FeatureFlagKey,
- UpdateOneAgentDocument,
- type UpdateOneAgentMutationVariables,
-} from '~/generated-metadata/graphql';
-
-type WorkflowAiAgentPromptTabProps = {
- action: WorkflowAiAgentAction;
- prompt: string;
- readonly: boolean;
- onPromptChange: (value: string) => void;
- humanInputInstructions: string;
- onHumanInputInstructionsChange: (value: string) => void;
- recipientWorkspaceMemberId: string | undefined;
- onRecipientChange: (workspaceMemberId: string | undefined) => void;
- conversation: WorkflowConversation | undefined;
- onConversationChange: (conversation: WorkflowConversation) => void;
- onResponseSchemaChange: (responseSchema: AgentResponseSchema) => void;
-};
-
-export const WorkflowAiAgentPromptTab = ({
- action,
- prompt,
- readonly,
- onPromptChange,
- humanInputInstructions,
- onHumanInputInstructionsChange,
- recipientWorkspaceMemberId,
- onRecipientChange,
- conversation,
- onConversationChange,
- onResponseSchemaChange,
-}: WorkflowAiAgentPromptTabProps) => {
- const [workflowAiAgentActionAgent, setWorkflowAiAgentActionAgent] =
- useAtomState(workflowAiAgentActionAgentState);
- const [updateAgent] = useMutation(UpdateOneAgentDocument);
- const { getUpdatableWorkflowVersionStepOrThrow } =
- useGetUpdatableWorkflowVersionOrThrow();
- const isAiChatInboxEnabled = useIsFeatureEnabled(
- FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,
- );
-
- const [outputSchemaFields, setOutputSchemaFields] = useState<
- OutputSchemaField[]
- >(() => {
- // steps saved before the format moved to them still carry it on their agent
- const responseFormat =
- action.settings.input.responseFormat ??
- workflowAiAgentActionAgent?.responseFormat;
- const schema: AgentResponseSchema = (responseFormat?.type === 'json'
- ? responseFormat.schema
- : undefined) || {
- type: 'object' as const,
- properties: {},
- required: [],
- additionalProperties: false as const,
- };
- const existingFields = schemaToFields(schema);
-
- return existingFields.length > 0
- ? existingFields
- : [createDefaultOutputSchemaField()];
- });
-
- const updateAgentField = async (
- input: Omit<UpdateOneAgentMutationVariables['input'], 'id'>,
- ) => {
- if (readonly || !workflowAiAgentActionAgent) {
- return;
- }
-
- const updatableStep = await getUpdatableWorkflowVersionStepOrThrow({
- stepId: action.id,
- stepType: 'AI_AGENT',
- });
-
- const updatableAgentId = updatableStep.settings.input.agentId;
-
- if (!isDefined(updatableAgentId)) {
- throw new Error(doNotTranslate('The AI agent step has no agent'));
- }
-
- const response = await updateAgent({
- variables: {
- input: {
- id: updatableAgentId,
- ...input,
- },
- },
- });
-
- setWorkflowAiAgentActionAgent((currentWorkflowAiAgentActionAgent) =>
- currentWorkflowAiAgentActionAgent
- ? {
- ...currentWorkflowAiAgentActionAgent,
- ...response.data?.updateOneAgent,
- }
- : currentWorkflowAiAgentActionAgent,
- );
- };
-
- if (!workflowAiAgentActionAgent) {
- return null;
- }
-
- const agent = workflowAiAgentActionAgent;
-
- const handleModelChange = async (modelId: string) => {
- await updateAgentField({
- modelId,
- });
- };
-
- const handleModelConfigurationChange = async (
- configuration: ModelConfiguration,
- ) => {
- await updateAgentField({
- modelConfiguration: configuration,
- });
- };
-
- const handleOutputSchemaChange = (updatedFields: OutputSchemaField[]) => {
- setOutputSchemaFields(updatedFields);
- onResponseSchemaChange(fieldsToSchema(updatedFields));
- };
-
- return (
- <>
- <AiModelPicker
- modelId={agent.modelId}
- onModelIdChange={handleModelChange}
- disabled={readonly}
- />
-
- <FormTextFieldInput
- multiline
- VariablePicker={WorkflowVariablePicker}
- label={t`Input (Prompt)`}
- placeholder={t`Describe what you want the AI to do...`}
- defaultValue={prompt}
- onChange={onPromptChange}
- readonly={readonly}
- />
-
- <FormTextFieldInput
- multiline
- label={t`Ask for human input`}
- placeholder={t`When should the agent stop and ask you? E.g. before sending any email or changing a deal's amount. Leave empty to never stop.`}
- defaultValue={humanInputInstructions}
- onChange={onHumanInputInstructionsChange}
- readonly={readonly}
- />
-
- {isAiChatInboxEnabled && (
- <>
- <FormSingleRecordPicker
- label={t`Recipient`}
- objectNameSingulars={[CoreObjectNameSingular.WorkspaceMember]}
- defaultValue={recipientWorkspaceMemberId}
- onChange={(workspaceMemberId) =>
- onRecipientChange(workspaceMemberId ?? undefined)
- }
- disabled={readonly}
- testId="workflow-edit-action-ai-agent-recipient"
- VariablePicker={WorkflowVariablePicker}
- />
-
- <WorkflowConversationFields
- dropdownId={`workflow-ai-agent-conversation-${action.id}`}
- conversation={conversation}
- defaultScope="STEP"
- description={t`With the recipient, or the workflow creator when empty. It stays out of their inbox until the agent needs them.`}
- readonly={readonly}
- onChange={onConversationChange}
- />
- </>
- )}
-
- <SettingsAgentModelCapabilities
- selectedModelId={agent.modelId}
- modelConfiguration={agent.modelConfiguration || {}}
- onConfigurationChange={handleModelConfigurationChange}
- disabled={readonly}
- />
-
- <AgentOutputSchemaBuilder
- fields={outputSchemaFields}
- onChange={handleOutputSchemaChange}
- readonly={readonly}
- />
- </>
- );
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentStepAgentField.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentStepAgentField.tsx
new file mode 100644
index 00000000000..f348b2c1044
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentStepAgentField.tsx
@@ -0,0 +1,42 @@
+import { getAgentIcon } from '@/object-core/agents/utils/getAgentIcon';
+import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
+import { getCoreAgentLink } from '@/object-core/agents/utils/getCoreAgentLink';
+import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
+import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
+import { useLingui } from '@lingui/react/macro';
+import { useIcons } from 'twenty-ui/icon/provider';
+import { Field } from 'twenty-ui/primitives/input';
+import { useTheme } from 'twenty-ui/theme';
+
+type WorkflowAiAgentStepAgentFieldProps = {
+ agent: Pick<FlatAgent, 'id' | 'label' | 'icon'>;
+};
+
+export const WorkflowAiAgentStepAgentField = ({
+ agent,
+}: WorkflowAiAgentStepAgentFieldProps) => {
+ const { t } = useLingui();
+ const theme = useTheme();
+ const { getIcon } = useIcons();
+ const Icon = getIcon(getAgentIcon(agent.icon));
+
+ return (
+ <FormFieldInputContainer>
+ <Field.Label>{t`Agent`}</Field.Label>
+ <div>
+ <LinkChip
+ to={getCoreAgentLink(agent.id)}
+ variant="soft"
+ startElement={
+ <Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
+ }
+ >
+ {agent.label}
+ </LinkChip>
+ </div>
+ <Field.Description>
+ {t`The agent sets the instructions, model and permissions.`}
+ </Field.Description>
+ </FormFieldInputContainer>
+ );
+};
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 68ab0085428..eb85638387a 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
@@ -10,33 +10,25 @@ import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
import { WorkflowStepCmdEnterButton } from '@/workflow/workflow-steps/components/WorkflowStepCmdEnterButton';
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
+import { WorkflowAiAgentAgentStepPromptTab } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentAgentStepPromptTab';
+import { WorkflowAiAgentGenerateStepPromptTab } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentGenerateStepPromptTab';
import { WorkflowAiAgentPermissionsTab } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPermissionsTab';
import { WORKFLOW_AI_AGENT_TAB_LIST_COMPONENT_ID } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentTabListComponentId';
import { WORKFLOW_AI_AGENT_TABS } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentTabs';
import { useResetWorkflowAiAgentPermissionsStateOnSidePanelClose } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
import { workflowAiAgentPermissionsIsAddingPermissionState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsAddingPermissionState';
+import { type WorkflowAiAgentStepInput } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepInput';
import { useQuery } from '@apollo/client/react';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { useEffect, useState } from 'react';
-import { type AgentResponseSchema } from 'twenty-shared/ai';
-import { SettingsPath } from 'twenty-shared/types';
+import { useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
-import { type WorkflowConversation } from 'twenty-shared/workflow';
-import { IconLock, IconSparkles } from 'twenty-ui/icon';
+import { isWorkflowAiAgentGenerateStep } from 'twenty-shared/workflow';
+import { IconAlertTriangle, IconLock, IconSparkles } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
import { useDebouncedCallback } from 'use-debounce';
-import {
- FindOneAgentDocument,
- GetRoleDocument,
-} from '~/generated-metadata/graphql';
-import { useNavigateSettings } from '~/hooks/useNavigateSettings';
+import { FindOneAgentDocument } from '~/generated-metadata/graphql';
import { SidePanelSkeletonLoader } from '~/loading/components/SidePanelSkeletonLoader';
-import { WorkflowAiAgentPromptTab } from './WorkflowAiAgentPromptTab';
-
-export type WorkflowAiAgentTabId =
- (typeof WORKFLOW_AI_AGENT_TABS)[keyof typeof WORKFLOW_AI_AGENT_TABS];
type WorkflowEditActionAiAgentProps = {
action: WorkflowAiAgentAction;
@@ -53,48 +45,45 @@ const StyledTabListContainer = styled.div`
padding-left: ${themeCssVariables.spacing[2]};
`;
+const StyledMissingAgentState = styled.div`
+ align-items: center;
+ color: ${themeCssVariables.font.color.tertiary};
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ font-size: ${themeCssVariables.font.size.sm};
+ gap: ${themeCssVariables.spacing[2]};
+ padding: ${themeCssVariables.spacing[8]} ${themeCssVariables.spacing[3]};
+ text-align: center;
+`;
+
export const WorkflowEditActionAiAgent = ({
action,
actionOptions,
}: WorkflowEditActionAiAgentProps) => {
const { t } = useLingui();
const componentInstanceId = `${WORKFLOW_AI_AGENT_TAB_LIST_COMPONENT_ID}-${action.id}`;
- const agentId = action.settings.input.agentId;
- const [workflowAiAgentActionAgent, setWorkflowAiAgentActionAgent] =
- useAtomState(workflowAiAgentActionAgentState);
- const {
- data: agentData,
- loading: agentLoading,
- refetch: refetchAgent,
- } = useQuery(FindOneAgentDocument, {
- variables: { id: agentId || '' },
- skip: !agentId,
- });
+ const readonly = actionOptions.readonly ?? false;
+ const isGenerateStep = isWorkflowAiAgentGenerateStep(action.settings.input);
+
+ const { data: agentData, loading: agentLoading } = useQuery(
+ FindOneAgentDocument,
+ {
+ variables: { id: action.settings.input.agentId ?? '' },
+ skip: isGenerateStep,
+ },
+ );
+ const agent = agentData?.findOneAgent;
- useEffect(() => {
- if (agentData?.findOneAgent) {
- setWorkflowAiAgentActionAgent(agentData.findOneAgent);
- }
- }, [agentData, setWorkflowAiAgentActionAgent]);
useResetWorkflowAiAgentPermissionsStateOnSidePanelClose();
- const [prompt, setPrompt] = useState(action.settings.input.prompt ?? '');
- const [humanInputInstructions, setHumanInputInstructions] = useState(
- action.settings.input.humanInputInstructions ?? '',
- );
- const [recipientWorkspaceMemberId, setRecipientWorkspaceMemberId] = useState(
- action.settings.input.workspaceMemberId,
- );
- const [conversation, setConversation] = useState(
- action.settings.input.conversation,
+ const [input, setInput] = useState<WorkflowAiAgentStepInput>(
+ action.settings.input,
);
- const [responseSchema, setResponseSchema] = useState<
- AgentResponseSchema | undefined
- >(undefined);
- // saves every field from the latest render, so editing one does not drop a pending edit of another
+ // saves the input of the latest render, so editing one field does not drop a pending edit of another
const saveInput = useDebouncedCallback(() => {
- if (actionOptions.readonly === true) {
+ if (actionOptions.readonly) {
return;
}
@@ -102,126 +91,87 @@ export const WorkflowEditActionAiAgent = ({
...action,
settings: {
...action.settings,
- input: {
- ...action.settings.input,
- prompt,
- humanInputInstructions,
- workspaceMemberId: recipientWorkspaceMemberId,
- conversation,
- ...(isDefined(responseSchema)
- ? { responseFormat: { type: 'json', schema: responseSchema } }
- : {}),
- },
- ...(isDefined(responseSchema)
- ? { outputSchema: agentResponseSchemaToOutputSchema(responseSchema) }
+ input,
+ ...(input.responseFormat?.type === 'json'
+ ? {
+ outputSchema: agentResponseSchemaToOutputSchema(
+ input.responseFormat.schema,
+ ),
+ }
: {}),
},
});
}, 500);
- const handleAgentPromptChange = (newPrompt: string) => {
- setPrompt(newPrompt);
- saveInput();
- };
-
- const handleHumanInputInstructionsChange = (newInstructions: string) => {
- setHumanInputInstructions(newInstructions);
- saveInput();
- };
-
- const handleRecipientChange = (workspaceMemberId: string | undefined) => {
- setRecipientWorkspaceMemberId(workspaceMemberId);
- saveInput();
- };
-
- const handleConversationChange = (nextConversation: WorkflowConversation) => {
- setConversation(nextConversation);
- saveInput();
- };
-
- const handleResponseSchemaChange = (
- nextResponseSchema: AgentResponseSchema,
+ const handleInputChange = (
+ inputUpdate: Partial<WorkflowAiAgentStepInput>,
) => {
- setResponseSchema(nextResponseSchema);
+ setInput((currentInput) => ({ ...currentInput, ...inputUpdate }));
saveInput();
};
+ // an agent step runs with its agent's role, edited on the agent
const tabs: SingleTabProps[] = [
{
id: WORKFLOW_AI_AGENT_TABS.PROMPT,
title: t`Prompt`,
Icon: IconSparkles,
},
- {
- id: WORKFLOW_AI_AGENT_TABS.PERMISSIONS,
- title: t`Permissions`,
- Icon: IconLock,
- },
+ ...(isGenerateStep
+ ? [
+ {
+ id: WORKFLOW_AI_AGENT_TABS.PERMISSIONS,
+ title: t`Permissions`,
+ Icon: IconLock,
+ },
+ ]
+ : []),
];
const activeTabId = useAtomComponentStateValue(
activeTabIdComponentState,
componentInstanceId,
);
- const currentTabId =
- (activeTabId as WorkflowAiAgentTabId) ?? WORKFLOW_AI_AGENT_TABS.PROMPT;
-
- const navigateSettings = useNavigateSettings();
- const agentRoleId = workflowAiAgentActionAgent?.roleId;
- const { data: roleData } = useQuery(GetRoleDocument, {
- variables: { id: agentRoleId ?? '' },
- skip: !isDefined(agentRoleId),
- });
+ const isPermissionsTabActive =
+ isGenerateStep && activeTabId === WORKFLOW_AI_AGENT_TABS.PERMISSIONS;
const [
workflowAiAgentPermissionsIsAddingPermission,
setWorkflowAiAgentPermissionsIsAddingPermission,
] = useAtomState(workflowAiAgentPermissionsIsAddingPermissionState);
- const role = roleData?.getRole;
-
- const isCurrentAgentLoaded =
- isDefined(workflowAiAgentActionAgent) &&
- workflowAiAgentActionAgent.id === agentId;
-
- const handleViewRole = () => {
- if (isDefined(role?.id)) {
- navigateSettings(SettingsPath.RoleDetail, { roleId: role.id });
- }
- };
-
- const getFooterActions = () => {
- if (currentTabId !== WORKFLOW_AI_AGENT_TABS.PERMISSIONS) {
- return [];
- }
-
- if (workflowAiAgentPermissionsIsAddingPermission) {
- return [
- <WorkflowStepCmdEnterButton
- key="view-role"
- title={t`View role`}
- onClick={handleViewRole}
- disabled={!isDefined(role?.id)}
- />,
- ];
- }
-
- if (isDefined(actionOptions.readonly)) {
- return [];
- }
-
- return [
- <WorkflowStepCmdEnterButton
- key="add-permission"
- title={t`Add permission`}
- onClick={() => setWorkflowAiAgentPermissionsIsAddingPermission(true)}
- />,
- ];
- };
-
- return agentLoading || !isCurrentAgentLoaded ? (
- <SidePanelSkeletonLoader />
- ) : (
+ const footerActions =
+ isPermissionsTabActive &&
+ !workflowAiAgentPermissionsIsAddingPermission &&
+ !readonly
+ ? [
+ <WorkflowStepCmdEnterButton
+ key="add-permission"
+ title={t`Add permission`}
+ onClick={() =>
+ setWorkflowAiAgentPermissionsIsAddingPermission(true)
+ }
+ />,
+ ]
+ : [];
+
+ if (!isGenerateStep && !agentLoading && !isDefined(agent)) {
+ return (
+ <>
+ <StyledMissingAgentState>
+ <IconAlertTriangle size={20} />
+ <div>{t`The agent this step runs could not be loaded. It may have been deleted.`}</div>
+ </StyledMissingAgentState>
+ {!readonly && <WorkflowStepFooter stepId={action.id} />}
+ </>
+ );
+ }
+
+ if (!isGenerateStep && !isDefined(agent)) {
+ return <SidePanelSkeletonLoader />;
+ }
+
+ return (
<TabListRoot componentInstanceId={componentInstanceId}>
<StyledTabListContainer>
<TabList
@@ -231,39 +181,45 @@ export const WorkflowEditActionAiAgent = ({
behaveAsLinks={false}
/>
</StyledTabListContainer>
- <WorkflowStepTabPanel value={currentTabId}>
- {currentTabId === WORKFLOW_AI_AGENT_TABS.PERMISSIONS ? (
+ <WorkflowStepTabPanel
+ value={
+ isPermissionsTabActive
+ ? WORKFLOW_AI_AGENT_TABS.PERMISSIONS
+ : WORKFLOW_AI_AGENT_TABS.PROMPT
+ }
+ >
+ {isPermissionsTabActive ? (
<WorkflowStepBody paddingBlock="0" paddingInline="0">
<WorkflowAiAgentPermissionsTab
- stepId={action.id}
- readonly={actionOptions.readonly === true}
- isAgentLoading={agentLoading}
- refetchAgent={refetchAgent}
+ scope={input.scope}
+ readonly={readonly}
+ onScopeChange={(scope) => handleInputChange({ scope })}
/>
</WorkflowStepBody>
) : (
<WorkflowStepBody>
- <WorkflowAiAgentPromptTab
- action={action}
- prompt={prompt}
- readonly={actionOptions.readonly === true}
- onPromptChange={handleAgentPromptChange}
- humanInputInstructions={humanInputInstructions}
- onHumanInputInstructionsChange={
- handleHumanInputInstructionsChange
- }
- recipientWorkspaceMemberId={recipientWorkspaceMemberId}
- onRecipientChange={handleRecipientChange}
- conversation={conversation}
- onConversationChange={handleConversationChange}
- onResponseSchemaChange={handleResponseSchemaChange}
- />
+ {isDefined(agent) ? (
+ <WorkflowAiAgentAgentStepPromptTab
+ agent={agent}
+ stepId={action.id}
+ input={input}
+ readonly={readonly}
+ onInputChange={handleInputChange}
+ />
+ ) : (
+ <WorkflowAiAgentGenerateStepPromptTab
+ stepId={action.id}
+ input={input}
+ readonly={readonly}
+ onInputChange={handleInputChange}
+ />
+ )}
</WorkflowStepBody>
)}
</WorkflowStepTabPanel>
- {!actionOptions.readonly && (
+ {!readonly && (
<WorkflowStepFooter
- additionalActions={getFooterActions()}
+ additionalActions={footerActions}
stepId={action.id}
/>
)}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__stories__/WorkflowAiAgentPermissionsPermissionRow.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__stories__/WorkflowAiAgentPermissionsPermissionRow.stories.tsx
index 75c209b5f9d..1be799adcc5 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__stories__/WorkflowAiAgentPermissionsPermissionRow.stories.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__stories__/WorkflowAiAgentPermissionsPermissionRow.stories.tsx
@@ -39,7 +39,7 @@ export const ActionOwnership: Story = {
}}
isEnabled
readonly={false}
- showDeleteButton
+ shouldShowDeleteButton
onAdd={args.onAdd}
onDelete={args.onDelete}
/>
@@ -69,7 +69,7 @@ export const ActionOwnership: Story = {
};
export const Readonly: Story = {
- args: { readonly: true, showDeleteButton: false },
+ args: { readonly: true, shouldShowDeleteButton: false },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(await canvas.findByText('Read records')).toBeVisible();
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__tests__/WorkflowEditActionAiAgent.test.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__tests__/WorkflowEditActionAiAgent.test.tsx
new file mode 100644
index 00000000000..1a8b21cd692
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/__tests__/WorkflowEditActionAiAgent.test.tsx
@@ -0,0 +1,62 @@
+import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';
+import { WorkflowEditActionAiAgent } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent';
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen } from '@testing-library/react';
+import { createStore, Provider as JotaiProvider } from 'jotai';
+import { MemoryRouter } from 'react-router-dom';
+
+jest.mock('@apollo/client/react', () => ({
+ ...jest.requireActual('@apollo/client/react'),
+ useQuery: () => ({ data: undefined, loading: false }),
+}));
+jest.mock('@/workflow/workflow-steps/components/WorkflowStepFooter', () => ({
+ WorkflowStepFooter: () => null,
+}));
+jest.mock(
+ '@/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose',
+ () => ({
+ useResetWorkflowAiAgentPermissionsStateOnSidePanelClose: jest.fn(),
+ }),
+);
+
+const deletedAgentStep: WorkflowAiAgentAction = {
+ id: 'ai-step-id',
+ name: 'Agent',
+ type: 'AI_AGENT',
+ valid: true,
+ settings: {
+ input: { agentId: 'deleted-agent-id', prompt: 'Qualify the lead' },
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ },
+};
+
+describe('WorkflowEditActionAiAgent', () => {
+ it('tells the author when the agent the step runs is missing', async () => {
+ render(
+ <WorkflowEditActionAiAgent
+ action={deletedAgentStep}
+ actionOptions={{ onActionUpdate: jest.fn() }}
+ />,
+ {
+ wrapper: ({ children }) => (
+ <MemoryRouter>
+ <I18nProvider i18n={i18n}>
+ <JotaiProvider store={createStore()}>{children}</JotaiProvider>
+ </I18nProvider>
+ </MemoryRouter>
+ ),
+ },
+ );
+
+ expect(
+ await screen.findByText(
+ 'The agent this step runs could not be loaded. It may have been deleted.',
+ ),
+ ).toBeVisible();
+ });
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/workflowAiAgentPermissions.utils.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/workflowAiAgentPermissions.utils.ts
deleted file mode 100644
index 6b9c628dc87..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/workflowAiAgentPermissions.utils.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { filterBySearchQuery } from '~/utils/filterBySearchQuery';
-
-export type FilteredPermissionsResult<T> = {
- filteredPermissions: T[];
- filteredEnabledPermissions: T[];
-};
-
-export const getFilteredPermissions = <
- T extends { key: string; name: string },
->({
- permissions,
- permissionFlagKeys,
- searchQuery,
-}: {
- permissions: T[];
- permissionFlagKeys: string[];
- searchQuery: string;
-}): FilteredPermissionsResult<T> => {
- const filteredPermissions = filterBySearchQuery<T>({
- items: permissions,
- searchQuery,
- getSearchableValues: (permission) => [permission.name],
- });
-
- const enabledPermissions = permissions.filter((permission) =>
- permissionFlagKeys.includes(permission.key),
- );
-
- const filteredEnabledPermissions = filterBySearchQuery<T>({
- items: enabledPermissions,
- searchQuery,
- getSearchableValues: (permission) => [permission.name],
- });
-
- return {
- filteredPermissions,
- filteredEnabledPermissions,
- };
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose.ts
index 56643c93510..984b8c63f87 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useResetWorkflowAiAgentPermissionsStateOnSidePanelClose.ts
@@ -1,6 +1,5 @@
import { useListenToSidePanelClosing } from '@/ui/layout/side-panel/hooks/useListenToSidePanelClosing';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
import { workflowAiAgentPermissionsIsAddingPermissionState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsAddingPermissionState';
import { workflowAiAgentPermissionsIsSystemObjectsListOpenState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsSystemObjectsListOpenState';
import { workflowAiAgentPermissionsSelectedObjectIdState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsSelectedObjectIdState';
@@ -15,15 +14,11 @@ export const useResetWorkflowAiAgentPermissionsStateOnSidePanelClose = () => {
const setWorkflowAiAgentPermissionsIsSystemObjectsListOpen = useSetAtomState(
workflowAiAgentPermissionsIsSystemObjectsListOpenState,
);
- const setWorkflowAiAgentActionAgent = useSetAtomState(
- workflowAiAgentActionAgentState,
- );
const resetPermissionState = () => {
setWorkflowAiAgentPermissionsSelectedObjectId(undefined);
setWorkflowAiAgentPermissionsIsAddingPermission(false);
setWorkflowAiAgentPermissionsIsSystemObjectsListOpen(false);
- setWorkflowAiAgentActionAgent(undefined);
};
useListenToSidePanelClosing(resetPermissionState);
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentPermissionActions.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentPermissionActions.ts
deleted file mode 100644
index 62d10263d97..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentPermissionActions.ts
+++ /dev/null
@@ -1,387 +0,0 @@
-import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
-import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
-import { useActionRolePermissionFlagConfig } from '@/settings/roles/role-permissions/permission-flags/hooks/useActionRolePermissionFlagConfig';
-import { useSettingsRolePermissionFlagConfig } from '@/settings/roles/role-permissions/permission-flags/hooks/useSettingsRolePermissionFlagConfig';
-import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
-import { useGetUpdatableWorkflowVersionOrThrow } from '@/workflow/hooks/useGetUpdatableWorkflowVersionOrThrow';
-import { CRUD_PERMISSIONS } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentCrudPermissions';
-import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
-import { workflowAiAgentPermissionsIsAddingPermissionState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsAddingPermissionState';
-import { workflowAiAgentPermissionsIsSystemObjectsListOpenState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsSystemObjectsListOpenState';
-import { workflowAiAgentPermissionsSelectedObjectIdState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsSelectedObjectIdState';
-import { useMutation } from '@apollo/client/react';
-import { t } from '@lingui/core/macro';
-import { useMemo } from 'react';
-import { doNotTranslate } from 'twenty-shared/i18n';
-import { isDefined } from 'twenty-shared/utils';
-import { useToast } from 'twenty-ui/components/feedback';
-import { v4 } from 'uuid';
-import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
-import {
- type ObjectPermission,
- AssignRoleToAgentDocument,
- CreateOneRoleDocument,
- UpsertObjectPermissionsDocument,
- UpsertPermissionFlagsDocument,
-} from '~/generated-metadata/graphql';
-
-type UseWorkflowAiAgentPermissionActionsParams = {
- stepId: string;
- readonly: boolean;
- objectPermissions: ObjectPermission[];
- permissionFlagKeys: string[];
- refetchAgentAndRoles: () => Promise<{ refetchedAgent?: FlatAgent }>;
-};
-
-export const useWorkflowAiAgentPermissionActions = ({
- stepId,
- readonly,
- objectPermissions,
- permissionFlagKeys,
- refetchAgentAndRoles,
-}: UseWorkflowAiAgentPermissionActionsParams) => {
- const { enqueueToast } = useToast();
- const { getUpdatableWorkflowVersionStepOrThrow } =
- useGetUpdatableWorkflowVersionOrThrow();
- const [workflowAiAgentActionAgent, setWorkflowAiAgentActionAgent] =
- useAtomState(workflowAiAgentActionAgentState);
- const { activeObjectMetadataItems: objectMetadataItems } =
- useFilteredObjectMetadataItems();
- const settingsPermissionsConfig = useSettingsRolePermissionFlagConfig({
- assignmentCapabilities: { canBeAssignedToAgents: true },
- });
- const actionPermissionsConfig = useActionRolePermissionFlagConfig({
- assignmentCapabilities: { canBeAssignedToAgents: true },
- });
-
- const [, setWorkflowAiAgentPermissionsSelectedObjectId] = useAtomState(
- workflowAiAgentPermissionsSelectedObjectIdState,
- );
- const [, setWorkflowAiAgentPermissionsIsAddingPermission] = useAtomState(
- workflowAiAgentPermissionsIsAddingPermissionState,
- );
- const [, setWorkflowAiAgentPermissionsIsSystemObjectsListOpen] = useAtomState(
- workflowAiAgentPermissionsIsSystemObjectsListOpenState,
- );
-
- const [createRole] = useMutation(CreateOneRoleDocument);
- const [assignRoleToAgent] = useMutation(AssignRoleToAgentDocument);
- const [upsertObjectPermissions] = useMutation(
- UpsertObjectPermissionsDocument,
- );
- const [upsertPermissionFlags] = useMutation(UpsertPermissionFlagsDocument);
-
- const roleId = workflowAiAgentActionAgent?.roleId;
-
- const permissionFlagLabelMap = useMemo(
- () =>
- [...settingsPermissionsConfig, ...actionPermissionsConfig].reduce<
- Partial<Record<string, string>>
- >((acc, permission) => {
- acc[permission.key] = permission.name;
- return acc;
- }, {}),
- [settingsPermissionsConfig, actionPermissionsConfig],
- );
-
- const ensureRoleId = async (): Promise<string | undefined> => {
- if (isDefined(roleId)) {
- return roleId;
- }
-
- if (!isDefined(workflowAiAgentActionAgent) || readonly) {
- return undefined;
- }
-
- const updatableStep = await getUpdatableWorkflowVersionStepOrThrow({
- stepId,
- stepType: 'AI_AGENT',
- });
-
- const updatableAgentId = updatableStep.settings.input.agentId;
-
- if (!isDefined(updatableAgentId)) {
- throw new Error(doNotTranslate('The AI agent step has no agent'));
- }
-
- const agentDisplayName =
- workflowAiAgentActionAgent.label ??
- workflowAiAgentActionAgent.name ??
- t`Agent`;
- const agentIdPrefix = workflowAiAgentActionAgent.id.substring(0, 8);
- const roleName = t`${agentDisplayName} role (${agentIdPrefix})`;
- const generatedRoleId = v4();
-
- await createRole({
- variables: {
- createRoleInput: {
- id: generatedRoleId,
- label: roleName,
- description: t`Auto-generated role for ${agentDisplayName}`,
- icon: 'IconLego',
- canAccessAllTools: false,
- canUpdateAllSettings: false,
- canReadAllObjectRecords: false,
- canUpdateAllObjectRecords: false,
- canSoftDeleteAllObjectRecords: false,
- canDestroyAllObjectRecords: false,
- canBeAssignedToAgents: true,
- canBeAssignedToUsers: false,
- canBeAssignedToApiKeys: false,
- },
- },
- });
-
- await assignRoleToAgent({
- variables: {
- agentId: updatableAgentId,
- roleId: generatedRoleId,
- },
- });
-
- const { refetchedAgent } = await refetchAgentAndRoles();
-
- // Update state with the refetched agent to ensure roleId is available
- // Apollo's onCompleted is not called on refetch, so we need to update manually
- if (isDefined(refetchedAgent)) {
- setWorkflowAiAgentActionAgent(refetchedAgent);
- }
-
- return generatedRoleId;
- };
-
- const handleAddPermission = async (
- objectMetadataId: string,
- permissionKey: SettingsRoleObjectPermissionKey,
- ) => {
- const ensuredRoleId = await ensureRoleId();
-
- if (!ensuredRoleId) {
- return;
- }
-
- const objectPermission = objectPermissions.find(
- (permission) => permission.objectMetadataId === objectMetadataId,
- );
-
- const updatedPermission: ObjectPermission = {
- objectMetadataId,
- canReadObjectRecords:
- permissionKey === 'canReadObjectRecords'
- ? true
- : (objectPermission?.canReadObjectRecords ??
- (permissionKey === 'canUpdateObjectRecords' ||
- permissionKey === 'canSoftDeleteObjectRecords' ||
- permissionKey === 'canDestroyObjectRecords'
- ? true
- : false)),
- canUpdateObjectRecords:
- permissionKey === 'canUpdateObjectRecords'
- ? true
- : (objectPermission?.canUpdateObjectRecords ?? false),
- canSoftDeleteObjectRecords:
- permissionKey === 'canSoftDeleteObjectRecords'
- ? true
- : (objectPermission?.canSoftDeleteObjectRecords ?? false),
- canDestroyObjectRecords:
- permissionKey === 'canDestroyObjectRecords'
- ? true
- : (objectPermission?.canDestroyObjectRecords ?? false),
- };
-
- const allObjectPermissions = objectPermissions
- .filter((permission) => permission.objectMetadataId !== objectMetadataId)
- .map((permission) => ({
- objectMetadataId: permission.objectMetadataId,
- canReadObjectRecords: permission.canReadObjectRecords ?? false,
- canUpdateObjectRecords: permission.canUpdateObjectRecords ?? false,
- canSoftDeleteObjectRecords:
- permission.canSoftDeleteObjectRecords ?? false,
- canDestroyObjectRecords: permission.canDestroyObjectRecords ?? false,
- }));
-
- allObjectPermissions.push({
- objectMetadataId: updatedPermission.objectMetadataId,
- canReadObjectRecords: updatedPermission.canReadObjectRecords ?? false,
- canUpdateObjectRecords: updatedPermission.canUpdateObjectRecords ?? false,
- canSoftDeleteObjectRecords:
- updatedPermission.canSoftDeleteObjectRecords ?? false,
- canDestroyObjectRecords:
- updatedPermission.canDestroyObjectRecords ?? false,
- });
-
- await upsertObjectPermissions({
- variables: {
- upsertObjectPermissionsInput: {
- roleId: ensuredRoleId,
- objectPermissions: allObjectPermissions,
- },
- },
- });
-
- await refetchAgentAndRoles();
- setWorkflowAiAgentPermissionsIsAddingPermission(false);
- setWorkflowAiAgentPermissionsSelectedObjectId(undefined);
- setWorkflowAiAgentPermissionsIsSystemObjectsListOpen(false);
- };
-
- const handleDeletePermission = async (
- objectMetadataId: string,
- permissionKey: SettingsRoleObjectPermissionKey,
- ) => {
- if (!isDefined(roleId) || readonly) {
- return;
- }
-
- const objectPermission = objectPermissions.find(
- (permission) => permission.objectMetadataId === objectMetadataId,
- );
-
- if (!isDefined(objectPermission)) {
- return;
- }
-
- const objectMetadata = objectMetadataItems.find(
- (item) => item.id === objectMetadataId,
- );
-
- if (!isDefined(objectMetadata)) {
- return;
- }
-
- const updatedPermission: ObjectPermission = {
- objectMetadataId,
- canReadObjectRecords:
- permissionKey === 'canReadObjectRecords'
- ? false
- : (objectPermission.canReadObjectRecords ?? false),
- canUpdateObjectRecords:
- permissionKey === 'canUpdateObjectRecords'
- ? false
- : (objectPermission.canUpdateObjectRecords ?? false),
- canSoftDeleteObjectRecords:
- permissionKey === 'canSoftDeleteObjectRecords'
- ? false
- : (objectPermission.canSoftDeleteObjectRecords ?? false),
- canDestroyObjectRecords:
- permissionKey === 'canDestroyObjectRecords'
- ? false
- : (objectPermission.canDestroyObjectRecords ?? false),
- };
-
- if (permissionKey === 'canReadObjectRecords') {
- updatedPermission.canUpdateObjectRecords = false;
- updatedPermission.canSoftDeleteObjectRecords = false;
- updatedPermission.canDestroyObjectRecords = false;
- }
-
- const allObjectPermissions = objectPermissions
- .filter((permission) => permission.objectMetadataId !== objectMetadataId)
- .map((permission) => ({
- objectMetadataId: permission.objectMetadataId,
- canReadObjectRecords: permission.canReadObjectRecords ?? false,
- canUpdateObjectRecords: permission.canUpdateObjectRecords ?? false,
- canSoftDeleteObjectRecords:
- permission.canSoftDeleteObjectRecords ?? false,
- canDestroyObjectRecords: permission.canDestroyObjectRecords ?? false,
- }));
-
- allObjectPermissions.push({
- objectMetadataId: updatedPermission.objectMetadataId,
- canReadObjectRecords: updatedPermission.canReadObjectRecords ?? false,
- canUpdateObjectRecords: updatedPermission.canUpdateObjectRecords ?? false,
- canSoftDeleteObjectRecords:
- updatedPermission.canSoftDeleteObjectRecords ?? false,
- canDestroyObjectRecords:
- updatedPermission.canDestroyObjectRecords ?? false,
- });
-
- await upsertObjectPermissions({
- variables: {
- upsertObjectPermissionsInput: {
- roleId,
- objectPermissions: allObjectPermissions,
- },
- },
- });
-
- await refetchAgentAndRoles();
- const permissionLabel = CRUD_PERMISSIONS.find(
- (permission) => permission.key === permissionKey,
- )?.label(objectMetadata.labelPlural);
-
- if (isDefined(permissionLabel)) {
- enqueueToast({
- status: 'success',
- children: t`${permissionLabel} Permission removed`,
- });
- }
- };
-
- const handleAddPermissionFlag = async (permissionFlagKey: string) => {
- if (readonly) {
- return;
- }
-
- const ensuredRoleId = await ensureRoleId();
-
- if (!ensuredRoleId || permissionFlagKeys.includes(permissionFlagKey)) {
- return;
- }
-
- await upsertPermissionFlags({
- variables: {
- upsertPermissionFlagsInput: {
- roleId: ensuredRoleId,
- permissionFlagKeys: [...permissionFlagKeys, permissionFlagKey],
- },
- },
- });
-
- await refetchAgentAndRoles();
- setWorkflowAiAgentPermissionsIsAddingPermission(false);
- setWorkflowAiAgentPermissionsSelectedObjectId(undefined);
- setWorkflowAiAgentPermissionsIsSystemObjectsListOpen(false);
- };
-
- const handleDeletePermissionFlag = async (permissionFlagKey: string) => {
- if (!isDefined(roleId) || readonly) {
- return;
- }
-
- if (!permissionFlagKeys.includes(permissionFlagKey)) {
- return;
- }
-
- const permissionFlagKeysAfterRemoval = permissionFlagKeys.filter(
- (flag) => flag !== permissionFlagKey,
- );
-
- await upsertPermissionFlags({
- variables: {
- upsertPermissionFlagsInput: {
- roleId,
- permissionFlagKeys: permissionFlagKeysAfterRemoval,
- },
- },
- });
-
- await refetchAgentAndRoles();
-
- const permissionLabel = permissionFlagLabelMap[permissionFlagKey];
-
- if (isDefined(permissionLabel)) {
- enqueueToast({
- status: 'success',
- children: t`${permissionLabel} permission removed`,
- });
- }
- };
-
- return {
- handleAddPermission,
- handleDeletePermission,
- handleAddPermissionFlag,
- handleDeletePermissionFlag,
- };
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentScopePermissionActions.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentScopePermissionActions.ts
new file mode 100644
index 00000000000..2273a835097
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/hooks/useWorkflowAiAgentScopePermissionActions.ts
@@ -0,0 +1,88 @@
+import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { workflowAiAgentPermissionsIsAddingPermissionState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsAddingPermissionState';
+import { workflowAiAgentPermissionsIsSystemObjectsListOpenState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsIsSystemObjectsListOpenState';
+import { workflowAiAgentPermissionsSelectedObjectIdState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentPermissionsSelectedObjectIdState';
+import { type WorkflowAiAgentObjectPermissionChange } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange';
+import { applyWorkflowAiAgentScopeObjectPermissionChange } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopeObjectPermissionChange';
+import { applyWorkflowAiAgentScopePermissionFlagChangeOrThrow } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopePermissionFlagChangeOrThrow';
+import { isUndefined } from '@sniptt/guards';
+import { type AiRunScope } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+type UseWorkflowAiAgentScopePermissionActionsParams = {
+ scope: AiRunScope | undefined;
+ onScopeChange: (scope: AiRunScope) => void;
+};
+
+export const useWorkflowAiAgentScopePermissionActions = ({
+ scope,
+ onScopeChange,
+}: UseWorkflowAiAgentScopePermissionActionsParams) => {
+ const { objectMetadataItems } = useFilteredObjectMetadataItems();
+ const setWorkflowAiAgentPermissionsSelectedObjectId = useSetAtomState(
+ workflowAiAgentPermissionsSelectedObjectIdState,
+ );
+ const setWorkflowAiAgentPermissionsIsAddingPermission = useSetAtomState(
+ workflowAiAgentPermissionsIsAddingPermissionState,
+ );
+ const setWorkflowAiAgentPermissionsIsSystemObjectsListOpen = useSetAtomState(
+ workflowAiAgentPermissionsIsSystemObjectsListOpenState,
+ );
+
+ const closeAddPermission = () => {
+ setWorkflowAiAgentPermissionsIsAddingPermission(false);
+ setWorkflowAiAgentPermissionsSelectedObjectId(undefined);
+ setWorkflowAiAgentPermissionsIsSystemObjectsListOpen(false);
+ };
+
+ const changeObjectPermission = (
+ { objectMetadataId, permissionKey }: WorkflowAiAgentObjectPermissionChange,
+ isGranted: boolean,
+ ) => {
+ const objectUniversalIdentifier = isDefined(objectMetadataId)
+ ? objectMetadataItems.find((item) => item.id === objectMetadataId)
+ ?.universalIdentifier
+ : null;
+
+ if (isUndefined(objectUniversalIdentifier)) {
+ return;
+ }
+
+ onScopeChange(
+ applyWorkflowAiAgentScopeObjectPermissionChange({
+ scope,
+ objectUniversalIdentifier,
+ permissionKey,
+ isGranted,
+ }),
+ );
+ };
+
+ const changePermissionFlag = (
+ permissionFlagKey: string,
+ isGranted: boolean,
+ ) =>
+ onScopeChange(
+ applyWorkflowAiAgentScopePermissionFlagChangeOrThrow({
+ scope,
+ permissionFlagKey,
+ isGranted,
+ }),
+ );
+
+ return {
+ onAddPermission: (change: WorkflowAiAgentObjectPermissionChange) => {
+ changeObjectPermission(change, true);
+ closeAddPermission();
+ },
+ onDeletePermission: (change: WorkflowAiAgentObjectPermissionChange) =>
+ changeObjectPermission(change, false),
+ onAddPermissionFlag: (permissionFlagKey: string) => {
+ changePermissionFlag(permissionFlagKey, true);
+ closeAddPermission();
+ },
+ onDeletePermissionFlag: (permissionFlagKey: string) =>
+ changePermissionFlag(permissionFlagKey, false),
+ };
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState.ts
deleted file mode 100644
index 346923edbe7..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
-
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const workflowAiAgentActionAgentState = createAtomState<
- FlatAgent | undefined
->({
- key: 'workflowAiAgentActionAgentState',
- defaultValue: undefined,
-});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission.ts
new file mode 100644
index 00000000000..8857c51eee4
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission.ts
@@ -0,0 +1,6 @@
+import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
+
+export type WorkflowAiAgentObjectPermission = {
+ // null for all objects
+ objectMetadataId: string | null;
+} & Partial<Record<SettingsRoleObjectPermissionKey, boolean | null>>;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange.ts
new file mode 100644
index 00000000000..b844f14fb25
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermissionChange.ts
@@ -0,0 +1,6 @@
+import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
+
+export type WorkflowAiAgentObjectPermissionChange = {
+ objectMetadataId: string | null;
+ permissionKey: SettingsRoleObjectPermissionKey;
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepInput.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepInput.ts
new file mode 100644
index 00000000000..d1aa3da39d9
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepInput.ts
@@ -0,0 +1,4 @@
+import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';
+
+export type WorkflowAiAgentStepInput =
+ WorkflowAiAgentAction['settings']['input'];
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps.ts
new file mode 100644
index 00000000000..45484a8cc98
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepPanelProps.ts
@@ -0,0 +1,8 @@
+import { type WorkflowAiAgentStepInput } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentStepInput';
+
+export type WorkflowAiAgentStepPanelProps = {
+ stepId: string;
+ input: WorkflowAiAgentStepInput;
+ readonly: boolean;
+ onInputChange: (inputUpdate: Partial<WorkflowAiAgentStepInput>) => void;
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts
new file mode 100644
index 00000000000..5a17f48830d
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts
@@ -0,0 +1,57 @@
+import { isAgentSelectableAsWorkflowStep } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep';
+
+const JSON_RESPONSE_FORMAT = {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { score: { type: 'number' } },
+ required: ['score'],
+ additionalProperties: false,
+ },
+};
+
+describe('isAgentSelectableAsWorkflowStep', () => {
+ it('offers an active agent with a JSON output', () => {
+ expect(
+ isAgentSelectableAsWorkflowStep({
+ isActive: true,
+ isSystem: false,
+ responseFormat: JSON_RESPONSE_FORMAT,
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ ['a text output', { type: 'text' }],
+ ['no output format', null],
+ [
+ 'a JSON output without fields',
+ { type: 'json', schema: { type: 'object', properties: {} } },
+ ],
+ ])('does not offer an agent with %s', (_, responseFormat) => {
+ expect(
+ isAgentSelectableAsWorkflowStep({
+ isActive: true,
+ isSystem: false,
+ responseFormat,
+ }),
+ ).toBe(false);
+ });
+
+ it('does not offer an inactive or system agent', () => {
+ expect(
+ isAgentSelectableAsWorkflowStep({
+ isActive: false,
+ isSystem: false,
+ responseFormat: JSON_RESPONSE_FORMAT,
+ }),
+ ).toBe(false);
+ expect(
+ isAgentSelectableAsWorkflowStep({
+ isActive: true,
+ isSystem: true,
+ responseFormat: JSON_RESPONSE_FORMAT,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/workflowAiAgentScope.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/workflowAiAgentScope.test.ts
new file mode 100644
index 00000000000..d5694499e91
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/workflowAiAgentScope.test.ts
@@ -0,0 +1,227 @@
+import {
+ PermissionFlagType,
+ SystemPermissionFlag,
+} from 'twenty-shared/constants';
+
+import { applyWorkflowAiAgentScopeObjectPermissionChange } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopeObjectPermissionChange';
+import { applyWorkflowAiAgentScopePermissionFlagChangeOrThrow } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopePermissionFlagChangeOrThrow';
+import { getWorkflowAiAgentScopePermissions } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/getWorkflowAiAgentScopePermissions';
+
+const objectMetadataItems = [
+ { id: 'person-id', universalIdentifier: 'person', labelPlural: 'People' },
+ {
+ id: 'company-id',
+ universalIdentifier: 'company',
+ labelPlural: 'Companies',
+ },
+];
+
+describe('workflow AI agent scope', () => {
+ it('reads a scope as written, without inheriting from all objects', () => {
+ expect(
+ getWorkflowAiAgentScopePermissions({
+ scope: {
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ canUpdateObjectRecords: true,
+ },
+ {
+ objectUniversalIdentifier: 'unknown',
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.SEND_EMAIL_TOOL,
+ SystemPermissionFlag.WORKSPACE,
+ ],
+ },
+ objectMetadataItems,
+ }),
+ ).toEqual({
+ objectPermissions: [
+ {
+ objectMetadataId: null,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: undefined,
+ canSoftDeleteObjectRecords: undefined,
+ canDestroyObjectRecords: undefined,
+ },
+ {
+ objectMetadataId: 'person-id',
+ objectUniversalIdentifier: 'person',
+ canUpdateObjectRecords: true,
+ },
+ ],
+ permissionFlagKeys: [
+ PermissionFlagType.SEND_EMAIL_TOOL,
+ PermissionFlagType.WORKSPACE,
+ ],
+ otherPermissionLabels: [],
+ });
+ });
+
+ it('lists the grants the editor has no row for', () => {
+ expect(
+ getWorkflowAiAgentScopePermissions({
+ scope: {
+ canUpdateAllSettings: true,
+ canAccessAllTools: true,
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canReadObjectRecords: false,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'phone',
+ canUpdateFieldValue: false,
+ },
+ ],
+ },
+ objectMetadataItems,
+ }).otherPermissionLabels,
+ ).toEqual([
+ 'All settings',
+ 'All tools',
+ 'See Companies (denied)',
+ 'Field permissions on People',
+ ]);
+ });
+
+ it('grants reading along with editing an object', () => {
+ expect(
+ applyWorkflowAiAgentScopeObjectPermissionChange({
+ scope: undefined,
+ objectUniversalIdentifier: 'person',
+ permissionKey: 'canUpdateObjectRecords',
+ isGranted: true,
+ }),
+ ).toEqual({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ });
+ });
+
+ it('removes an object grant instead of denying it, so all objects still apply', () => {
+ expect(
+ applyWorkflowAiAgentScopeObjectPermissionChange({
+ scope: {
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ },
+ objectUniversalIdentifier: 'person',
+ permissionKey: 'canReadObjectRecords',
+ isGranted: false,
+ }),
+ ).toEqual({ canReadAllObjectRecords: true, objectPermissions: [] });
+ });
+
+ it('keeps the other grants of the scope when a grant is removed', () => {
+ const fieldPermissions = [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ ];
+
+ expect(
+ applyWorkflowAiAgentScopeObjectPermissionChange({
+ scope: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canUpdateAllSettings: true,
+ fieldPermissions,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canUpdateObjectRecords: true,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ },
+ objectUniversalIdentifier: 'company',
+ permissionKey: 'canUpdateObjectRecords',
+ isGranted: false,
+ }),
+ ).toEqual({
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canUpdateAllSettings: true,
+ fieldPermissions,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canDestroyObjectRecords: false,
+ },
+ ],
+ });
+ });
+
+ it('removes every change on all objects when reading all objects is removed', () => {
+ expect(
+ applyWorkflowAiAgentScopeObjectPermissionChange({
+ scope: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ permissionFlagUniversalIdentifiers: [],
+ },
+ objectUniversalIdentifier: null,
+ permissionKey: 'canReadObjectRecords',
+ isGranted: false,
+ }),
+ ).toEqual({ permissionFlagUniversalIdentifiers: [] });
+ });
+
+ it('keeps the flags it does not know when a flag is granted or removed', () => {
+ const scope = {
+ permissionFlagUniversalIdentifiers: [
+ 'flag-from-a-newer-server',
+ SystemPermissionFlag.SEND_EMAIL_TOOL,
+ ],
+ };
+
+ const grantedScope = applyWorkflowAiAgentScopePermissionFlagChangeOrThrow({
+ scope,
+ permissionFlagKey: PermissionFlagType.HTTP_REQUEST_TOOL,
+ isGranted: true,
+ });
+
+ expect(grantedScope.permissionFlagUniversalIdentifiers).toEqual([
+ 'flag-from-a-newer-server',
+ SystemPermissionFlag.SEND_EMAIL_TOOL,
+ SystemPermissionFlag.HTTP_REQUEST_TOOL,
+ ]);
+ expect(
+ applyWorkflowAiAgentScopePermissionFlagChangeOrThrow({
+ scope: grantedScope,
+ permissionFlagKey: PermissionFlagType.SEND_EMAIL_TOOL,
+ isGranted: false,
+ }).permissionFlagUniversalIdentifiers,
+ ).toEqual([
+ 'flag-from-a-newer-server',
+ SystemPermissionFlag.HTTP_REQUEST_TOOL,
+ ]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopeObjectPermissionChange.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopeObjectPermissionChange.ts
new file mode 100644
index 00000000000..32902cc176f
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopeObjectPermissionChange.ts
@@ -0,0 +1,75 @@
+import { applyObjectPermissionChange } from '@/settings/roles/role-permissions/object-level-permissions/utils/applyObjectPermissionChange';
+import { type SettingsRoleObjectPermissionKey } from '@/settings/roles/role-permissions/objects-permissions/constants/SettingsRoleObjectPermissionIconConfig';
+import {
+ type AiRunScope,
+ type AiRunScopeObjectPermission,
+} from 'twenty-shared/ai';
+import {
+ OBJECT_PERMISSION_ACTIONS,
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION,
+} from 'twenty-shared/application';
+import { isDefined, removePropertiesFromRecord } from 'twenty-shared/utils';
+
+// removing drops the grant instead of denying it, so a broader grant still applies;
+// changing records needs reading them, so removing reading removes every change
+export const applyWorkflowAiAgentScopeObjectPermissionChange = ({
+ scope = {},
+ objectUniversalIdentifier,
+ permissionKey,
+ isGranted,
+}: {
+ scope: AiRunScope | undefined;
+ objectUniversalIdentifier: string | null;
+ permissionKey: SettingsRoleObjectPermissionKey;
+ isGranted: boolean;
+}): AiRunScope => {
+ const removedActions =
+ permissionKey === 'canReadObjectRecords'
+ ? [...OBJECT_PERMISSION_ACTIONS]
+ : [permissionKey];
+
+ if (!isDefined(objectUniversalIdentifier)) {
+ if (!isGranted) {
+ return removePropertiesFromRecord(
+ scope,
+ removedActions.map(
+ (action) => ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION[action],
+ ),
+ );
+ }
+
+ return {
+ ...scope,
+ [ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION[permissionKey]]: true,
+ canReadAllObjectRecords: true,
+ };
+ }
+
+ const otherObjectPermissions = (scope.objectPermissions ?? []).filter(
+ (objectPermission) =>
+ objectPermission.objectUniversalIdentifier !== objectUniversalIdentifier,
+ );
+ const existingObjectPermission = scope.objectPermissions?.find(
+ (objectPermission) =>
+ objectPermission.objectUniversalIdentifier === objectUniversalIdentifier,
+ ) ?? { objectUniversalIdentifier };
+
+ const changedObjectPermission: AiRunScopeObjectPermission = isGranted
+ ? applyObjectPermissionChange({
+ objectPermission: existingObjectPermission,
+ permissionKey,
+ value: true,
+ })
+ : removePropertiesFromRecord(existingObjectPermission, removedActions);
+
+ const hasRemainingPermission = OBJECT_PERMISSION_ACTIONS.some((action) =>
+ isDefined(changedObjectPermission[action]),
+ );
+
+ return {
+ ...scope,
+ objectPermissions: hasRemainingPermission
+ ? [...otherObjectPermissions, changedObjectPermission]
+ : otherObjectPermissions,
+ };
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopePermissionFlagChangeOrThrow.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopePermissionFlagChangeOrThrow.ts
new file mode 100644
index 00000000000..3b99cc03172
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/applyWorkflowAiAgentScopePermissionFlagChangeOrThrow.ts
@@ -0,0 +1,38 @@
+import { type AiRunScope } from 'twenty-shared/ai';
+import { PERMISSION_FLAG_UNIVERSAL_IDENTIFIER_BY_TYPE } from 'twenty-shared/constants';
+import { doNotTranslate } from 'twenty-shared/i18n';
+import { CustomError, isDefined } from 'twenty-shared/utils';
+
+export const applyWorkflowAiAgentScopePermissionFlagChangeOrThrow = ({
+ scope,
+ permissionFlagKey,
+ isGranted,
+}: {
+ scope: AiRunScope | undefined;
+ permissionFlagKey: string;
+ isGranted: boolean;
+}): AiRunScope => {
+ const universalIdentifier =
+ PERMISSION_FLAG_UNIVERSAL_IDENTIFIER_BY_TYPE.get(permissionFlagKey);
+
+ if (!isDefined(universalIdentifier)) {
+ throw new CustomError(
+ doNotTranslate(`Unknown permission flag ${permissionFlagKey}`),
+ 'UNKNOWN_PERMISSION_FLAG',
+ );
+ }
+
+ const otherUniversalIdentifiers = (
+ scope?.permissionFlagUniversalIdentifiers ?? []
+ ).filter(
+ (existingUniversalIdentifier) =>
+ existingUniversalIdentifier !== universalIdentifier,
+ );
+
+ return {
+ ...scope,
+ permissionFlagUniversalIdentifiers: isGranted
+ ? [...otherUniversalIdentifiers, universalIdentifier]
+ : otherUniversalIdentifiers,
+ };
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/getWorkflowAiAgentScopePermissions.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/getWorkflowAiAgentScopePermissions.ts
new file mode 100644
index 00000000000..e660564e6b1
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/getWorkflowAiAgentScopePermissions.ts
@@ -0,0 +1,97 @@
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { CRUD_PERMISSIONS } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/constants/WorkflowAiAgentCrudPermissions';
+import { type WorkflowAiAgentObjectPermission } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/types/WorkflowAiAgentObjectPermission';
+import { t } from '@lingui/core/macro';
+import { type AiRunScope } from 'twenty-shared/ai';
+import {
+ OBJECT_PERMISSION_ACTIONS,
+ ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION,
+} from 'twenty-shared/application';
+import { PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+
+// rows show the scope as written, not what all objects imply, so removing a row removes exactly that grant
+export const getWorkflowAiAgentScopePermissions = ({
+ scope,
+ objectMetadataItems,
+}: {
+ scope: AiRunScope | undefined;
+ objectMetadataItems: Pick<
+ EnrichedObjectMetadataItem,
+ 'id' | 'universalIdentifier' | 'labelPlural'
+ >[];
+}): {
+ objectPermissions: WorkflowAiAgentObjectPermission[];
+ permissionFlagKeys: string[];
+ otherPermissionLabels: string[];
+} => {
+ const findObjectMetadataItem = (objectUniversalIdentifier: string) =>
+ objectMetadataItems.find(
+ (item) => item.universalIdentifier === objectUniversalIdentifier,
+ );
+
+ const objectPermissions = (scope?.objectPermissions ?? []).flatMap(
+ (objectPermission) => {
+ const objectMetadataItem = findObjectMetadataItem(
+ objectPermission.objectUniversalIdentifier,
+ );
+
+ return isDefined(objectMetadataItem)
+ ? [{ ...objectPermission, objectMetadataItem }]
+ : [];
+ },
+ );
+
+ const deniedPermissionLabels = objectPermissions.flatMap(
+ ({ objectMetadataItem, ...objectPermission }) =>
+ CRUD_PERMISSIONS.filter(({ key }) => objectPermission[key] === false).map(
+ ({ label }) => {
+ const permissionLabel = label(objectMetadataItem.labelPlural);
+
+ return t`${permissionLabel} (denied)`;
+ },
+ ),
+ );
+
+ const fieldPermissionLabels = [
+ ...new Set(
+ (scope?.fieldPermissions ?? []).map(
+ ({ objectUniversalIdentifier }) =>
+ findObjectMetadataItem(objectUniversalIdentifier)?.labelPlural,
+ ),
+ ),
+ ]
+ .filter(isDefined)
+ .map((objectLabel) => t`Field permissions on ${objectLabel}`);
+
+ return {
+ objectPermissions: [
+ {
+ objectMetadataId: null,
+ ...Object.fromEntries(
+ OBJECT_PERMISSION_ACTIONS.map((action) => [
+ action,
+ scope?.[ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION[action]],
+ ]),
+ ),
+ },
+ ...objectPermissions.map(
+ ({ objectMetadataItem, ...objectPermission }) => ({
+ ...objectPermission,
+ objectMetadataId: objectMetadataItem.id,
+ }),
+ ),
+ ],
+ permissionFlagKeys: (scope?.permissionFlagUniversalIdentifiers ?? [])
+ .map((universalIdentifier) =>
+ PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER.get(universalIdentifier),
+ )
+ .filter(isDefined),
+ otherPermissionLabels: [
+ ...(scope?.canUpdateAllSettings ? [t`All settings`] : []),
+ ...(scope?.canAccessAllTools ? [t`All tools`] : []),
+ ...deniedPermissionLabels,
+ ...fieldPermissionLabels,
+ ],
+ };
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts
new file mode 100644
index 00000000000..06fd017fc92
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts
@@ -0,0 +1,21 @@
+import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
+import {
+ agentResponseFormatSchema,
+ isAgentRunnableAsWorkflowStep,
+} from 'twenty-shared/workflow';
+
+// picker-only: a step's output must be known when the workflow is built, so only agents with a JSON output are listed
+export const isAgentSelectableAsWorkflowStep = (
+ agent: Pick<FlatAgent, 'isActive' | 'isSystem' | 'responseFormat'>,
+): boolean => {
+ const parsedResponseFormat = agentResponseFormatSchema.safeParse(
+ agent.responseFormat,
+ );
+
+ return (
+ isAgentRunnableAsWorkflowStep(agent) &&
+ parsedResponseFormat.success &&
+ parsedResponseFormat.data.type === 'json' &&
+ Object.keys(parsedResponseFormat.data.schema.properties).length > 0
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/AiAgentAction.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/AiAgentAction.ts
index f5c6784b1e5..5e88d2bccc9 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/AiAgentAction.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/AiAgentAction.ts
@@ -7,7 +7,7 @@ export const AI_AGENT_ACTION: {
type: Extract<WorkflowActionType, 'AI_AGENT'>;
icon: string;
} = {
- defaultLabel: msg`Agent`,
+ defaultLabel: msg`Generate`,
type: 'AI_AGENT',
- icon: 'IconLego',
+ icon: 'IconSparkles',
};
diff --git a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
index 8baa9e60217..c531654d1b9 100644
--- a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
@@ -1,4 +1,5 @@
import { type WorkflowManifest } from 'twenty-shared/application';
+import { WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES } from 'twenty-shared/workflow';
import { defineWorkflow } from '@/sdk/define/workflows/define-workflow';
@@ -140,4 +141,75 @@ describe('defineWorkflow', () => {
expect(result.success).toBe(false);
expect(result.errors).toEqual([error]);
});
+
+ const withAiAgentStep = (
+ input: Extract<
+ WorkflowManifest['version']['steps'][number],
+ { type: 'AI_AGENT' }
+ >['input'],
+ ): WorkflowManifest => ({
+ ...workflow,
+ version: {
+ ...workflow.version,
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Qualify',
+ type: 'AI_AGENT',
+ input,
+ nextStepIds: [],
+ },
+ ],
+ },
+ });
+
+ it('accepts an AI agent step that carries its own config', () => {
+ expect(
+ defineWorkflow(
+ withAiAgentStep({
+ instructions: 'Qualify the lead.',
+ scope: { canReadAllObjectRecords: true },
+ prompt: 'Qualify {{trigger.name}}',
+ }),
+ ).success,
+ ).toBe(true);
+ });
+
+ it('refuses an AI agent step that runs an agent with its own config', () => {
+ expect(
+ defineWorkflow(
+ withAiAgentStep({
+ agentUniversalIdentifier: '66666666-6666-4666-8666-666666666666',
+ modelId: 'model-id',
+ }),
+ ).success,
+ ).toBe(false);
+ });
+
+ it('refuses a conversation on an AI agent step without an agent', () => {
+ expect(
+ defineWorkflow(
+ withAiAgentStep({
+ instructions: 'Qualify the lead.',
+ prompt: 'Qualify {{trigger.name}}',
+ conversation: { scope: 'RUN' },
+ }),
+ ).errors,
+ ).toEqual([
+ `version.steps.0.input.agentUniversalIdentifier: ${WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.GENERATE_STEP_HAS_CONVERSATION_CONFIG}`,
+ ]);
+ });
+
+ it('accepts a conversation on an AI agent step running an agent', () => {
+ expect(
+ defineWorkflow(
+ withAiAgentStep({
+ agentUniversalIdentifier: '66666666-6666-4666-8666-666666666666',
+ prompt: 'Qualify {{trigger.name}}',
+ humanInputInstructions: 'Ask when the company is unclear',
+ conversation: { scope: 'RUN' },
+ }),
+ ).success,
+ ).toBe(true);
+ });
});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/list-conversation-messages.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/list-conversation-messages.spec.ts
new file mode 100644
index 00000000000..6eaa2b57119
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/list-conversation-messages.spec.ts
@@ -0,0 +1,87 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+import { listConversationMessages } from '@/sdk/logic-function/agents/list-conversation-messages';
+import { type AgentConversationHistory } from '@/sdk/logic-function/agents/types/agent-conversation.type';
+
+const STREAM_CATCHUP = { chunks: [], maxSeq: 0, error: null };
+
+const RESPONSE = {
+ messages: [
+ {
+ id: 'message-id',
+ threadId: 'thread-id',
+ turnId: 'run-id',
+ senderWorkspaceMemberId: null,
+ role: 'assistant',
+ status: 'sent',
+ createdAt: '2026-10-31T10:00:00.000Z',
+ processedAt: '2026-10-31T10:00:02.000Z',
+ parts: [
+ { orderIndex: 1, type: 'text', textContent: 'Acme is a fit.' },
+ { orderIndex: 0, type: 'step-start' },
+ ],
+ },
+ ],
+ streamCatchup: STREAM_CATCHUP,
+};
+
+const HISTORY: AgentConversationHistory = {
+ messages: [
+ {
+ id: 'message-id',
+ role: 'assistant',
+ parts: [{ type: 'step-start' }, { type: 'text', text: 'Acme is a fit.' }],
+ metadata: {
+ createdAt: '2026-10-31T10:00:00.000Z',
+ senderWorkspaceMemberId: null,
+ turnId: 'run-id',
+ startedAt: '2026-10-31T10:00:00.000Z',
+ finishedAt: '2026-10-31T10:00:02.000Z',
+ },
+ },
+ ],
+ streamCatchup: STREAM_CATCHUP,
+};
+
+describe('listConversationMessages', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ fetchSpy.mockResolvedValue(
+ new Response(JSON.stringify({ data: RESPONSE }), { status: 200 }),
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('reads the history of a conversation by agent and thread key as UI messages', async () => {
+ const conversation = {
+ agentUniversalIdentifier: 'agent-uid',
+ threadKey: 'C123:1700000000.000100',
+ };
+
+ expect(await listConversationMessages(conversation)).toMatchObject(HISTORY);
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+ const sentBody = JSON.parse(String(requestInit?.body));
+
+ expect(url).toBe('https://api.test/metadata');
+ expect(sentBody.query).toContain('chatMessages(');
+ expect(sentBody.query).toContain('chatStreamCatchupChunks(');
+ expect(sentBody.variables).toEqual(conversation);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts
index 8001a10c84f..1ae6517022f 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/run-agent.spec.ts
@@ -28,6 +28,7 @@ describe('runAgent', () => {
it('POSTs the runAgent mutation to /metadata and returns the result', async () => {
const payload = {
threadId: 'thread-id',
+ runId: 'run-id',
status: 'COMPLETED',
result: { response: 'done' },
error: null,
@@ -62,6 +63,7 @@ describe('runAgent', () => {
const sentBody = JSON.parse(requestInit?.body as string);
expect(sentBody.query).toContain('runAgent(input: $input)');
+ expect(sentBody.query).toContain('runId');
expect(sentBody.variables).toEqual({
input: {
agentUniversalIdentifier: 'agent-uid',
@@ -175,7 +177,9 @@ describe('runAgent', () => {
await expect(
runAgent({ agentUniversalIdentifier: 'a', prompt: 'p' }),
- ).rejects.toThrow(/requires the app runtime env vars/);
+ ).rejects.toThrow(
+ 'requires the app runtime env vars TWENTY_API_URL and TWENTY_APP_APPLICATION_ACCESS_TOKEN (or TWENTY_APP_ACCESS_TOKEN)',
+ );
expect(fetchSpy).not.toHaveBeenCalled();
});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/stream-conversation.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/stream-conversation.spec.ts
new file mode 100644
index 00000000000..7945501ec15
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/__tests__/stream-conversation.spec.ts
@@ -0,0 +1,256 @@
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+import { streamConversation } from '@/sdk/logic-function/agents/stream-conversation';
+
+const CONVERSATION = {
+ agentUniversalIdentifier: 'agent-uid',
+ threadKey: 'deal-42',
+};
+const KEEPALIVE: AgentChatSubscriptionEvent = { type: 'keepalive' };
+const CHUNK: AgentChatSubscriptionEvent = {
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta', id: 'text-1', delta: 'Acme renews' },
+ seq: 3,
+};
+
+const toNextEvent = (result: {
+ data?: { onAgentChatEvent: { event: AgentChatSubscriptionEvent } };
+ errors?: { message: string }[];
+}) => `event: next\ndata: ${JSON.stringify(result)}\n\n`;
+
+const toEventData = (event: AgentChatSubscriptionEvent) => ({
+ data: { onAgentChatEvent: { event } },
+});
+
+const mockServerSentEvents = (chunks: string[]) =>
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ chunks.forEach((chunk) =>
+ controller.enqueue(new TextEncoder().encode(chunk)),
+ );
+ controller.close();
+ },
+ }),
+ { status: 200, headers: { 'Content-Type': 'text/event-stream' } },
+ );
+
+const collect = async (events: AsyncIterable<AgentChatSubscriptionEvent>) => {
+ const collected: AgentChatSubscriptionEvent[] = [];
+
+ for await (const event of events) {
+ collected.push(event);
+ }
+
+ return collected;
+};
+
+describe('streamConversation', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('yields the chat events the subscription sends until it completes', async () => {
+ const chunk = toNextEvent(toEventData(CHUNK));
+
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([
+ ':\n\n',
+ toNextEvent(toEventData(KEEPALIVE)),
+ chunk.slice(0, 20),
+ chunk.slice(20),
+ 'event: complete\n\n',
+ ]),
+ );
+
+ expect(await collect(streamConversation(CONVERSATION))).toEqual([
+ KEEPALIVE,
+ CHUNK,
+ ]);
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+ const sentBody = JSON.parse(String(requestInit?.body));
+
+ expect(url).toBe('https://api.test/metadata');
+ expect(requestInit?.headers).toEqual(
+ expect.objectContaining({
+ Accept: 'text/event-stream',
+ Authorization: 'Bearer app-token',
+ }),
+ );
+ expect(sentBody.query).toContain('onAgentChatEvent(');
+ expect(sentBody.variables).toEqual(CONVERSATION);
+ });
+
+ it('surfaces subscription errors as a regular Error', async () => {
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([
+ toNextEvent({ errors: [{ message: 'Agent agent-uid not found' }] }),
+ ]),
+ );
+
+ await expect(collect(streamConversation(CONVERSATION))).rejects.toThrow(
+ 'streamConversation() failed: Agent agent-uid not found',
+ );
+ });
+
+ it('fails on a result that is not a chat event', async () => {
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([`event: next\ndata: {"data":{"other":1}}\n\n`]),
+ );
+
+ await expect(collect(streamConversation(CONVERSATION))).rejects.toThrow(
+ 'streamConversation() failed: unexpected result',
+ );
+ });
+
+ it('passes on what a newer server sends, checking only the event type', async () => {
+ const events = [
+ { type: 'thread-renamed' },
+ { type: 'keepalive', addedField: 1 },
+ ];
+
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([
+ ...events.map(
+ (event) =>
+ `event: next\ndata: ${JSON.stringify({ data: { onAgentChatEvent: { event } } })}\n\n`,
+ ),
+ 'event: complete\n\n',
+ ]),
+ );
+
+ expect(await collect(streamConversation(CONVERSATION))).toEqual(events);
+ });
+
+ it('reads events whose CRLF line endings are split across reads', async () => {
+ const keepalive = toNextEvent(toEventData(KEEPALIVE)).replace(
+ /\n/g,
+ '\r\n',
+ );
+
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([
+ keepalive.slice(0, -1),
+ keepalive.slice(-1),
+ 'event: complete\r',
+ '\n\r\n',
+ ]),
+ );
+
+ expect(await collect(streamConversation(CONVERSATION))).toEqual([
+ KEEPALIVE,
+ ]);
+ });
+
+ it('surfaces the GraphQL errors of a refused request', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ errors: [
+ {
+ message:
+ 'Continuing a conversation requires an application access token',
+ },
+ ],
+ }),
+ { status: 400, statusText: 'Bad Request' },
+ ),
+ );
+
+ await expect(collect(streamConversation(CONVERSATION))).rejects.toThrow(
+ 'streamConversation() failed: Continuing a conversation requires an application access token',
+ );
+ });
+
+ it('names the HTTP status of a refused request without GraphQL errors', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response('Bad gateway', { status: 502, statusText: 'Bad Gateway' }),
+ );
+
+ await expect(collect(streamConversation(CONVERSATION))).rejects.toThrow(
+ 'streamConversation() failed: HTTP 502 Bad Gateway',
+ );
+ });
+
+ it('fails when the stream closes without completing, so the caller can resume', async () => {
+ fetchSpy.mockResolvedValue(
+ mockServerSentEvents([toNextEvent(toEventData(KEEPALIVE))]),
+ );
+
+ await expect(collect(streamConversation(CONVERSATION))).rejects.toThrow(
+ 'streamConversation() failed: the stream closed early; read the history and stream again to resume',
+ );
+ });
+
+ it('stops without failing when aborted while connecting', async () => {
+ const abortController = new AbortController();
+
+ fetchSpy.mockImplementation(
+ (_url, requestInit) =>
+ new Promise((_resolve, reject) => {
+ requestInit?.signal?.addEventListener('abort', () =>
+ reject(new DOMException('Aborted', 'AbortError')),
+ );
+ }),
+ );
+
+ const events = collect(
+ streamConversation({ ...CONVERSATION, signal: abortController.signal }),
+ );
+
+ await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalled());
+ abortController.abort();
+
+ await expect(events).resolves.toEqual([]);
+ });
+
+ it('stops without failing when aborted with a reason of its own', async () => {
+ const abortController = new AbortController();
+
+ fetchSpy.mockImplementation(
+ (_url, requestInit) =>
+ new Promise((_resolve, reject) => {
+ requestInit?.signal?.addEventListener('abort', () =>
+ reject(requestInit.signal?.reason),
+ );
+ }),
+ );
+
+ const events = collect(
+ streamConversation({ ...CONVERSATION, signal: abortController.signal }),
+ );
+
+ await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalled());
+ abortController.abort('done');
+
+ await expect(events).resolves.toEqual([]);
+ });
+
+ it('does not connect once its signal is aborted', async () => {
+ const events = await collect(
+ streamConversation({ ...CONVERSATION, signal: AbortSignal.abort() }),
+ );
+
+ expect(events).toEqual([]);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/list-conversation-messages.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/list-conversation-messages.ts
new file mode 100644
index 00000000000..5b099a9bf78
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/list-conversation-messages.ts
@@ -0,0 +1,78 @@
+import {
+ type AgentMessageRow,
+ mapAgentMessagesToUIMessages,
+} from 'twenty-shared/ai';
+
+import {
+ type AgentConversationHistory,
+ type AgentConversationInput,
+} from '@/sdk/logic-function/agents/types/agent-conversation.type';
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const CONVERSATION_MESSAGES_QUERY = `
+ query ConversationMessages($agentUniversalIdentifier: UUID!, $threadKey: String!) {
+ messages: chatMessages(agentUniversalIdentifier: $agentUniversalIdentifier, threadKey: $threadKey) {
+ id
+ threadId
+ turnId
+ senderWorkspaceMemberId
+ role
+ status
+ createdAt
+ processedAt
+ parts {
+ orderIndex
+ type
+ textContent
+ reasoningContent
+ toolName
+ toolCallId
+ toolInput
+ toolOutput
+ state
+ providerExecuted
+ errorMessage
+ sourceUrlSourceId
+ sourceUrlUrl
+ sourceUrlTitle
+ sourceDocumentSourceId
+ sourceDocumentMediaType
+ sourceDocumentTitle
+ sourceDocumentFilename
+ fileMediaType
+ fileFilename
+ fileUrl
+ fileId
+ providerMetadata
+ }
+ }
+ streamCatchup: chatStreamCatchupChunks(agentUniversalIdentifier: $agentUniversalIdentifier, threadKey: $threadKey) {
+ chunks
+ maxSeq
+ error {
+ code
+ message
+ }
+ }
+ }
+`;
+
+export const listConversationMessages = async (
+ conversation: AgentConversationInput,
+): Promise<AgentConversationHistory> => {
+ const { messages, streamCatchup } = await postGraphqlRequest<
+ AgentConversationInput,
+ Pick<AgentConversationHistory, 'streamCatchup'> & {
+ messages: AgentMessageRow[];
+ }
+ >({
+ query: CONVERSATION_MESSAGES_QUERY,
+ variables: conversation,
+ caller: 'listConversationMessages',
+ });
+
+ return {
+ messages: mapAgentMessagesToUIMessages(messages),
+ streamCatchup,
+ };
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts
index 987a305a2bc..987302e7d17 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/run-agent.ts
@@ -5,11 +5,13 @@ import {
import { isDefined } from 'twenty-shared/utils';
import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+import { toRunAgentMessages } from '@/sdk/logic-function/utils/to-run-agent-messages.util';
const RUN_AGENT_MUTATION = `
mutation RunAgent($input: RunAgentInput!) {
runAgent(input: $input) {
threadId
+ runId
status
result
error
@@ -24,13 +26,7 @@ export const runAgent = async ({
}: RunAgentInput): Promise<RunAgentResult> => {
const variables = {
input: isDefined(input)
- ? {
- ...rest,
- input:
- typeof input === 'string'
- ? [{ role: 'user', content: input }]
- : input,
- }
+ ? { ...rest, input: toRunAgentMessages(input) }
: rest,
};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/stream-conversation.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/stream-conversation.ts
new file mode 100644
index 00000000000..b97b8de089f
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/stream-conversation.ts
@@ -0,0 +1,28 @@
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+
+import { type AgentConversationInput } from '@/sdk/logic-function/agents/types/agent-conversation.type';
+import { streamAgentChatEvents } from '@/sdk/logic-function/utils/stream-agent-chat-events.util';
+
+const ON_AGENT_CHAT_EVENT_SUBSCRIPTION = `
+ subscription OnAgentChatEvent($agentUniversalIdentifier: UUID!, $threadKey: String!) {
+ onAgentChatEvent(agentUniversalIdentifier: $agentUniversalIdentifier, threadKey: $threadKey) {
+ event
+ }
+ }
+`;
+
+export type StreamConversationInput = AgentConversationInput & {
+ signal?: AbortSignal;
+};
+
+export const streamConversation = ({
+ signal,
+ ...conversation
+}: StreamConversationInput): AsyncGenerator<AgentChatSubscriptionEvent> =>
+ streamAgentChatEvents({
+ query: ON_AGENT_CHAT_EVENT_SUBSCRIPTION,
+ variables: conversation,
+ caller: 'streamConversation',
+ signal,
+ closedEarlyAdvice: '; read the history and stream again to resume',
+ });
diff --git a/packages/twenty-sdk/src/sdk/logic-function/agents/types/agent-conversation.type.ts b/packages/twenty-sdk/src/sdk/logic-function/agents/types/agent-conversation.type.ts
new file mode 100644
index 00000000000..27c0f9963e2
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/agents/types/agent-conversation.type.ts
@@ -0,0 +1,30 @@
+// an application names its conversation with an agent by the key it passes to runAgent
+export type AgentConversationInput = {
+ agentUniversalIdentifier: string;
+ threadKey: string;
+};
+
+// an AI SDK UIMessage, as the chat and its live chunks build it, typed without the ai package
+export type AgentConversationMessage = {
+ id: string;
+ role: 'system' | 'user' | 'assistant';
+ parts: ({ type: string } & Record<string, unknown>)[];
+ metadata?: {
+ createdAt?: string;
+ startedAt?: string;
+ finishedAt?: string;
+ senderWorkspaceMemberId?: string | null;
+ // the run the message belongs to, as runAgent() returns it
+ turnId?: string | null;
+ };
+};
+
+export type AgentConversationHistory = {
+ messages: AgentConversationMessage[];
+ // the chunks of a reply still streaming; live chunks with a seq up to maxSeq repeat them
+ streamCatchup: {
+ chunks: Record<string, unknown>[];
+ maxSeq: number;
+ error: { code: string; message: string } | null;
+ };
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/ai/__tests__/ai.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/ai/__tests__/ai.spec.ts
new file mode 100644
index 00000000000..5b10baa4bb3
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/ai/__tests__/ai.spec.ts
@@ -0,0 +1,630 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+import { ai } from '@/sdk/logic-function/ai/ai';
+
+const RESULT = {
+ success: true,
+ text: 'Acme is a good fit.',
+ object: null,
+ error: null,
+ runId: 'run-id',
+ usage: { inputTokens: 12, outputTokens: 7 },
+};
+
+describe('ai.generate', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ fetchSpy.mockResolvedValue(
+ new Response(JSON.stringify({ data: { generate: RESULT } }), {
+ status: 200,
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('POSTs the generate mutation to /metadata and returns the result', async () => {
+ const result = await ai.generate({
+ input: 'Is Acme a good fit?',
+ instructions: 'Qualify leads for Twenty.',
+ });
+
+ expect(result).toEqual(RESULT);
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(url).toBe('https://api.test/metadata');
+
+ const sentBody = JSON.parse(requestInit?.body as string);
+
+ expect(sentBody.query).toContain('generate(input: $input)');
+ expect(sentBody.variables).toEqual({
+ input: {
+ input: [{ role: 'user', content: 'Is Acme a good fit?' }],
+ instructions: 'Qualify leads for Twenty.',
+ },
+ });
+ });
+
+ it('acts as the person who triggered the run rather than the application', async () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
+
+ try {
+ await ai.generate({ input: 'Is Acme a good fit?' });
+
+ expect(
+ new Headers(fetchSpy.mock.calls[0][1]?.headers).get('Authorization'),
+ ).toBe('Bearer app-token');
+ } finally {
+ delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
+ }
+ });
+
+ it('sends messages and the scope as given', async () => {
+ const scope = {
+ objectPermissions: [
+ { objectUniversalIdentifier: 'company', canReadObjectRecords: true },
+ ],
+ };
+
+ await ai.generate({
+ input: [
+ { role: 'user', content: 'Summarize Acme.' },
+ { role: 'assistant', content: 'Which period?' },
+ { role: 'user', content: 'This quarter.' },
+ ],
+ scope,
+ });
+
+ const sentBody = JSON.parse(fetchSpy.mock.calls[0][1]?.body as string);
+
+ expect(sentBody.variables.input.input).toHaveLength(3);
+ expect(sentBody.variables.input.scope).toEqual(scope);
+ });
+});
+
+const RUN_ID = '3f1c9a52-7b0e-4d6a-8c2f-9e4b5a6d7c81';
+
+const toNextEvent = (event: Record<string, unknown>) =>
+ new TextEncoder().encode(
+ `event: next\ndata: ${JSON.stringify({ data: { onAgentChatEvent: { event } } })}\n\n`,
+ );
+
+const isStreamRequest = (requestInit: RequestInit | undefined) =>
+ new Headers(requestInit?.headers).get('Accept') === 'text/event-stream';
+
+const mockRunChannel = ({
+ fetchSpy,
+ isKeepaliveHeld = false,
+}: {
+ fetchSpy: MockInstance<typeof fetch>;
+ isKeepaliveHeld?: boolean;
+}) => {
+ let channel: ReadableStreamDefaultController<Uint8Array> | undefined;
+ let isChannelCancelled = false;
+ let answerMutation: (body: Record<string, unknown>) => void = () => {};
+ const requests: string[] = [];
+
+ fetchSpy.mockImplementation(async (_url, requestInit) => {
+ const signal = requestInit?.signal;
+
+ if (isStreamRequest(requestInit)) {
+ requests.push('subscription');
+
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ channel = controller;
+
+ if (!isKeepaliveHeld) {
+ controller.enqueue(toNextEvent({ type: 'keepalive' }));
+ }
+ },
+ cancel() {
+ isChannelCancelled = true;
+ },
+ });
+
+ signal?.addEventListener('abort', () =>
+ channel?.error(new DOMException('Aborted', 'AbortError')),
+ );
+
+ return new Response(body, { status: 200 });
+ }
+
+ requests.push('mutation');
+
+ return new Promise<Response>((resolve, reject) => {
+ signal?.addEventListener('abort', () =>
+ reject(new DOMException('Aborted', 'AbortError')),
+ );
+ answerMutation = (body) =>
+ resolve(new Response(JSON.stringify(body), { status: 200 }));
+ });
+ });
+
+ return {
+ requests,
+ send: (event: Record<string, unknown>) =>
+ channel?.enqueue(toNextEvent(event)),
+ answerMutation: (body: Record<string, unknown>) => answerMutation(body),
+ fail: () => channel?.error(new Error('Network down')),
+ releaseKeepalive: () =>
+ channel?.enqueue(toNextEvent({ type: 'keepalive' })),
+ isChannelCancelled: () => isChannelCancelled,
+ };
+};
+
+describe('ai.generate with onChunk', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', 'https://api.test');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-token');
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ fetchSpy.mockRestore();
+ });
+
+ it('follows the run from before it starts and resolves once its last chunk is delivered', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const chunks: Record<string, unknown>[] = [];
+
+ const generation = ai.generate({
+ input: 'Is Acme a good fit?',
+ onChunk: (chunk) => {
+ chunks.push(chunk);
+ },
+ });
+
+ await vi.waitFor(() =>
+ expect(runChannel.requests).toEqual(['subscription', 'mutation']),
+ );
+
+ const [subscriptionCall, mutationCall] = fetchSpy.mock.calls;
+
+ const subscriptionBody = JSON.parse(String(subscriptionCall[1]?.body));
+
+ expect(subscriptionBody.query).toContain('onAgentChatEvent(runId: $runId)');
+ // the SDK picks the run id itself, so the mutation runs on the channel it follows
+ expect(
+ JSON.parse(String(mutationCall[1]?.body)).variables.input,
+ ).toMatchObject({ runId: subscriptionBody.variables.runId });
+
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta', id: 'text-1', delta: 'Acme' },
+ seq: 1,
+ });
+ runChannel.answerMutation({
+ data: { generate: { ...RESULT, runId: RUN_ID } },
+ });
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'finish' },
+ seq: 2,
+ });
+ runChannel.send({ type: 'run-finished' });
+
+ await expect(generation).resolves.toEqual({ ...RESULT, runId: RUN_ID });
+ expect(chunks).toEqual([
+ { type: 'text-delta', id: 'text-1', delta: 'Acme' },
+ { type: 'finish' },
+ ]);
+ expect(runChannel.isChannelCancelled()).toBe(true);
+ });
+
+ it('starts the run only once the subscription is live', async () => {
+ const runChannel = mockRunChannel({ fetchSpy, isKeepaliveHeld: true });
+
+ const generation = ai.generate({ input: 'Hi', onChunk: () => {} });
+
+ await vi.waitFor(() =>
+ expect(runChannel.requests).toEqual(['subscription']),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ expect(runChannel.requests).toEqual(['subscription']);
+
+ runChannel.releaseKeepalive();
+
+ await vi.waitFor(() =>
+ expect(runChannel.requests).toEqual(['subscription', 'mutation']),
+ );
+
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ runChannel.send({ type: 'run-finished' });
+
+ await expect(generation).resolves.toEqual(RESULT);
+ });
+
+ it('follows the run and starts it with the same caller token', async () => {
+ vi.stubEnv('TWENTY_APP_APPLICATION_ACCESS_TOKEN', 'application-token');
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({ input: 'Hi', onChunk: () => {} });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ runChannel.send({ type: 'run-finished' });
+
+ await expect(generation).resolves.toEqual(RESULT);
+ expect(
+ fetchSpy.mock.calls.map(([, requestInit]) =>
+ new Headers(requestInit?.headers).get('Authorization'),
+ ),
+ ).toEqual(['Bearer app-token', 'Bearer app-token']);
+ });
+
+ it('closes the stream and rejects when aborted during the run', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const abortController = new AbortController();
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: () => {},
+ signal: abortController.signal,
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ abortController.abort();
+
+ await expect(generation).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetchSpy.mock.calls[0][1]?.signal?.aborted).toBe(true);
+ });
+
+ it('rejects when aborted after the mutation returned but before the last chunk', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const abortController = new AbortController();
+ const chunks: Record<string, unknown>[] = [];
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: (chunk) => {
+ chunks.push(chunk);
+ },
+ signal: abortController.signal,
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ runChannel.send({ type: 'stream-chunk', chunk: { type: 'start' }, seq: 1 });
+ await vi.waitFor(() => expect(chunks).toHaveLength(1));
+ abortController.abort();
+
+ await expect(generation).rejects.toMatchObject({ name: 'AbortError' });
+ });
+
+ it('rejects when aborted while onChunk is still running after the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const abortController = new AbortController();
+ let isOnChunkCalled = false;
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: () => {
+ isOnChunkCalled = true;
+
+ return new Promise(() => {});
+ },
+ signal: abortController.signal,
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ runChannel.send({ type: 'stream-chunk', chunk: { type: 'start' }, seq: 1 });
+ runChannel.send({ type: 'run-finished' });
+ await vi.waitFor(() => expect(isOnChunkCalled).toBe(true));
+ abortController.abort();
+
+ await expect(generation).rejects.toMatchObject({ name: 'AbortError' });
+ });
+
+ it('does not connect once its signal is aborted', async () => {
+ await expect(
+ ai.generate({
+ input: 'Hi',
+ onChunk: () => {},
+ signal: AbortSignal.abort(),
+ }),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('resolves with the result when the end event never arrives', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({ input: 'Hi', onChunk: () => {} });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ await expect(generation).resolves.toEqual(RESULT);
+ expect(fetchSpy.mock.calls[0][1]?.signal?.aborted).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('delivers every chunk to a slow onChunk, however long after the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const chunks: Record<string, unknown>[] = [];
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: async (chunk) => {
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ chunks.push(chunk);
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ for (const sequence of [1, 2, 3, 4, 5]) {
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta', id: 'text-1', delta: `${sequence}` },
+ seq: sequence,
+ });
+ }
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ runChannel.send({ type: 'run-finished' });
+
+ await vi.advanceTimersByTimeAsync(10_000);
+
+ await expect(generation).resolves.toEqual(RESULT);
+ expect(chunks.map(({ delta }) => delta)).toEqual([
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('delivers the chunks received before a lost end event, then stops after a quiet grace', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const chunks: Record<string, unknown>[] = [];
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: async (chunk) => {
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ chunks.push(chunk);
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ for (const sequence of [1, 2, 3, 4, 5]) {
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta', id: 'text-1', delta: `${sequence}` },
+ seq: sequence,
+ });
+ }
+ runChannel.answerMutation({ data: { generate: RESULT } });
+
+ await vi.advanceTimersByTimeAsync(10_000);
+
+ expect(chunks).toHaveLength(5);
+ expect(fetchSpy.mock.calls[0][1]?.signal?.aborted).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ expect(fetchSpy.mock.calls[0][1]?.signal?.aborted).toBe(true);
+ await expect(generation).resolves.toEqual(RESULT);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stops after the quiet grace even while keepalives keep coming', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ let isSettled = false;
+
+ const generation = ai
+ .generate({ input: 'Hi', onChunk: () => {} })
+ .finally(() => {
+ isSettled = true;
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ runChannel.answerMutation({ data: { generate: RESULT } });
+
+ for (const _second of [1, 2, 3, 4]) {
+ runChannel.send({ type: 'keepalive' });
+ await vi.advanceTimersByTimeAsync(1_000);
+ }
+
+ await vi.advanceTimersByTimeAsync(1_500);
+
+ expect(isSettled).toBe(true);
+ await expect(generation).resolves.toEqual(RESULT);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('never runs a slow onChunk concurrently, and keeps the chunk order', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const deliveredDeltas: unknown[] = [];
+ let runningCount = 0;
+ let maxRunningCount = 0;
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: async (chunk) => {
+ runningCount += 1;
+ maxRunningCount = Math.max(maxRunningCount, runningCount);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ deliveredDeltas.push(chunk.type === 'text-delta' ? chunk.delta : null);
+ runningCount -= 1;
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+
+ for (const sequence of [1, 2, 3, 4]) {
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta', id: 'text-1', delta: `${sequence}` },
+ seq: sequence,
+ });
+ }
+ runChannel.send({ type: 'run-finished' });
+ runChannel.answerMutation({ data: { generate: RESULT } });
+
+ await expect(generation).resolves.toEqual(RESULT);
+ expect(maxRunningCount).toBe(1);
+ expect(deliveredDeltas).toEqual(['1', '2', '3', '4']);
+ });
+
+ it('resolves with the result and the chunks it received when the channel fails after the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const chunks: Record<string, unknown>[] = [];
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: (chunk) => {
+ chunks.push(chunk);
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.send({ type: 'stream-chunk', chunk: { type: 'start' }, seq: 1 });
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ runChannel.fail();
+
+ await expect(generation).resolves.toEqual(RESULT);
+ expect(chunks).toEqual([{ type: 'start' }]);
+ });
+
+ it('still returns the billed result when the channel fails before it', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({ input: 'Hi', onChunk: () => {} });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.fail();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ runChannel.answerMutation({ data: { generate: RESULT } });
+
+ await expect(generation).resolves.toEqual(RESULT);
+ });
+
+ it('rejects when onChunk throws after the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: () => {
+ throw new Error('Could not render the chunk');
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.answerMutation({ data: { generate: RESULT } });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ runChannel.send({ type: 'stream-chunk', chunk: { type: 'start' }, seq: 1 });
+
+ await expect(generation).rejects.toThrow('Could not render the chunk');
+ });
+
+ it('rejects at once when onChunk throws, without waiting for the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: () => {
+ throw new Error('Could not render the chunk');
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.send({ type: 'stream-chunk', chunk: { type: 'start' }, seq: 1 });
+
+ await expect(generation).rejects.toThrow('Could not render the chunk');
+ expect(fetchSpy.mock.calls[1][1]?.signal?.aborted).toBe(true);
+ });
+
+ it('leaves no rejection unhandled when onChunk throws before the result', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+ const unhandledRejections: unknown[] = [];
+ const recordUnhandledRejection = (reason: unknown) =>
+ unhandledRejections.push(reason);
+
+ process.on('unhandledRejection', recordUnhandledRejection);
+
+ try {
+ const generation = ai.generate({
+ input: 'Hi',
+ onChunk: () => {
+ throw new Error('Could not render the chunk');
+ },
+ });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.send({
+ type: 'stream-chunk',
+ chunk: { type: 'start' },
+ seq: 1,
+ });
+
+ await expect(generation).rejects.toThrow('Could not render the chunk');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ expect(unhandledRejections).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', recordUnhandledRejection);
+ }
+ });
+
+ it('stops following the run when the mutation fails', async () => {
+ const runChannel = mockRunChannel({ fetchSpy });
+
+ const generation = ai.generate({ input: 'Hi', onChunk: () => {} });
+
+ await vi.waitFor(() => expect(runChannel.requests).toHaveLength(2));
+ runChannel.answerMutation({
+ errors: [{ message: 'Run already exists; pass a new runId' }],
+ });
+
+ await expect(generation).rejects.toThrow(
+ 'ai.generate() failed: Run already exists; pass a new runId',
+ );
+ expect(fetchSpy.mock.calls[0][1]?.signal?.aborted).toBe(true);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/ai/ai.ts b/packages/twenty-sdk/src/sdk/logic-function/ai/ai.ts
new file mode 100644
index 00000000000..0be1dc4f6cb
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/ai/ai.ts
@@ -0,0 +1,226 @@
+import { isString } from '@sniptt/guards';
+import {
+ type AgentResponseFormat,
+ type AiRunScope,
+ isAgentChatTurnEndEvent,
+} from 'twenty-shared/ai';
+import {
+ type GenerateResult,
+ type RunAgentMessage,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+import { streamAgentChatEvents } from '@/sdk/logic-function/utils/stream-agent-chat-events.util';
+import { toRunAgentMessages } from '@/sdk/logic-function/utils/to-run-agent-messages.util';
+
+const GENERATE_MUTATION = `
+ mutation Generate($input: GenerateInput!) {
+ generate(input: $input) {
+ success
+ text
+ object
+ error
+ runId
+ usage {
+ inputTokens
+ outputTokens
+ }
+ }
+ }
+`;
+
+// an AI SDK UIMessageChunk, typed without the ai package
+export type GenerateChunk = { type: string } & Record<string, unknown>;
+
+export type GenerateInput = {
+ // a string is sent as one user message
+ input: string | RunAgentMessage[];
+ instructions?: string | null;
+ // the workspace default model when unset
+ modelId?: string | null;
+ responseFormat?: AgentResponseFormat | null;
+ // no data tools when unset
+ scope?: AiRunScope | null;
+ onChunk?: (chunk: GenerateChunk) => void | Promise<void>;
+ signal?: AbortSignal;
+};
+
+const ON_AGENT_RUN_EVENT_SUBSCRIPTION = `
+ subscription OnAgentRunEvent($runId: UUID!) {
+ onAgentChatEvent(runId: $runId) {
+ event
+ }
+ }
+`;
+
+const END_EVENT_GRACE_MS = 5_000;
+
+type GenerateVariables = {
+ input: Omit<GenerateInput, 'input' | 'onChunk' | 'signal'> & {
+ input: RunAgentMessage[];
+ runId?: string;
+ };
+};
+
+const requestGenerate = async ({
+ variables,
+ signal,
+}: {
+ variables: GenerateVariables;
+ signal: AbortSignal | undefined;
+}): Promise<GenerateResult> => {
+ const { generate: result } = await postGraphqlRequest<
+ GenerateVariables,
+ { generate: GenerateResult }
+ >({
+ query: GENERATE_MUTATION,
+ variables,
+ caller: 'ai.generate',
+ signal,
+ isActingAsCaller: true,
+ });
+
+ return result;
+};
+
+// the run channel carries the AI SDK's own chunks, so one that names its type is taken as one
+const isGenerateChunk = (
+ chunk: Record<string, unknown>,
+): chunk is GenerateChunk => isString(chunk.type);
+
+// resolves undefined once the result is in and no event came for the grace, so a lost end event stops the wait
+const waitForQuietAfterResult = (generated: Promise<GenerateResult>) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let isWaiting = true;
+ const quiet = new Promise<undefined>((resolve) => {
+ void generated.then(
+ () => {
+ if (isWaiting) {
+ timer = setTimeout(() => resolve(undefined), END_EVENT_GRACE_MS);
+ }
+ },
+ () => undefined,
+ );
+ });
+
+ return {
+ quiet,
+ stop: () => {
+ isWaiting = false;
+ clearTimeout(timer);
+ },
+ };
+};
+
+// Starts the run once its channel is live (the first keepalive), and reads the channel no faster than onChunk
+// takes its chunks. The run is billed whatever happens to the channel, so a failing channel only stops the reading
+const generateWithChunks = async ({
+ variables,
+ onChunk,
+ signal,
+}: {
+ variables: GenerateVariables;
+ onChunk: NonNullable<GenerateInput['onChunk']>;
+ signal: AbortSignal | undefined;
+}): Promise<GenerateResult> => {
+ const runId = crypto.randomUUID();
+ const stopFollowing = new AbortController();
+ const runSignal = isDefined(signal)
+ ? AbortSignal.any([signal, stopFollowing.signal])
+ : stopFollowing.signal;
+ // settles the call on abort even while an onChunk is still running
+ const callerAborted = new Promise<never>((_resolve, reject) =>
+ signal?.addEventListener('abort', () => reject(signal.reason), {
+ once: true,
+ signal: stopFollowing.signal,
+ }),
+ );
+
+ void callerAborted.catch(() => undefined);
+
+ try {
+ const events = streamAgentChatEvents({
+ query: ON_AGENT_RUN_EVENT_SUBSCRIPTION,
+ variables: { runId },
+ caller: 'ai.generate',
+ signal: runSignal,
+ // the same token as the mutation, so both reach the run as one caller
+ isActingAsCaller: true,
+ });
+
+ if ((await events.next()).done) {
+ signal?.throwIfAborted();
+
+ throw new Error('ai.generate() failed: the stream ended before the run');
+ }
+
+ const generated = requestGenerate({
+ variables: { input: { ...variables.input, runId } },
+ signal: runSignal,
+ });
+
+ const deliverChunks = async () => {
+ // only a chunk restarts the grace, since keepalives keep coming after the result
+ let wait = waitForQuietAfterResult(generated);
+
+ try {
+ for (;;) {
+ const next = await Promise.race([events.next(), wait.quiet]).catch(
+ () => undefined,
+ );
+
+ if (
+ !isDefined(next) ||
+ next.done ||
+ runSignal.aborted ||
+ isAgentChatTurnEndEvent(next.value)
+ ) {
+ return;
+ }
+
+ if (
+ next.value.type === 'stream-chunk' &&
+ isGenerateChunk(next.value.chunk)
+ ) {
+ wait.stop();
+ await onChunk(next.value.chunk);
+ wait = waitForQuietAfterResult(generated);
+ }
+ }
+ } finally {
+ wait.stop();
+ // a read left pending settles once following stops, so the channel closes without waiting on it
+ void events.return(undefined).catch(() => undefined);
+ }
+ };
+
+ const [result] = await Promise.race([
+ Promise.all([generated, deliverChunks()]),
+ callerAborted,
+ ]);
+
+ // the reader ends quietly on abort, so an abort after the result would read as a full delivery
+ signal?.throwIfAborted();
+
+ return result;
+ } finally {
+ stopFollowing.abort();
+ }
+};
+
+export const ai = {
+ // runs as the function's caller, like the default clients; with no scope it gets no data tools, and a scope only narrows the caller
+ generate: async ({
+ input,
+ onChunk,
+ signal,
+ ...rest
+ }: GenerateInput): Promise<GenerateResult> => {
+ const variables = { input: { ...rest, input: toRunAgentMessages(input) } };
+
+ return isDefined(onChunk)
+ ? generateWithChunks({ variables, onChunk, signal })
+ : requestGenerate({ variables, signal });
+ },
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index 8c85e1df44f..ddadefa1e12 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -83,6 +83,20 @@ export type { AppMessageFolder } from '@/sdk/logic-function/messaging/types/app-
export { runAgent } from '@/sdk/logic-function/agents/run-agent';
export type { RunAgentInput, RunAgentResult } from 'twenty-shared/application';
+export { listConversationMessages } from '@/sdk/logic-function/agents/list-conversation-messages';
+export { streamConversation } from '@/sdk/logic-function/agents/stream-conversation';
+export type { StreamConversationInput } from '@/sdk/logic-function/agents/stream-conversation';
+export type {
+ AgentConversationHistory,
+ AgentConversationInput,
+ AgentConversationMessage,
+} from '@/sdk/logic-function/agents/types/agent-conversation.type';
+export type { AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+export { isAgentChatTurnEndEvent } from 'twenty-shared/ai';
+
+export { ai, type GenerateInput } from '@/sdk/logic-function/ai/ai';
+export type { GenerateResult } from 'twenty-shared/application';
+export type { AiRunScope } from 'twenty-shared/ai';
export { sendInboxMessage } from '@/sdk/inbox/send-inbox-message';
export { inboxMention } from '@/sdk/inbox/mentions/inbox-mention';
diff --git a/packages/twenty-sdk/src/sdk/logic-function/utils/get-application-api-config-or-throw.util.ts b/packages/twenty-sdk/src/sdk/logic-function/utils/get-application-api-config-or-throw.util.ts
new file mode 100644
index 00000000000..b6bba134e0e
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/utils/get-application-api-config-or-throw.util.ts
@@ -0,0 +1,34 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ DEFAULT_API_URL_NAME,
+ DEFAULT_APP_ACCESS_TOKEN_NAME,
+ DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
+} from 'twenty-shared/application-runtime';
+
+import {
+ getApplicationAccessToken,
+ getCallerAccessToken,
+} from '@/sdk/utils/get-application-access-token';
+
+export const getApplicationApiConfigOrThrow = ({
+ caller,
+ isActingAsCaller = false,
+}: {
+ caller: string;
+ isActingAsCaller?: boolean;
+}): { apiUrl: string; accessToken: string } => {
+ const apiUrl = process.env[DEFAULT_API_URL_NAME];
+ const accessToken = isActingAsCaller
+ ? getCallerAccessToken()
+ : getApplicationAccessToken();
+
+ if (!isNonEmptyString(apiUrl) || !isNonEmptyString(accessToken)) {
+ throw new Error(
+ `${caller}() requires the app runtime env vars ` +
+ `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME} ` +
+ `(or ${DEFAULT_APP_ACCESS_TOKEN_NAME}).`,
+ );
+ }
+
+ return { apiUrl, accessToken };
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts b/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
index b23aeea12a8..5c089938adb 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/utils/post-graphql-request.util.ts
@@ -1,28 +1,22 @@
-import {
- DEFAULT_API_URL_NAME,
- DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
-} from 'twenty-shared/application-runtime';
-
-import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
+import { getApplicationApiConfigOrThrow } from '@/sdk/logic-function/utils/get-application-api-config-or-throw.util';
export const postGraphqlRequest = async <TVariables, TData>({
query,
variables,
caller,
+ signal,
+ isActingAsCaller = false,
}: {
query: string;
variables: TVariables;
caller: string;
+ signal?: AbortSignal;
+ isActingAsCaller?: boolean;
}): Promise<TData> => {
- const apiUrl = process.env[DEFAULT_API_URL_NAME];
- const accessToken = getApplicationAccessToken();
-
- if (!apiUrl || !accessToken) {
- throw new Error(
- `${caller}() requires the app runtime env vars ` +
- `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME}.`,
- );
- }
+ const { apiUrl, accessToken } = getApplicationApiConfigOrThrow({
+ caller,
+ isActingAsCaller,
+ });
const response = await fetch(`${apiUrl}/metadata`, {
method: 'POST',
@@ -31,6 +25,7 @@ export const postGraphqlRequest = async <TVariables, TData>({
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ query, variables }),
+ signal,
});
if (!response.ok) {
diff --git a/packages/twenty-sdk/src/sdk/logic-function/utils/stream-agent-chat-events.util.ts b/packages/twenty-sdk/src/sdk/logic-function/utils/stream-agent-chat-events.util.ts
new file mode 100644
index 00000000000..6d53f73fb34
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/utils/stream-agent-chat-events.util.ts
@@ -0,0 +1,182 @@
+import { isArray, isNonEmptyString, isObject, isString } from '@sniptt/guards';
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getApplicationApiConfigOrThrow } from '@/sdk/logic-function/utils/get-application-api-config-or-throw.util';
+
+type ServerSentEvent =
+ | { type: 'complete' }
+ | { type: 'errors'; messages: string[] }
+ | { type: 'event'; event: AgentChatSubscriptionEvent }
+ | null;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ isObject(value) && !isArray(value);
+
+const toErrorMessages = (errors: unknown[]): string[] =>
+ errors.map((error) =>
+ isRecord(error) && isString(error.message)
+ ? error.message
+ : JSON.stringify(error),
+ );
+
+// only the type is checked, so a field a newer server adds never fails an older SDK
+const isAgentChatSubscriptionEvent = (
+ event: unknown,
+): event is AgentChatSubscriptionEvent =>
+ isRecord(event) && isString(event.type);
+
+// GraphQL over server-sent events: one `next` event per result, then `complete`
+const parseServerSentEventOrThrow = ({
+ block,
+ caller,
+}: {
+ block: string;
+ caller: string;
+}): ServerSentEvent => {
+ const lines = block.split('\n');
+
+ if (lines.includes('event: complete')) {
+ return { type: 'complete' };
+ }
+
+ const data = lines
+ .filter((line) => line.startsWith('data:'))
+ .map((line) => line.slice('data:'.length).trimStart())
+ .join('\n');
+
+ if (!isNonEmptyString(data)) {
+ return null;
+ }
+
+ const result: unknown = JSON.parse(data);
+
+ if (!isRecord(result)) {
+ throw new Error(`${caller}() failed: unexpected result ${data}`);
+ }
+
+ // isNonEmptyArray would inline twenty-shared's utils chunk into every logic function
+ if (isArray(result.errors)) {
+ return { type: 'errors', messages: toErrorMessages(result.errors) };
+ }
+
+ const event =
+ isRecord(result.data) && isRecord(result.data.onAgentChatEvent)
+ ? result.data.onAgentChatEvent.event
+ : undefined;
+
+ if (!isAgentChatSubscriptionEvent(event)) {
+ throw new Error(`${caller}() failed: unexpected result ${data}`);
+ }
+
+ return { type: 'event', event };
+};
+
+const readFailedResponseMessage = async (response: Response) => {
+ const body: unknown = await response.json().catch(() => undefined);
+
+ if (isRecord(body) && isArray(body.errors)) {
+ return toErrorMessages(body.errors).join(', ');
+ }
+
+ return `HTTP ${response.status} ${response.statusText}`;
+};
+
+// yields the events of an onAgentChatEvent subscription; an abort ends it quietly, a dropped connection throws
+export async function* streamAgentChatEvents({
+ query,
+ variables,
+ caller,
+ signal,
+ closedEarlyAdvice = '',
+ isActingAsCaller = false,
+}: {
+ query: string;
+ variables: Record<string, unknown>;
+ caller: string;
+ signal?: AbortSignal;
+ isActingAsCaller?: boolean;
+ // appended to the error a dropped connection throws, for callers that can resume
+ closedEarlyAdvice?: string;
+}): AsyncGenerator<AgentChatSubscriptionEvent> {
+ const { apiUrl, accessToken } = getApplicationApiConfigOrThrow({
+ caller,
+ isActingAsCaller,
+ });
+ let reader: ReadableStreamDefaultReader<string> | undefined;
+
+ if (signal?.aborted) {
+ return;
+ }
+
+ try {
+ const response = await fetch(`${apiUrl}/metadata`, {
+ method: 'POST',
+ headers: {
+ Accept: 'text/event-stream',
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${accessToken}`,
+ },
+ body: JSON.stringify({ query, variables }),
+ signal,
+ });
+
+ if (!response.ok || !isDefined(response.body)) {
+ throw new Error(
+ `${caller}() failed: ${await readFailedResponseMessage(response)}`,
+ );
+ }
+
+ reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
+ let buffer = '';
+
+ while (true) {
+ const { done, value } = await reader.read();
+
+ // the server completes every stream it ends, so this is a dropped connection
+ if (done) {
+ throw new Error(
+ `${caller}() failed: the stream closed early${closedEarlyAdvice}`,
+ );
+ }
+
+ // a CRLF can be split across two reads
+ buffer = (buffer + value).replace(/\r\n/g, '\n');
+
+ let boundary = buffer.indexOf('\n\n');
+
+ while (boundary !== -1) {
+ const serverSentEvent = parseServerSentEventOrThrow({
+ block: buffer.slice(0, boundary),
+ caller,
+ });
+
+ buffer = buffer.slice(boundary + 2);
+ boundary = buffer.indexOf('\n\n');
+
+ if (serverSentEvent?.type === 'complete') {
+ return;
+ }
+
+ if (serverSentEvent?.type === 'errors') {
+ throw new Error(
+ `${caller}() failed: ${serverSentEvent.messages.join(', ')}`,
+ );
+ }
+
+ if (serverSentEvent?.type === 'event') {
+ yield serverSentEvent.event;
+ }
+ }
+ }
+ } catch (error) {
+ // an abort rejects with the signal's reason, which is not always an AbortError
+ if (signal?.aborted) {
+ return;
+ }
+
+ throw error;
+ } finally {
+ await reader?.cancel().catch(() => {});
+ }
+}
diff --git a/packages/twenty-sdk/src/sdk/logic-function/utils/to-run-agent-messages.util.ts b/packages/twenty-sdk/src/sdk/logic-function/utils/to-run-agent-messages.util.ts
new file mode 100644
index 00000000000..4634651324c
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/utils/to-run-agent-messages.util.ts
@@ -0,0 +1,7 @@
+import { isString } from '@sniptt/guards';
+import { type RunAgentMessage } from 'twenty-shared/application';
+
+export const toRunAgentMessages = (
+ input: string | RunAgentMessage[],
+): RunAgentMessage[] =>
+ isString(input) ? [{ role: 'user', content: input }] : input;
diff --git a/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts b/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts
index 6540a3d87db..5705393ba9c 100644
--- a/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts
+++ b/packages/twenty-sdk/src/sdk/utils/__tests__/get-application-access-token.test.ts
@@ -1,20 +1,25 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
+import {
+ getApplicationAccessToken,
+ getCallerAccessToken,
+} from '@/sdk/utils/get-application-access-token';
-describe('getApplicationAccessToken', () => {
- const initialEnvironment = process.env;
+const initialEnvironment = process.env;
- beforeEach(() => {
- process.env = { ...initialEnvironment };
- delete process.env.TWENTY_APP_ACCESS_TOKEN;
- delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
- });
+beforeEach(() => {
+ process.env = {
+ ...initialEnvironment,
+ TWENTY_APP_ACCESS_TOKEN: undefined,
+ TWENTY_APP_APPLICATION_ACCESS_TOKEN: undefined,
+ };
+});
- afterEach(() => {
- process.env = initialEnvironment;
- });
+afterEach(() => {
+ process.env = initialEnvironment;
+});
+describe('getApplicationAccessToken', () => {
it('should prefer the application token over the delegated one', () => {
process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application';
process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated';
@@ -38,3 +43,22 @@ describe('getApplicationAccessToken', () => {
expect(getApplicationAccessToken()).toBeUndefined();
});
});
+
+describe('getCallerAccessToken', () => {
+ it('should prefer the delegated token over the application one', () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application';
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'delegated';
+
+ expect(getCallerAccessToken()).toBe('delegated');
+ });
+
+ it('should fall back to the application token in a run nobody triggered', () => {
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application';
+
+ expect(getCallerAccessToken()).toBe('application');
+ });
+
+ it('should return undefined outside the app runtime', () => {
+ expect(getCallerAccessToken()).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
index bbce37ee857..2d1aabb1a86 100644
--- a/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
+++ b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
@@ -7,3 +7,8 @@ import {
export const getApplicationAccessToken = (): string | undefined =>
process.env[DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME] ??
process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
+
+// acts as whoever triggered the run, like the client SDK's default runAs
+export const getCallerAccessToken = (): string | undefined =>
+ process.env[DEFAULT_APP_ACCESS_TOKEN_NAME] ??
+ process.env[DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME];
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-upgrade-version-command.module.ts
index 4c13a94320d..9b9b7bc53ba 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-upgrade-version-command.module.ts
@@ -3,9 +3,12 @@ import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
import { AddDirectMessagePairIdentityCommand } from 'src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793639083811-add-direct-message-pair-identity.command';
import { EnableDirectMessagePairIdentityCommand } from 'src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793639083813-enable-direct-message-pair-identity.command';
+import { MakeAgentTurnThreadOptionalCommand } from 'src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418663-make-agent-turn-thread-optional.command';
+import { InlineWorkflowStepAgentsCommand } from 'src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418665-inline-workflow-step-agents.command';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@Module({
@@ -15,10 +18,13 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
WorkspaceCacheModule,
WorkspaceIteratorModule,
WorkspaceMigrationModule,
+ WorkspaceMigrationRunnerModule,
],
providers: [
AddDirectMessagePairIdentityCommand,
EnableDirectMessagePairIdentityCommand,
+ MakeAgentTurnThreadOptionalCommand,
+ InlineWorkflowStepAgentsCommand,
],
})
export class V2_56_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418663-make-agent-turn-thread-optional.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418663-make-agent-turn-thread-optional.command.ts
new file mode 100644
index 00000000000..9b4ca6dafc9
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418663-make-agent-turn-thread-optional.command.ts
@@ -0,0 +1,68 @@
+import { Command } from 'nest-commander';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { WorkspaceMigrationRunnerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/services/workspace-migration-runner.service';
+
+@RegisteredWorkspaceCommand('2.56.0', 1793697418663)
+@Command({
+ name: 'upgrade:2-56:make-agent-turn-thread-optional',
+ description:
+ 'Let a one-shot AI run record its turn without a conversation thread',
+})
+export class MakeAgentTurnThreadOptionalCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceMigrationRunnerService: WorkspaceMigrationRunnerService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ dataSource,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ if (!isDefined(dataSource) || options.dryRun) {
+ return;
+ }
+
+ const schema = getWorkspaceSchemaName(workspaceId);
+ const [table] = await dataSource.query('SELECT to_regclass($1) AS name', [
+ `"${schema}"."agentTurn"`,
+ ]);
+
+ if (!isDefined(table?.name)) {
+ this.logger.log(
+ `Agent turn table absent in workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ await dataSource.query(
+ `ALTER TABLE "${schema}"."agentTurn" ALTER COLUMN "threadId" DROP NOT NULL`,
+ );
+ await dataSource.query(
+ `UPDATE core."fieldMetadata" field
+ SET "isNullable" = true
+ FROM core."objectMetadata" object
+ WHERE field."objectMetadataId" = object.id
+ AND object."workspaceId" = $1
+ AND object."nameSingular" = 'agentTurn'
+ AND field.name = 'thread'`,
+ [workspaceId],
+ );
+ await this.workspaceMigrationRunnerService.invalidateCache({
+ allFlatEntityMapsKeys: [
+ 'flatFieldMetadataMaps',
+ 'flatObjectMetadataMaps',
+ ],
+ workspaceId,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418665-inline-workflow-step-agents.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418665-inline-workflow-step-agents.command.ts
new file mode 100644
index 00000000000..b3496107e03
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418665-inline-workflow-step-agents.command.ts
@@ -0,0 +1,354 @@
+import { Command } from 'nest-commander';
+import {
+ type AgentResponseFormat,
+ type AiRunScope,
+ type ModelConfiguration,
+} from 'twenty-shared/ai';
+import { type RolePermissionGrants } from 'twenty-shared/application';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+import { type DataSource } from 'typeorm';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import {
+ buildAiRunScopeFromStepAgentRole,
+ type StoredFieldPermissionRow,
+ type StoredObjectPermissionRow,
+} from 'src/database/commands/upgrade-version-command/2-56/utils/build-ai-run-scope-from-step-agent-role.util';
+import { inlineWorkflowStepAgents } from 'src/database/commands/upgrade-version-command/2-56/utils/inline-workflow-step-agents.util';
+import {
+ type StepAgentInlineConfig,
+ type StoredWorkflowStep,
+} from 'src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type';
+import { rewriteJsonbRowsWithCompareAndSet } from 'src/database/commands/upgrade-version-command/2-56/utils/rewrite-jsonb-rows-with-compare-and-set.util';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
+
+type StepAgentRow = {
+ id: string;
+ prompt: string;
+ modelId: string;
+ modelConfiguration: ModelConfiguration | null;
+ responseFormat: AgentResponseFormat | null;
+ roleId: string | null;
+ isActive: boolean;
+};
+
+type StepAgentRoleRow = Required<
+ Pick<RolePermissionGrants, 'canUpdateAllSettings' | 'canAccessAllTools'>
+> & {
+ id: string;
+ hasRowLevelPermissionPredicates: boolean;
+};
+
+type StepAgents = {
+ inlineConfigByAgentId: Map<string, StepAgentInlineConfig>;
+ keptAgentIds: Set<string>;
+};
+
+// in-flight runs keep their agent, which the runtime still runs by agentId,
+// so the later deletion command must skip agents still referenced by runnable runs
+@RegisteredWorkspaceCommand('2.56.0', 1793697418665)
+@Command({
+ name: 'upgrade:2-56:inline-workflow-step-agents',
+ description:
+ 'Move the prompt, model and permissions of the hidden agent behind each AI workflow step into the step',
+})
+export class InlineWorkflowStepAgentsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace({
+ workspaceId,
+ options,
+ dataSource,
+ }: RunOnWorkspaceArgs): Promise<void> {
+ if (!isDefined(dataSource)) {
+ this.logger.warn(
+ `No data source for workspace ${workspaceId}, skipping workflow step agents`,
+ );
+
+ return;
+ }
+
+ const isDryRun = options.dryRun ?? false;
+ const stepAgents = await this.loadStepAgents({ dataSource, workspaceId });
+
+ if (
+ stepAgents.inlineConfigByAgentId.size === 0 &&
+ stepAgents.keptAgentIds.size === 0
+ ) {
+ return;
+ }
+
+ const keptStepAgentIds = new Set<string>();
+ const inlineSteps = ({ value }: { value: StoredWorkflowStep[] }) => {
+ const result = inlineWorkflowStepAgents({
+ steps: value,
+ inlineConfigByAgentId: stepAgents.inlineConfigByAgentId,
+ keptAgentIds: stepAgents.keptAgentIds,
+ });
+
+ result.keptStepAgentIds.forEach((agentId) =>
+ keptStepAgentIds.add(agentId),
+ );
+
+ return { value: result.steps, hasChanged: result.hasChanged };
+ };
+
+ const coreWorkflowVersionCount = await rewriteJsonbRowsWithCompareAndSet({
+ dataSource,
+ isDryRun,
+ tableName: 'core."workflowVersion"',
+ columnName: 'steps',
+ whereClause: `"workspaceId" = $1 AND steps @> '[{"type":"AI_AGENT"}]'`,
+ whereParameters: [workspaceId],
+ mapRow: inlineSteps,
+ });
+
+ const workflowVersionTable = await this.findWorkflowVersionTable({
+ dataSource,
+ workspaceId,
+ });
+ const workflowVersionCount = isDefined(workflowVersionTable)
+ ? await rewriteJsonbRowsWithCompareAndSet({
+ dataSource,
+ isDryRun,
+ tableName: workflowVersionTable,
+ columnName: 'steps',
+ whereClause: `steps @> '[{"type":"AI_AGENT"}]'`,
+ whereParameters: [],
+ mapRow: inlineSteps,
+ })
+ : 0;
+
+ const visibleAgentCount = await this.makeKeptStepAgentsVisible({
+ dataSource,
+ isDryRun,
+ agentIds: [...keptStepAgentIds],
+ });
+
+ if (!isDryRun && coreWorkflowVersionCount > 0) {
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'flatWorkflowVersionMaps',
+ ]);
+ }
+
+ if (!isDryRun && visibleAgentCount > 0) {
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'flatAgentMaps',
+ ]);
+ }
+
+ this.logger.log(
+ `${isDryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId}: inlined the agents of ${coreWorkflowVersionCount} core workflow version(s) and ${workflowVersionCount} workflow version(s), and made ${visibleAgentCount} kept step agent(s) visible`,
+ );
+ }
+
+ private async loadStepAgents({
+ dataSource,
+ workspaceId,
+ }: {
+ dataSource: DataSource;
+ workspaceId: string;
+ }): Promise<StepAgents> {
+ const [{ workspaceCustomApplicationId }]: {
+ workspaceCustomApplicationId: string | null;
+ }[] = await dataSource.query(
+ `SELECT "workspaceCustomApplicationId" FROM core."workspace" WHERE id = $1`,
+ [workspaceId],
+ );
+
+ // only builder steps create system agents in the custom application; an installed app's are its own
+ const agentRows: StepAgentRow[] = await dataSource.query(
+ `SELECT agent.id, agent.prompt, agent."modelId", agent."modelConfiguration",
+ agent."responseFormat", agent."isActive", target."roleId"
+ FROM core."agent" agent
+ LEFT JOIN core."roleTarget" target ON target."agentId" = agent.id
+ WHERE agent."workspaceId" = $1
+ AND agent."isSystem" = true
+ AND agent."applicationId" = $2
+ AND agent."deletedAt" IS NULL
+ AND COALESCE(jsonb_array_length(agent.triggers), 0) = 0`,
+ [workspaceId, workspaceCustomApplicationId],
+ );
+
+ const scopeByRoleId = await this.loadRoleScopes({
+ dataSource,
+ roleIds: [
+ ...new Set(agentRows.map(({ roleId }) => roleId).filter(isDefined)),
+ ],
+ });
+
+ const stepAgents: StepAgents = {
+ inlineConfigByAgentId: new Map(),
+ keptAgentIds: new Set(),
+ };
+
+ for (const agentRow of agentRows) {
+ const scope = isDefined(agentRow.roleId)
+ ? scopeByRoleId.get(agentRow.roleId)
+ : null;
+
+ if (!agentRow.isActive || scope === undefined) {
+ stepAgents.keptAgentIds.add(agentRow.id);
+ continue;
+ }
+
+ stepAgents.inlineConfigByAgentId.set(agentRow.id, {
+ instructions: agentRow.prompt,
+ modelId: agentRow.modelId,
+ modelConfiguration: agentRow.modelConfiguration,
+ responseFormat: agentRow.responseFormat,
+ scope,
+ });
+ }
+
+ return stepAgents;
+ }
+
+ private async makeKeptStepAgentsVisible({
+ dataSource,
+ isDryRun,
+ agentIds,
+ }: {
+ dataSource: DataSource;
+ isDryRun: boolean;
+ agentIds: string[];
+ }): Promise<number> {
+ if (agentIds.length === 0 || isDryRun) {
+ return agentIds.length;
+ }
+
+ // isSystem marks the hidden step agents the deferred deletion targets
+ const [, updatedAgentCount]: [unknown, number] = await dataSource.query(
+ `UPDATE core."agent" SET "isSystem" = false WHERE id = ANY($1::uuid[])`,
+ [agentIds],
+ );
+
+ return updatedAgentCount;
+ }
+
+ // a role with row-level predicates is left out of the map, so its agents are kept
+ private async loadRoleScopes({
+ dataSource,
+ roleIds,
+ }: {
+ dataSource: DataSource;
+ roleIds: string[];
+ }): Promise<Map<string, AiRunScope>> {
+ if (roleIds.length === 0) {
+ return new Map();
+ }
+
+ const [roleRows, objectPermissionRows, fieldPermissionRows, flagRows]: [
+ StepAgentRoleRow[],
+ (StoredObjectPermissionRow & { roleId: string })[],
+ (StoredFieldPermissionRow & { roleId: string })[],
+ { roleId: string; universalIdentifier: string }[],
+ ] = await Promise.all([
+ dataSource.query(
+ `SELECT role.id, role."canUpdateAllSettings", role."canAccessAllTools",
+ EXISTS (
+ SELECT 1 FROM core."rowLevelPermissionPredicate" predicate
+ WHERE predicate."roleId" = role.id AND predicate."deletedAt" IS NULL
+ ) AS "hasRowLevelPermissionPredicates"
+ FROM core."role" role
+ WHERE role.id = ANY($1::uuid[])`,
+ [roleIds],
+ ),
+ dataSource.query(
+ `SELECT permission."roleId", object."universalIdentifier" AS "objectUniversalIdentifier",
+ permission."canReadObjectRecords", permission."canUpdateObjectRecords",
+ permission."canSoftDeleteObjectRecords", permission."canDestroyObjectRecords"
+ FROM core."objectPermission" permission
+ JOIN core."objectMetadata" object ON object.id = permission."objectMetadataId"
+ WHERE permission."roleId" = ANY($1::uuid[])`,
+ [roleIds],
+ ),
+ dataSource.query(
+ `SELECT permission."roleId", object."universalIdentifier" AS "objectUniversalIdentifier",
+ field."universalIdentifier" AS "fieldUniversalIdentifier",
+ permission."canReadFieldValue", permission."canUpdateFieldValue"
+ FROM core."fieldPermission" permission
+ JOIN core."objectMetadata" object ON object.id = permission."objectMetadataId"
+ JOIN core."fieldMetadata" field ON field.id = permission."fieldMetadataId"
+ WHERE permission."roleId" = ANY($1::uuid[])`,
+ [roleIds],
+ ),
+ dataSource.query(
+ `SELECT role_flag."roleId", flag."universalIdentifier"
+ FROM core."rolePermissionFlag" role_flag
+ JOIN core."permissionFlag" flag ON flag.id = role_flag."permissionFlagId"
+ WHERE role_flag."roleId" = ANY($1::uuid[])`,
+ [roleIds],
+ ),
+ ]);
+
+ return new Map(
+ roleRows
+ .filter(
+ ({ hasRowLevelPermissionPredicates }) =>
+ !hasRowLevelPermissionPredicates,
+ )
+ .map((role) => [
+ role.id,
+ buildAiRunScopeFromStepAgentRole({
+ canUpdateAllSettings: role.canUpdateAllSettings,
+ canAccessAllTools: role.canAccessAllTools,
+ objectPermissions: objectPermissionRows
+ .filter(({ roleId }) => roleId === role.id)
+ .map(({ roleId: _roleId, ...permission }) => permission),
+ fieldPermissions: fieldPermissionRows
+ .filter(({ roleId }) => roleId === role.id)
+ .map(({ roleId: _roleId, ...permission }) => permission),
+ permissionFlagUniversalIdentifiers: flagRows
+ .filter(({ roleId }) => roleId === role.id)
+ .map(({ universalIdentifier }) => universalIdentifier),
+ }),
+ ]),
+ );
+ }
+
+ private async findWorkflowVersionTable({
+ dataSource,
+ workspaceId,
+ }: {
+ dataSource: DataSource;
+ workspaceId: string;
+ }): Promise<string | null> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+
+ if (
+ !isDefined(
+ findFlatEntityByUniversalIdentifier({
+ flatEntityMaps: flatObjectMetadataMaps,
+ universalIdentifier:
+ STANDARD_OBJECTS.workflowVersion.universalIdentifier,
+ }),
+ )
+ ) {
+ return null;
+ }
+
+ const tableName = `${escapeIdentifier(getWorkspaceSchemaName(workspaceId))}."workflowVersion"`;
+ const [table]: { name: string | null }[] = await dataSource.query(
+ 'SELECT to_regclass($1) AS name',
+ [tableName],
+ );
+
+ return isDefined(table?.name) ? tableName : null;
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/build-ai-run-scope-from-step-agent-role.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/build-ai-run-scope-from-step-agent-role.util.spec.ts
new file mode 100644
index 00000000000..9359b9b3f27
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/build-ai-run-scope-from-step-agent-role.util.spec.ts
@@ -0,0 +1,77 @@
+import { buildAiRunScopeFromStepAgentRole } from 'src/database/commands/upgrade-version-command/2-56/utils/build-ai-run-scope-from-step-agent-role.util';
+
+const DENY_ALL_ROLE: Parameters<typeof buildAiRunScopeFromStepAgentRole>[0] = {
+ canUpdateAllSettings: false,
+ canAccessAllTools: false,
+ objectPermissions: [],
+ fieldPermissions: [],
+ permissionFlagUniversalIdentifiers: [],
+};
+
+describe('buildAiRunScopeFromStepAgentRole', () => {
+ it('gives an empty scope for a role that grants nothing', () => {
+ expect(buildAiRunScopeFromStepAgentRole(DENY_ALL_ROLE)).toEqual({});
+ });
+
+ it('keeps the object, field and flag grants of the role', () => {
+ expect(
+ buildAiRunScopeFromStepAgentRole({
+ ...DENY_ALL_ROLE,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: null,
+ canDestroyObjectRecords: null,
+ },
+ {
+ objectUniversalIdentifier: 'person',
+ canReadObjectRecords: null,
+ canUpdateObjectRecords: null,
+ canSoftDeleteObjectRecords: null,
+ canDestroyObjectRecords: null,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ canUpdateFieldValue: null,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: ['send-email', 'ai'],
+ }),
+ ).toEqual({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: ['ai', 'send-email'],
+ });
+ });
+
+ it('keeps the tools and settings grants of the role', () => {
+ expect(
+ buildAiRunScopeFromStepAgentRole({
+ ...DENY_ALL_ROLE,
+ canAccessAllTools: true,
+ canUpdateAllSettings: true,
+ }),
+ ).toEqual({
+ canAccessAllTools: true,
+ canUpdateAllSettings: true,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/inline-workflow-step-agents.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/inline-workflow-step-agents.util.spec.ts
new file mode 100644
index 00000000000..795119266d2
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/__tests__/inline-workflow-step-agents.util.spec.ts
@@ -0,0 +1,126 @@
+import { inlineWorkflowStepAgents } from 'src/database/commands/upgrade-version-command/2-56/utils/inline-workflow-step-agents.util';
+import {
+ type StepAgentInlineConfig,
+ type StoredWorkflowStep,
+} from 'src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type';
+
+const INLINE_CONFIG: StepAgentInlineConfig = {
+ instructions: 'Qualify the lead.',
+ modelId: 'auto-select',
+ modelConfiguration: { webSearch: { enabled: true } },
+ responseFormat: { type: 'text' },
+ scope: {
+ objectPermissions: [
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: true },
+ ],
+ },
+};
+
+const buildAgentStep = (
+ input: Record<string, unknown>,
+): StoredWorkflowStep => ({
+ id: 'step-id',
+ type: 'AI_AGENT',
+ name: 'Qualify',
+ settings: { input, outputSchema: {} },
+});
+
+const inline = ({
+ steps,
+ inlineConfig = INLINE_CONFIG,
+}: {
+ steps: StoredWorkflowStep[];
+ inlineConfig?: StepAgentInlineConfig;
+}) =>
+ inlineWorkflowStepAgents({
+ steps,
+ inlineConfigByAgentId: new Map([['agent-id', inlineConfig]]),
+ keptAgentIds: new Set(),
+ });
+
+describe('inlineWorkflowStepAgents', () => {
+ it("keeps the step's own response format over the agent's", () => {
+ const stepResponseFormat = {
+ type: 'json',
+ schema: { type: 'object', properties: {} },
+ };
+
+ const { steps } = inline({
+ steps: [
+ buildAgentStep({
+ agentId: 'agent-id',
+ responseFormat: stepResponseFormat,
+ }),
+ ],
+ });
+
+ expect(steps[0].settings?.input).toMatchObject({
+ responseFormat: stepResponseFormat,
+ });
+ });
+
+ it('gives a step whose agent had no role no scope', () => {
+ const { steps } = inline({
+ steps: [buildAgentStep({ agentId: 'agent-id' })],
+ inlineConfig: { ...INLINE_CONFIG, scope: null },
+ });
+
+ expect(steps[0].settings?.input).not.toHaveProperty('scope');
+ });
+
+ it('leaves other steps and agents it does not inline as they are', () => {
+ const steps = [
+ { id: 'code', type: 'CODE', settings: { input: {} } },
+ buildAgentStep({ agentId: 'installed-app-agent-id' }),
+ ];
+
+ expect(inline({ steps })).toEqual({
+ steps,
+ hasChanged: false,
+ keptStepAgentIds: [],
+ });
+ });
+
+ it('still inlines a plain step next to a conversational one', () => {
+ const conversationalStep = {
+ ...buildAgentStep({
+ agentId: 'conversational-agent-id',
+ conversation: { scope: 'RUN' },
+ }),
+ id: 'conversational-step-id',
+ };
+
+ const { steps, hasChanged, keptStepAgentIds } = inlineWorkflowStepAgents({
+ steps: [buildAgentStep({ agentId: 'agent-id' }), conversationalStep],
+ inlineConfigByAgentId: new Map([
+ ['agent-id', INLINE_CONFIG],
+ ['conversational-agent-id', INLINE_CONFIG],
+ ]),
+ keptAgentIds: new Set(),
+ });
+
+ expect(hasChanged).toBe(true);
+ expect(keptStepAgentIds).toEqual(['conversational-agent-id']);
+ expect(steps).toEqual([
+ buildAgentStep({
+ instructions: 'Qualify the lead.',
+ modelId: 'auto-select',
+ modelConfiguration: { webSearch: { enabled: true } },
+ scope: INLINE_CONFIG.scope,
+ }),
+ conversationalStep,
+ ]);
+ });
+
+ it('inlines a step whose human input instructions are blank', () => {
+ const { steps, hasChanged, keptStepAgentIds } = inline({
+ steps: [
+ buildAgentStep({ agentId: 'agent-id', humanInputInstructions: ' ' }),
+ ],
+ });
+
+ expect(hasChanged).toBe(true);
+ expect(keptStepAgentIds).toEqual([]);
+ expect(steps[0].settings?.input).not.toHaveProperty('agentId');
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/build-ai-run-scope-from-step-agent-role.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/build-ai-run-scope-from-step-agent-role.util.ts
new file mode 100644
index 00000000000..121cfbf0b9a
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/build-ai-run-scope-from-step-agent-role.util.ts
@@ -0,0 +1,82 @@
+import {
+ type AiRunScope,
+ type AiRunScopeFieldPermission,
+ type AiRunScopeObjectPermission,
+} from 'twenty-shared/ai';
+import { type RolePermissionGrants } from 'twenty-shared/application';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+// a permission column is null where a grant leaves its key out
+type StoredPermissionRow<TGrant> = {
+ [Key in keyof TGrant]-?: undefined extends TGrant[Key]
+ ? Exclude<TGrant[Key], undefined> | null
+ : TGrant[Key];
+};
+
+export type StoredObjectPermissionRow =
+ StoredPermissionRow<AiRunScopeObjectPermission>;
+
+export type StoredFieldPermissionRow =
+ StoredPermissionRow<AiRunScopeFieldPermission>;
+
+const toScopeObjectPermission = ({
+ objectUniversalIdentifier,
+ canReadObjectRecords,
+ canUpdateObjectRecords,
+ canSoftDeleteObjectRecords,
+ canDestroyObjectRecords,
+}: StoredObjectPermissionRow): AiRunScopeObjectPermission => ({
+ objectUniversalIdentifier,
+ ...(isDefined(canReadObjectRecords) ? { canReadObjectRecords } : {}),
+ ...(isDefined(canUpdateObjectRecords) ? { canUpdateObjectRecords } : {}),
+ ...(isDefined(canSoftDeleteObjectRecords)
+ ? { canSoftDeleteObjectRecords }
+ : {}),
+ ...(isDefined(canDestroyObjectRecords) ? { canDestroyObjectRecords } : {}),
+});
+
+const toScopeFieldPermission = ({
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ canReadFieldValue,
+ canUpdateFieldValue,
+}: StoredFieldPermissionRow): AiRunScopeFieldPermission => ({
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ ...(isDefined(canReadFieldValue) ? { canReadFieldValue } : {}),
+ ...(isDefined(canUpdateFieldValue) ? { canUpdateFieldValue } : {}),
+});
+
+// all-records flags stay out: before 2.56, a step agent's tools only reached the objects its role granted row by row
+export const buildAiRunScopeFromStepAgentRole = (
+ role: Pick<
+ RolePermissionGrants,
+ | 'canUpdateAllSettings'
+ | 'canAccessAllTools'
+ | 'permissionFlagUniversalIdentifiers'
+ > & {
+ objectPermissions: StoredObjectPermissionRow[];
+ fieldPermissions: StoredFieldPermissionRow[];
+ },
+): AiRunScope => {
+ const objectPermissions = role.objectPermissions
+ .map(toScopeObjectPermission)
+ .filter((objectPermission) => Object.keys(objectPermission).length > 1);
+ const fieldPermissions = role.fieldPermissions
+ .map(toScopeFieldPermission)
+ .filter((fieldPermission) => Object.keys(fieldPermission).length > 2);
+
+ return {
+ ...(role.canUpdateAllSettings ? { canUpdateAllSettings: true } : {}),
+ ...(role.canAccessAllTools ? { canAccessAllTools: true } : {}),
+ ...(isNonEmptyArray(objectPermissions) ? { objectPermissions } : {}),
+ ...(isNonEmptyArray(fieldPermissions) ? { fieldPermissions } : {}),
+ ...(isNonEmptyArray(role.permissionFlagUniversalIdentifiers)
+ ? {
+ permissionFlagUniversalIdentifiers: [
+ ...role.permissionFlagUniversalIdentifiers,
+ ].sort(),
+ }
+ : {}),
+ };
+};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/inline-workflow-step-agents.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/inline-workflow-step-agents.util.ts
new file mode 100644
index 00000000000..ea9da75b4f8
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/inline-workflow-step-agents.util.ts
@@ -0,0 +1,89 @@
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ hasWorkflowAiAgentConfig,
+ workflowAiAgentConversationConfigSchema,
+} from 'twenty-shared/workflow';
+
+import {
+ type StepAgentInlineConfig,
+ type StoredWorkflowStep,
+} from 'src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type';
+
+export const inlineWorkflowStepAgents = ({
+ steps,
+ inlineConfigByAgentId,
+ keptAgentIds,
+}: {
+ steps: StoredWorkflowStep[];
+ inlineConfigByAgentId: ReadonlyMap<string, StepAgentInlineConfig>;
+ keptAgentIds: ReadonlySet<string>;
+}): {
+ steps: StoredWorkflowStep[];
+ hasChanged: boolean;
+ keptStepAgentIds: string[];
+} => {
+ let hasChanged = false;
+ const keptStepAgentIds = new Set<string>();
+
+ const rewrittenSteps = steps.map((step) => {
+ const input = step.settings?.input;
+ const agentId = input?.agentId;
+
+ if (step.type !== 'AI_AGENT' || !isDefined(input) || !isString(agentId)) {
+ return step;
+ }
+
+ const isConversational =
+ inlineConfigByAgentId.has(agentId) &&
+ hasWorkflowAiAgentConfig(workflowAiAgentConversationConfigSchema, input);
+
+ if (isConversational || keptAgentIds.has(agentId)) {
+ keptStepAgentIds.add(agentId);
+
+ return step;
+ }
+
+ const inlineConfig = inlineConfigByAgentId.get(agentId);
+
+ if (!isDefined(inlineConfig)) {
+ return step;
+ }
+
+ hasChanged = true;
+
+ const { agentId: _agentId, responseFormat, ...rest } = input;
+ // a step without a format already gets text, so only the agent's json format is worth carrying
+ const inlinedResponseFormat =
+ !isDefined(responseFormat) && inlineConfig.responseFormat?.type === 'json'
+ ? inlineConfig.responseFormat
+ : responseFormat;
+
+ return {
+ ...step,
+ settings: {
+ ...step.settings,
+ input: {
+ ...rest,
+ instructions: inlineConfig.instructions,
+ modelId: inlineConfig.modelId,
+ ...(isDefined(inlineConfig.modelConfiguration)
+ ? { modelConfiguration: inlineConfig.modelConfiguration }
+ : {}),
+ ...(isDefined(inlineConfig.scope)
+ ? { scope: inlineConfig.scope }
+ : {}),
+ ...(isDefined(inlinedResponseFormat)
+ ? { responseFormat: inlinedResponseFormat }
+ : {}),
+ },
+ },
+ };
+ });
+
+ return {
+ steps: rewrittenSteps,
+ hasChanged,
+ keptStepAgentIds: [...keptStepAgentIds],
+ };
+};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/rewrite-jsonb-rows-with-compare-and-set.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/rewrite-jsonb-rows-with-compare-and-set.util.ts
new file mode 100644
index 00000000000..c70c71103f5
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/rewrite-jsonb-rows-with-compare-and-set.util.ts
@@ -0,0 +1,64 @@
+import { isDefined } from 'twenty-shared/utils';
+import { type DataSource } from 'typeorm';
+
+const REWRITE_BATCH_SIZE = 100;
+
+export type StoredJsonbRow<TValue> = { id: string; value: TValue };
+
+export const rewriteJsonbRowsWithCompareAndSet = async <TValue>({
+ dataSource,
+ isDryRun,
+ tableName,
+ columnName,
+ whereClause,
+ whereParameters,
+ mapRow,
+}: {
+ dataSource: DataSource;
+ isDryRun: boolean;
+ tableName: string;
+ columnName: string;
+ whereClause: string;
+ whereParameters: unknown[];
+ mapRow: (row: StoredJsonbRow<TValue>) => {
+ value: TValue;
+ hasChanged: boolean;
+ };
+}): Promise<number> => {
+ let rewrittenRowCount = 0;
+ let afterRowId: string | undefined;
+
+ while (true) {
+ const parameters = isDefined(afterRowId)
+ ? [...whereParameters, afterRowId]
+ : whereParameters;
+
+ const rows: StoredJsonbRow<TValue>[] = await dataSource.query(
+ `SELECT id, ${columnName} AS value FROM ${tableName} WHERE (${whereClause})${isDefined(afterRowId) ? ` AND id > $${parameters.length}` : ''} ORDER BY id LIMIT ${REWRITE_BATCH_SIZE}`,
+ parameters,
+ );
+
+ const rewrites = rows.flatMap((row) => {
+ const { value, hasChanged } = mapRow(row);
+
+ return hasChanged ? [{ id: row.id, from: row.value, to: value }] : [];
+ });
+
+ if (isDryRun) {
+ rewrittenRowCount += rewrites.length;
+ } else if (rewrites.length > 0) {
+ const [, updatedRowCount]: [unknown, number] = await dataSource.query(
+ `UPDATE ${tableName} AS target SET ${columnName} = rewrite."to" FROM jsonb_to_recordset($1::jsonb) AS rewrite(id uuid, "from" jsonb, "to" jsonb) WHERE target.id = rewrite.id AND target.${columnName} = rewrite."from"`,
+ [JSON.stringify(rewrites)],
+ );
+
+ rewrittenRowCount += updatedRowCount;
+ }
+
+ if (rows.length < REWRITE_BATCH_SIZE) {
+ return rewrittenRowCount;
+ }
+
+ afterRowId = rows[rows.length - 1].id;
+ }
+};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type.ts
new file mode 100644
index 00000000000..3bd8180e897
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-56/utils/step-agent-inline-config.type.ts
@@ -0,0 +1,24 @@
+import {
+ type AgentResponseFormat,
+ type AiRunScope,
+ type ModelConfiguration,
+} from 'twenty-shared/ai';
+import { type WorkflowConversation } from 'twenty-shared/workflow';
+
+export type StepAgentInlineConfig = {
+ instructions: string;
+ modelId: string;
+ modelConfiguration: ModelConfiguration | null;
+ responseFormat: AgentResponseFormat | null;
+ // null when the agent had no role, so the step keeps having no data tools
+ scope: AiRunScope | null;
+};
+
+export type StoredWorkflowStep = {
+ id?: unknown;
+ type?: unknown;
+ name?: unknown;
+ settings?: {
+ input?: Record<string, unknown> & { conversation?: WorkflowConversation };
+ } & Record<string, unknown>;
+} & Record<string, unknown>;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
index da1bbaaf774..180e662b7ae 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
@@ -14,6 +14,7 @@ import {
import { isDefined } from 'twenty-shared/utils';
import {
type BaseOutputSchemaV2,
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES,
WorkflowActionType,
} from 'twenty-shared/workflow';
@@ -668,6 +669,49 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {
});
});
+ it.each([
+ { humanInputInstructions: 'Ask when the company is unclear' },
+ { conversation: { scope: 'RUN' } },
+ ])('reports a step without an agent that stores %o', (agentOnlyInput) => {
+ const synced = syncWorkflow(
+ buildWorkflow({
+ steps: [
+ buildStep({
+ type: 'AI_AGENT',
+ overrides: {
+ input: {
+ instructions: 'Qualify the lead.',
+ prompt: 'Summarize {{trigger.text}}',
+ },
+ },
+ }),
+ ],
+ }),
+ );
+ const [step] = synced.flatWorkflowVersion.steps ?? [];
+
+ Object.assign(step.settings.input, agentOnlyInput);
+
+ expect(exportWorkflow(synced)).toEqual({
+ reason:
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.GENERATE_STEP_HAS_CONVERSATION_CONFIG,
+ });
+ });
+
+ it('reports a step on an agent that still stores its own config', () => {
+ const synced = syncWorkflow(
+ buildWorkflow({ steps: [buildStep({ type: 'AI_AGENT' })] }),
+ );
+ const [step] = synced.flatWorkflowVersion.steps ?? [];
+
+ Object.assign(step.settings.input, { instructions: 'Qualify the lead.' });
+
+ expect(exportWorkflow(synced)).toEqual({
+ reason:
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.AGENT_STEP_HAS_INLINE_CONFIG,
+ });
+ });
+
it('reports a webhook with authentication', () => {
const synced = syncWorkflow(
buildWorkflow({
@@ -738,6 +782,55 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {
reason:
'workflow step on a logic function that is not a workflow action of this application',
},
+ {
+ description: 'an agent scope naming an object that is not exported',
+ step: buildStep({
+ type: 'AI_AGENT',
+ overrides: {
+ input: {
+ prompt: 'Summarize {{trigger.text}}',
+ scope: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: OBJECT_ID,
+ canReadObjectRecords: true,
+ },
+ ],
+ },
+ },
+ },
+ }),
+ exportReferences: {
+ ...references,
+ objectByUniversalIdentifier: new Map(),
+ },
+ reason: 'workflow referencing an object that is not exported',
+ },
+ {
+ description: 'an agent scope naming a field that is not exported',
+ step: buildStep({
+ type: 'AI_AGENT',
+ overrides: {
+ input: {
+ prompt: 'Summarize {{trigger.text}}',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: OBJECT_ID,
+ fieldUniversalIdentifier: STATUS_FIELD_ID,
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ },
+ },
+ }),
+ exportReferences: {
+ ...references,
+ fieldByUniversalIdentifier: new Map(),
+ },
+ reason: 'workflow referencing a field that is not exported',
+ },
{
description: 'an agent the application does not export',
step: buildStep({ type: 'AI_AGENT' }),
@@ -1107,6 +1200,66 @@ describe('fromFlatWorkflowToWorkflowManifest on versions built in the workflow b
});
});
+ it('exports an agent step that carries its own config, with no agent to reference', () => {
+ const input = {
+ instructions: 'Qualify the lead from its last email.',
+ modelId: 'auto-select-workspace-default-model',
+ modelConfiguration: { webSearch: { enabled: true } },
+ scope: {
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: OBJECT_ID,
+ canUpdateObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: ['send-email-tool'],
+ },
+ prompt: '{{trigger.properties.after.summary}}',
+ };
+ const [step] = exportBuilderVersion({
+ triggers: [recordCreatedTrigger()],
+ steps: [
+ createRecordStep({
+ name: 'Qualify the lead',
+ type: 'AI_AGENT',
+ settings: {
+ outputSchema: {},
+ errorHandlingOptions: BUILDER_ERROR_HANDLING_OPTIONS,
+ input,
+ },
+ }),
+ ],
+ }).steps;
+
+ expect(step).toMatchObject({ type: 'AI_AGENT', input });
+ expect(step.input).not.toHaveProperty('agentUniversalIdentifier');
+ });
+
+ it('exports a step without an agent with the blank human input instructions the builder stores', () => {
+ const input = {
+ instructions: 'Qualify the lead from its last email.',
+ prompt: '{{trigger.properties.after.summary}}',
+ humanInputInstructions: '',
+ };
+ const [step] = exportBuilderVersion({
+ triggers: [recordCreatedTrigger()],
+ steps: [
+ createRecordStep({
+ name: 'Qualify the lead',
+ type: 'AI_AGENT',
+ settings: {
+ outputSchema: {},
+ errorHandlingOptions: BUILDER_ERROR_HANDLING_OPTIONS,
+ input,
+ },
+ }),
+ ],
+ }).steps;
+
+ expect(step).toMatchObject({ type: 'AI_AGENT', input });
+ });
+
it('exports an email step written without files', () => {
const input = {
connectedAccountId: '{{trigger.properties.after.accountId}}',
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
index c3d24e55d33..dc0d17afd51 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
@@ -233,6 +233,90 @@ describe('application workflow actions', () => {
expect(convert(type)).toMatchObject({ id: STEP_ID, type, valid: true });
});
+ it('keeps an agent step that carries its own config as is, with no agent to resolve', () => {
+ const input = {
+ instructions: 'Qualify the lead.',
+ modelId: 'auto-select-workspace-default-model',
+ scope: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: REFERENCE_ID,
+ canReadObjectRecords: true,
+ },
+ ],
+ },
+ prompt: 'Qualify {{trigger.name}}',
+ };
+ const result = fromWorkflowStepManifestToActionOrThrow({
+ step: workflowStepManifestSchema.parse({
+ universalIdentifier: STEP_ID,
+ name: 'Qualify',
+ type: 'AI_AGENT',
+ input,
+ nextStepIds: [],
+ }),
+ index: 0,
+ references: { ...references, agentIdByUniversalIdentifier: new Map() },
+ });
+
+ expect(result.settings.input).toEqual(input);
+ expect(result.settings.outputSchema).toMatchObject({
+ response: { type: 'string' },
+ });
+ });
+
+ it.each([
+ {
+ case: 'an object that is not available',
+ scope: {
+ objectPermissions: [
+ { objectUniversalIdentifier: LOCAL_ID, canReadObjectRecords: true },
+ ],
+ },
+ error: 'missing object',
+ },
+ {
+ case: 'a field that is not available',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: REFERENCE_ID,
+ fieldUniversalIdentifier: LOCAL_ID,
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ error: 'missing field',
+ },
+ {
+ case: 'a field of another object',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: LOCAL_ID,
+ fieldUniversalIdentifier: FIELD_ID,
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ error: 'does not belong',
+ },
+ ])('rejects a step scope naming $case', ({ scope, error }) => {
+ expect(() =>
+ fromWorkflowStepManifestToActionOrThrow({
+ step: workflowStepManifestSchema.parse({
+ universalIdentifier: STEP_ID,
+ name: 'Qualify',
+ type: 'AI_AGENT',
+ input: { prompt: 'Qualify {{trigger.name}}', scope },
+ nextStepIds: [],
+ }),
+ index: 0,
+ references,
+ }),
+ ).toThrow(error);
+ });
+
it('resolves functions, agents, objects and filter fields', () => {
expect(convert(WorkflowActionType.LOGIC_FUNCTION).settings.input).toEqual({
logicFunctionId: LOCAL_ID,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
index 0db4c5c03b0..29e3c4e95a1 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
@@ -1,7 +1,12 @@
import isEqual from 'lodash.isequal';
import { type WorkflowStepManifest } from 'twenty-shared/application';
import { isDefined, isPlainObject, sortKeysDeeply } from 'twenty-shared/utils';
-import { WorkflowActionType } from 'twenty-shared/workflow';
+import {
+ getWorkflowAiAgentStepConfigIssues,
+ isWorkflowAiAgentGenerateStep,
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES,
+ WorkflowActionType,
+} from 'twenty-shared/workflow';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
import { buildWorkflowManifestInverseReferenceResolvers } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util';
@@ -182,11 +187,24 @@ const fromActionInput = ({
return toRecord(input).logicFunctionInput;
case WorkflowActionType.AI_AGENT: {
const { agentId, ...rest } = toRecord(input);
+ // defineWorkflow refuses these, so the export would not apply
+ for (const issueCode of getWorkflowAiAgentStepConfigIssues(
+ action.settings.input,
+ )) {
+ resolvers.markUnsupported(
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES[issueCode],
+ );
+ }
- return {
- ...rest,
- agentUniversalIdentifier: resolvers.agentUniversalIdentifier(agentId),
- };
+ resolvers.checkAiRunScopeReferences(action.settings.input.scope);
+
+ return isWorkflowAiAgentGenerateStep(action.settings.input)
+ ? rest
+ : {
+ ...rest,
+ agentUniversalIdentifier:
+ resolvers.agentUniversalIdentifier(agentId),
+ };
}
case WorkflowActionType.CREATE_RECORD:
case WorkflowActionType.UPDATE_RECORD:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
index b34244bc3d7..a21f6cbb827 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
@@ -46,14 +46,27 @@ export const fromWorkflowStepManifestToActionOrThrow = ({
break;
case 'AI_AGENT': {
const { agentUniversalIdentifier, ...rest } = step.input;
- input = {
- ...rest,
- agentId: resolve(
- references.agentIdByUniversalIdentifier,
- agentUniversalIdentifier,
- 'application agent',
- ),
- };
+
+ // the scope names objects and fields by universal identifier, so it is checked rather than rewritten
+ for (const { objectUniversalIdentifier } of rest.scope
+ ?.objectPermissions ?? []) {
+ objectName(objectUniversalIdentifier);
+ }
+ for (const { objectUniversalIdentifier, fieldUniversalIdentifier } of rest
+ .scope?.fieldPermissions ?? []) {
+ field(fieldUniversalIdentifier, objectUniversalIdentifier);
+ }
+
+ input = isDefined(agentUniversalIdentifier)
+ ? {
+ ...rest,
+ agentId: resolve(
+ references.agentIdByUniversalIdentifier,
+ agentUniversalIdentifier,
+ 'application agent',
+ ),
+ }
+ : rest;
break;
}
case 'CREATE_RECORD':
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
index 6650e046711..198cf4c3ac6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
@@ -1,3 +1,5 @@
+import { isString } from '@sniptt/guards';
+import { type AiRunScope } from 'twenty-shared/ai';
import { isDefined, isPlainObject } from 'twenty-shared/utils';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
@@ -94,24 +96,56 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
reason: string;
}): string => universalIdentifier ?? markUnsupported(reason);
- const objectUniversalIdentifier = (nameSingular: unknown): string =>
+ const exportedUniversalIdentifier = ({
+ universalIdentifier,
+ exportedByUniversalIdentifier,
+ reason,
+ }: {
+ universalIdentifier: string | undefined;
+ exportedByUniversalIdentifier: ReadonlyMap<string, unknown> | undefined;
+ reason: string;
+ }): string =>
resolveOrMarkUnsupported({
universalIdentifier:
- typeof nameSingular === 'string'
- ? objectUniversalIdentifierByNameSingular.get(nameSingular)
+ isDefined(universalIdentifier) &&
+ exportedByUniversalIdentifier?.has(universalIdentifier)
+ ? universalIdentifier
: undefined,
+ reason,
+ });
+
+ const exportedObjectUniversalIdentifier = (
+ universalIdentifier: string | undefined,
+ ): string =>
+ exportedUniversalIdentifier({
+ universalIdentifier,
+ exportedByUniversalIdentifier: references.objectByUniversalIdentifier,
reason: 'workflow referencing an object that is not exported',
});
- const fieldUniversalIdentifier = (fieldMetadataId: unknown): string =>
- resolveOrMarkUnsupported({
- universalIdentifier:
- typeof fieldMetadataId === 'string'
- ? fieldUniversalIdentifierById.get(fieldMetadataId)
- : undefined,
+ const exportedFieldUniversalIdentifier = (
+ universalIdentifier: string | undefined,
+ ): string =>
+ exportedUniversalIdentifier({
+ universalIdentifier,
+ exportedByUniversalIdentifier: references.fieldByUniversalIdentifier,
reason: 'workflow referencing a field that is not exported',
});
+ const objectUniversalIdentifier = (nameSingular: unknown): string =>
+ exportedObjectUniversalIdentifier(
+ isString(nameSingular)
+ ? objectUniversalIdentifierByNameSingular.get(nameSingular)
+ : undefined,
+ );
+
+ const fieldUniversalIdentifier = (fieldMetadataId: unknown): string =>
+ exportedFieldUniversalIdentifier(
+ isString(fieldMetadataId)
+ ? fieldUniversalIdentifierById.get(fieldMetadataId)
+ : undefined,
+ );
+
const fieldUniversalIdentifierByName = ({
objectUniversalIdentifier,
fieldName,
@@ -119,15 +153,34 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
objectUniversalIdentifier: string;
fieldName: unknown;
}): string =>
- resolveOrMarkUnsupported({
- universalIdentifier:
- typeof fieldName === 'string'
- ? fieldUniversalIdentifierByObjectFieldName.get(
- toObjectFieldKey({ objectUniversalIdentifier, name: fieldName }),
- )
- : undefined,
- reason: 'workflow referencing a field that is not exported',
- });
+ exportedFieldUniversalIdentifier(
+ isString(fieldName)
+ ? fieldUniversalIdentifierByObjectFieldName.get(
+ toObjectFieldKey({ objectUniversalIdentifier, name: fieldName }),
+ )
+ : undefined,
+ );
+
+ // The scope already names objects and fields by universal identifier, but only exported ones can be applied
+ const checkAiRunScopeReferences = (
+ scope:
+ | Pick<AiRunScope, 'objectPermissions' | 'fieldPermissions'>
+ | null
+ | undefined,
+ ): void => {
+ for (const { objectUniversalIdentifier } of scope?.objectPermissions ??
+ []) {
+ exportedObjectUniversalIdentifier(objectUniversalIdentifier);
+ }
+
+ for (const {
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ } of scope?.fieldPermissions ?? []) {
+ exportedObjectUniversalIdentifier(objectUniversalIdentifier);
+ exportedFieldUniversalIdentifier(fieldUniversalIdentifier);
+ }
+ };
const watchedFieldUniversalIdentifier = ({
objectUniversalIdentifier,
@@ -137,34 +190,31 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
watchedFieldName: unknown;
}): string =>
resolveOrMarkUnsupported({
- universalIdentifier:
- typeof watchedFieldName === 'string'
- ? fieldUniversalIdentifierByWatchedFieldName.get(
- toObjectFieldKey({
- objectUniversalIdentifier,
- name: watchedFieldName,
- }),
- )
- : undefined,
+ universalIdentifier: isString(watchedFieldName)
+ ? fieldUniversalIdentifierByWatchedFieldName.get(
+ toObjectFieldKey({
+ objectUniversalIdentifier,
+ name: watchedFieldName,
+ }),
+ )
+ : undefined,
reason: 'workflow watching a field that is not exported',
});
const logicFunctionUniversalIdentifier = (logicFunctionId: unknown): string =>
resolveOrMarkUnsupported({
- universalIdentifier:
- typeof logicFunctionId === 'string'
- ? logicFunctionUniversalIdentifierById.get(logicFunctionId)
- : undefined,
+ universalIdentifier: isString(logicFunctionId)
+ ? logicFunctionUniversalIdentifierById.get(logicFunctionId)
+ : undefined,
reason:
'workflow step on a logic function that is not a workflow action of this application',
});
const agentUniversalIdentifier = (agentId: unknown): string =>
resolveOrMarkUnsupported({
- universalIdentifier:
- typeof agentId === 'string'
- ? agentUniversalIdentifierById.get(agentId)
- : undefined,
+ universalIdentifier: isString(agentId)
+ ? agentUniversalIdentifierById.get(agentId)
+ : undefined,
reason: 'workflow step on an agent the application does not export',
});
@@ -176,10 +226,9 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
stepType: WorkflowConnectedAccountStepType;
connectedAccountId: unknown;
}): { connectedAccountId: unknown } | { connectedAccountHandle: string } => {
- const connectedAccount =
- typeof connectedAccountId === 'string'
- ? connectedAccountById.get(connectedAccountId)
- : undefined;
+ const connectedAccount = isString(connectedAccountId)
+ ? connectedAccountById.get(connectedAccountId)
+ : undefined;
if (
!isDefined(connectedAccount) ||
@@ -240,6 +289,7 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
watchedFieldUniversalIdentifier,
logicFunctionUniversalIdentifier,
agentUniversalIdentifier,
+ checkAiRunScopeReferences,
connectedAccountReference,
markUnsupported,
getUnsupportedReason: (): string | undefined => unsupportedReasons[0],
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
index 489e8fb9ab0..0ddf78d3b50 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service.ts
@@ -107,6 +107,10 @@ export class PendingWakeUpResolverService {
ReturnType<PendingWakeUpOwnerHandler['getReadPermissions']>
>;
}): Promise<PendingWakeUpEvent | undefined> {
+ if (!isDefined(readPermissions)) {
+ return undefined;
+ }
+
const [objectName, action] = event.eventName.split('.');
const { success, result, error } = await this.findRecordsService.execute({
diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
index b0a5a783941..ca68dc375fe 100644
--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type.ts
@@ -14,13 +14,14 @@ export type PendingWakeUpOwnerHandler<TOwner = unknown> = {
wakeUp: PendingWakeUpEntity,
): Promise<PendingWakeUpOwnerState<TOwner>>;
+ // null when the owner may read no record, so no event wakes it up
getReadPermissions(input: {
wakeUp: PendingWakeUpEntity;
owner: TOwner;
}): Promise<{
authContext: WorkspaceAuthContext;
rolePermissionConfig: RolePermissionConfig;
- }>;
+ } | null>;
// the handler claims the wake-up once it takes the outcome, so the outcome is taken once
resolve(input: {
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type.ts
new file mode 100644
index 00000000000..deeb8115e45
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type.ts
@@ -0,0 +1,4 @@
+import { type ObjectRecordsPermissionGrants } from 'twenty-shared/application';
+
+// the only objects a run is handed tools for, so it is not handed one per object its roles can reach
+export type ExplicitObjectGrants = ObjectRecordsPermissionGrants;
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type.ts
index f433264f2da..18b42e69556 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type.ts
@@ -3,6 +3,7 @@ import { type APP_LOCALES } from 'twenty-shared/translations';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/code-execution-stream-emitter.type';
import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
@@ -20,6 +21,5 @@ export type ToolProviderContext = {
threadId?: string;
locale?: keyof typeof APP_LOCALES;
onCodeExecutionUpdate?: CodeExecutionStreamEmitter;
- // database tools then only cover the objects this role explicitly grants
- explicitObjectGrantsRoleId?: string;
+ explicitObjectGrants?: ExplicitObjectGrants;
};
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
index 9a93eb35c77..fc5153718c8 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
@@ -1,6 +1,8 @@
import { type ToolCatalogOptions } from 'src/engine/core-modules/tool-provider/types/tool-catalog-options.type';
+import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
export type ToolRetrievalOptions = ToolCatalogOptions & {
+ isToolOffered?: (tool: ToolIndexEntry) => boolean;
// Apply output compaction (strip nulls/empty values) to dispatch results
// before returning. Chat enables this to reduce token usage in the
// conversation context; MCP and workflow agents leave raw output intact.
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
index ad50a94a93b..58b3d2731c3 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
@@ -3,6 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { type ApplicationTranslationCatalogService } from 'src/engine/metadata-modules/application-translation-catalog/services/application-translation-catalog.service';
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
import { DatabaseToolProvider } from 'src/engine/core-modules/tool-provider/providers/database-tool.provider';
import { type ToolDescriptor } from 'src/engine/core-modules/tool-provider/types/tool-descriptor.type';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
@@ -17,7 +18,6 @@ import { type RolePermissionConfig } from 'src/engine/permissions/principal/type
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
const roleId = 'role-id';
-const userRoleId = 'user-role-id';
const workspaceId = 'workspace-id';
const allObjectPermissions: ObjectPermissions = {
@@ -41,18 +41,9 @@ const createFlatObject = (
...overrides,
});
-type ExplicitPermissionRow = {
- objectMetadataId: string;
- canReadObjectRecords?: boolean;
- canUpdateObjectRecords?: boolean;
- canSoftDeleteObjectRecords?: boolean;
-};
-
type GenerateDescriptorsTestOptions = {
- explicitObjectGrantsRoleId?: string;
- explicitPermissionRows?: ExplicitPermissionRow[];
+ explicitObjectGrants?: ExplicitObjectGrants;
composedObjectPermissions?: Partial<ObjectPermissions>;
- explicitPermissionRowsRoleId?: string;
rolePermissionConfig?: RolePermissionConfig;
sharedOperationTypes?: OperationType[];
};
@@ -90,15 +81,6 @@ describe('DatabaseToolProvider', () => {
object.universalIdentifier;
}
- const explicitPermissionRows =
- options?.explicitPermissionRows ??
- objects.map((object) => ({
- objectMetadataId: object.id,
- canReadObjectRecords: true,
- canUpdateObjectRecords: true,
- canSoftDeleteObjectRecords: true,
- }));
-
const composedObjectPermissionsByObjectId = Object.fromEntries(
objects.map((object) => [
object.id,
@@ -113,20 +95,8 @@ describe('DatabaseToolProvider', () => {
getOrRecompute: jest.fn().mockResolvedValue({
rolesPermissions: {
[roleId]: composedObjectPermissionsByObjectId,
- [userRoleId]: composedObjectPermissionsByObjectId,
},
flatApplicationMaps: { byId: {}, idByUniversalIdentifier: {} },
- flatObjectPermissionMaps: {
- byUniversalIdentifier: Object.fromEntries(
- explicitPermissionRows.map((row, index) => [
- `object-permission-${index}`,
- {
- roleId: options?.explicitPermissionRowsRoleId ?? roleId,
- ...row,
- },
- ]),
- ),
- },
}),
} as unknown as WorkspaceCacheService;
@@ -191,7 +161,7 @@ describe('DatabaseToolProvider', () => {
rolePermissionConfig: options?.rolePermissionConfig ?? {
intersectionOf: { agentRoleId: roleId },
},
- explicitObjectGrantsRoleId: options?.explicitObjectGrantsRoleId,
+ explicitObjectGrants: options?.explicitObjectGrants,
},
{ includeSchemas: false },
)) as (ToolIndexEntry | ToolDescriptor)[];
@@ -440,7 +410,7 @@ describe('DatabaseToolProvider', () => {
}
});
- describe('explicitObjectGrantsRoleId', () => {
+ describe('explicitObjectGrants', () => {
const personObject = createFlatObject({
nameSingular: 'person',
namePlural: 'people',
@@ -450,35 +420,42 @@ describe('DatabaseToolProvider', () => {
namePlural: 'companies',
});
- it('emits no tools for objects without an explicit permission row', async () => {
+ it('emits no tools for objects the grants do not name', async () => {
const descriptorNames = await generateDescriptorNames(
[personObject, companyObject],
{
- explicitObjectGrantsRoleId: roleId,
- explicitPermissionRows: [
- {
- objectMetadataId: personObject.id,
- canReadObjectRecords: true,
- },
- ],
+ explicitObjectGrants: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: personObject.universalIdentifier,
+ canReadObjectRecords: true,
+ },
+ ],
+ },
},
);
expect(descriptorNames).toContain('find_many_people');
+ expect(descriptorNames).not.toContain('create_one_person');
expect(descriptorNames).not.toContain('find_many_companies');
});
- it('emits only the verbs granted by the explicit row', async () => {
+ it('drops the verbs the composed permissions deny even when granted', async () => {
const descriptorNames = await generateDescriptorNames([personObject], {
- explicitObjectGrantsRoleId: roleId,
- explicitPermissionRows: [
- {
- objectMetadataId: personObject.id,
- canReadObjectRecords: true,
- canUpdateObjectRecords: false,
- canSoftDeleteObjectRecords: false,
- },
- ],
+ explicitObjectGrants: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: personObject.universalIdentifier,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
+ },
+ ],
+ },
+ composedObjectPermissions: {
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ },
});
expect(descriptorNames).toContain('find_many_people');
@@ -486,39 +463,34 @@ describe('DatabaseToolProvider', () => {
expect(descriptorNames).not.toContain('delete_one_person');
});
- it('drops the verbs the composed permissions deny even with an explicit row', async () => {
- const descriptorNames = await generateDescriptorNames([personObject], {
- explicitObjectGrantsRoleId: roleId,
- composedObjectPermissions: {
- canUpdateObjectRecords: false,
- canSoftDeleteObjectRecords: false,
+ it('names every object for an action granted on all objects', async () => {
+ const descriptorNames = await generateDescriptorNames(
+ [personObject, companyObject],
+ {
+ explicitObjectGrants: { canReadAllObjectRecords: true },
},
- });
+ );
expect(descriptorNames).toContain('find_many_people');
+ expect(descriptorNames).toContain('find_many_companies');
expect(descriptorNames).not.toContain('create_one_person');
- expect(descriptorNames).not.toContain('delete_one_person');
});
- it('ignores explicit rows of the other roles', async () => {
+ it('keeps all-objects grants within the composed permissions', async () => {
const descriptorNames = await generateDescriptorNames([personObject], {
- explicitObjectGrantsRoleId: roleId,
- explicitPermissionRowsRoleId: userRoleId,
- rolePermissionConfig: {
- intersectionOf: {
- agentRoleId: roleId,
- userWorkspaceRoleId: userRoleId,
- },
+ explicitObjectGrants: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
},
+ composedObjectPermissions: { canUpdateObjectRecords: false },
});
- expect(descriptorNames).toEqual([]);
+ expect(descriptorNames).toContain('find_many_people');
+ expect(descriptorNames).not.toContain('create_one_person');
});
- it('keeps composed permissions without a grants role even without explicit rows', async () => {
- const descriptorNames = await generateDescriptorNames([personObject], {
- explicitPermissionRows: [],
- });
+ it('keeps composed permissions without explicit grants', async () => {
+ const descriptorNames = await generateDescriptorNames([personObject]);
expect(descriptorNames).toContain('find_many_people');
expect(descriptorNames).toContain('create_one_person');
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
index cd0582c5f70..04adec4b86b 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
@@ -1,6 +1,10 @@
import { type I18n } from '@lingui/core';
import { Injectable } from '@nestjs/common';
+import {
+ type EffectiveObjectPermissions,
+ type ObjectPermissionAction,
+} from 'twenty-shared/application';
import { MUTATION_MAX_MERGE_RECORDS } from 'twenty-shared/constants';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
import { camelToSnakeCase, isDefined } from 'twenty-shared/utils';
@@ -28,8 +32,8 @@ import { MERGE_MANY_TOOL_INPUT_SCHEMA } from 'src/engine/core-modules/record-cru
import { type ToolDescriptor } from 'src/engine/core-modules/tool-provider/types/tool-descriptor.type';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { buildExplicitObjectPermissionByObjectId } from 'src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util';
import { getDatabaseCrudToolFlatObjects } from 'src/engine/metadata-modules/ai/ai-agent/utils/get-database-crud-tool-flat-objects.util';
-import { type FlatObjectPermission } from 'src/engine/metadata-modules/flat-object-permission/types/flat-object-permission.type';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { RecordAccessPolicyService } from 'src/engine/permissions/combine/services/record-access-policy.service';
import { buildDeprecatedPermissionsPrincipalsFromConfig } from 'src/engine/permissions/principal/utils/build-deprecated-permissions-principals-from-config.util';
@@ -77,10 +81,9 @@ export class DatabaseToolProvider implements ToolProvider {
const toolNames = options?.toolNames;
const descriptors: (ToolIndexEntry | ToolDescriptor)[] = [];
- const { rolesPermissions, flatObjectPermissionMaps, flatApplicationMaps } =
+ const { rolesPermissions, flatApplicationMaps } =
await this.workspaceCacheService.getOrRecompute(context.workspaceId, [
'rolesPermissions',
- 'flatObjectPermissionMaps',
'flatApplicationMaps',
]);
const { flatObjectMetadataMaps, flatFieldMetadataMaps } =
@@ -113,28 +116,20 @@ export class DatabaseToolProvider implements ToolProvider {
return descriptors;
}
- const { explicitObjectGrantsRoleId } = context;
- const requireExplicitObjectGrants = isDefined(explicitObjectGrantsRoleId);
-
- const explicitPermissionByObjectId = new Map<
- string,
- FlatObjectPermission
- >();
-
- if (requireExplicitObjectGrants) {
- for (const flatObjectPermission of Object.values(
- flatObjectPermissionMaps.byUniversalIdentifier,
- )) {
- if (
- isDefined(flatObjectPermission) &&
- flatObjectPermission.roleId === explicitObjectGrantsRoleId
- ) {
- explicitPermissionByObjectId.set(
- flatObjectPermission.objectMetadataId,
- flatObjectPermission,
- );
- }
- }
+ const { explicitObjectGrants } = context;
+ const requireExplicitObjectGrants = isDefined(explicitObjectGrants);
+ const explicitPermissionByObjectId = requireExplicitObjectGrants
+ ? buildExplicitObjectPermissionByObjectId({
+ explicitObjectGrants,
+ flatObjectMetadataMaps,
+ })
+ : new Map<string, EffectiveObjectPermissions>();
+
+ if (
+ requireExplicitObjectGrants &&
+ explicitPermissionByObjectId.size === 0
+ ) {
+ return descriptors;
}
const allFlatObjects = getDatabaseCrudToolFlatObjects(
@@ -166,15 +161,7 @@ export class DatabaseToolProvider implements ToolProvider {
continue;
}
- const isExplicitlyGranted = (
- objectPermission: keyof Pick<
- FlatObjectPermission,
- | 'canReadObjectRecords'
- | 'canUpdateObjectRecords'
- | 'canSoftDeleteObjectRecords'
- | 'canDestroyObjectRecords'
- >,
- ) =>
+ const isExplicitlyGranted = (objectPermission: ObjectPermissionAction) =>
!requireExplicitObjectGrants ||
(explicitPermission?.[objectPermission] ?? false);
const hasAccessToSomeRecords = async (operationType: OperationType) =>
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts
index 0746a93bf96..ad43a284ba5 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts
@@ -8,7 +8,6 @@ import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/servi
import { type ToolOutputSpillService } from 'src/engine/core-modules/tool/services/tool-output-spill.service';
const workspaceId = 'workspace-id';
-const agentRoleId = 'agent-role-id';
const buildToolRegistryService = () => {
const generateDescriptors = jest.fn().mockResolvedValue([]);
@@ -52,12 +51,14 @@ describe('ToolRegistryService', () => {
rolePermissionConfig: {
intersectionOf: { userWorkspaceRoleId: 'member-role-id' },
},
- explicitObjectGrantsRoleId: agentRoleId,
+ explicitObjectGrants: { canReadAllObjectRecords: true },
resolveExecutionContext: async () => resolvedContext,
});
expect(generateDescriptors).toHaveBeenCalledWith(
- expect.objectContaining({ explicitObjectGrantsRoleId: agentRoleId }),
+ expect.objectContaining({
+ explicitObjectGrants: { canReadAllObjectRecords: true },
+ }),
expect.anything(),
);
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
index 08e0d1d3329..7fae24ef6e8 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
@@ -421,14 +421,21 @@ export class ToolRegistryService {
context: ToolProviderContext,
options: ToolRetrievalOptions = {},
): Promise<ToolSet> {
- const { categories, excludeTools, compactOutput, spillLargeOutput } =
- options;
-
- const descriptors = await this.getCatalog(context, {
+ const {
categories,
excludeTools,
- includeSchemas: true,
- });
+ isToolOffered = () => true,
+ compactOutput,
+ spillLargeOutput,
+ } = options;
+
+ const descriptors = (
+ await this.getCatalog(context, {
+ categories,
+ excludeTools,
+ includeSchemas: true,
+ })
+ ).filter(isToolOffered);
const toolSet = this.hydrateToolSet(descriptors, context, {
compactOutput,
@@ -523,7 +530,7 @@ export class ToolRegistryService {
return {
...(await context.resolveExecutionContext()),
- explicitObjectGrantsRoleId: context.explicitObjectGrantsRoleId,
+ explicitObjectGrants: context.explicitObjectGrants,
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/build-explicit-object-permission-by-object-id.util.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/build-explicit-object-permission-by-object-id.util.spec.ts
new file mode 100644
index 00000000000..98809945103
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/build-explicit-object-permission-by-object-id.util.spec.ts
@@ -0,0 +1,64 @@
+import { buildExplicitObjectPermissionByObjectId } from 'src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+
+const buildFlatObjectMetadataMaps = (
+ objects: { id: string; universalIdentifier: string }[],
+) => ({
+ byUniversalIdentifier: Object.fromEntries(
+ objects.map((object) => [
+ object.universalIdentifier,
+ getFlatObjectMetadataMock(object),
+ ]),
+ ),
+});
+
+const flatObjectMetadataMaps = buildFlatObjectMetadataMaps([
+ { id: 'company-id', universalIdentifier: 'company' },
+ { id: 'person-id', universalIdentifier: 'person' },
+]);
+
+describe('buildExplicitObjectPermissionByObjectId', () => {
+ it('lets an object denied on its own override its all-objects grant', () => {
+ const permissionByObjectId = buildExplicitObjectPermissionByObjectId({
+ explicitObjectGrants: {
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ canReadObjectRecords: false,
+ canUpdateObjectRecords: false,
+ },
+ ],
+ },
+ flatObjectMetadataMaps,
+ });
+
+ expect(permissionByObjectId.get('company-id')).toEqual({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ });
+ expect(permissionByObjectId.has('person-id')).toBe(false);
+ });
+
+ it('grants an object named on its own', () => {
+ const permissionByObjectId = buildExplicitObjectPermissionByObjectId({
+ explicitObjectGrants: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ canReadObjectRecords: true,
+ },
+ ],
+ },
+ flatObjectMetadataMaps,
+ });
+
+ expect([...permissionByObjectId.keys()]).toEqual(['company-id']);
+ expect(permissionByObjectId.get('company-id')?.canReadObjectRecords).toBe(
+ true,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util.ts
new file mode 100644
index 00000000000..5fdf573b308
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util.ts
@@ -0,0 +1,37 @@
+import {
+ type EffectiveObjectPermissions,
+ getEffectiveObjectPermissionsFromRoleManifest,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+export const buildExplicitObjectPermissionByObjectId = ({
+ explicitObjectGrants,
+ flatObjectMetadataMaps,
+}: {
+ explicitObjectGrants: ExplicitObjectGrants;
+ flatObjectMetadataMaps: Pick<
+ FlatEntityMaps<FlatObjectMetadata>,
+ 'byUniversalIdentifier'
+ >;
+}): Map<string, EffectiveObjectPermissions> =>
+ new Map(
+ Object.values(flatObjectMetadataMaps.byUniversalIdentifier)
+ .filter(isDefined)
+ .flatMap((flatObjectMetadata) => {
+ const effectiveObjectPermissions =
+ getEffectiveObjectPermissionsFromRoleManifest({
+ role: explicitObjectGrants,
+ objectUniversalIdentifier: flatObjectMetadata.universalIdentifier,
+ });
+
+ return Object.values(effectiveObjectPermissions).some(
+ (isGranted) => isGranted,
+ )
+ ? [[flatObjectMetadata.id, effectiveObjectPermissions] as const]
+ : [];
+ }),
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
new file mode 100644
index 00000000000..fabef02be79
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
@@ -0,0 +1,154 @@
+import { Test } from '@nestjs/testing';
+
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
+import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workflow/services/core-workflow-id-resolution.service';
+import { CoreWorkflowVersionListService } from 'src/engine/core-modules/workflow/services/core-workflow-version-list.service';
+import { CoreWorkflowVersionMutationWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service';
+import { CoreWorkflowVersionWriteService } from 'src/engine/core-modules/workflow/services/core-workflow-version-write.service';
+import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
+import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
+import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const WORKSPACE_ID = 'workspace-id';
+const CORE_WORKFLOW_VERSION_ID = 'core-workflow-version-id';
+
+const buildAiAgentStep = ({
+ input,
+}: {
+ input: WorkflowAiAgentAction['settings']['input'];
+}): WorkflowAiAgentAction => ({
+ id: 'step-id',
+ name: 'Agent',
+ type: WorkflowActionType.AI_AGENT,
+ valid: true,
+ nextStepIds: ['next-step-id'],
+ position: { x: 10, y: 20 },
+ settings: {
+ input,
+ outputSchema: {},
+ errorHandlingOptions: {
+ continueOnFailure: { value: false },
+ retryOnFailure: { value: 0 },
+ },
+ },
+});
+
+const buildService = async ({
+ existingStep,
+}: {
+ existingStep: WorkflowAiAgentAction;
+}) => {
+ const coreWorkflowVersionWriteService = {
+ getValidatedDraftCoreWorkflowVersion: jest.fn().mockResolvedValue({
+ coreWorkflowVersion: { id: CORE_WORKFLOW_VERSION_ID },
+ trigger: null,
+ steps: [existingStep],
+ }),
+ writeContent: jest
+ .fn()
+ .mockImplementation(async ({ steps }) => ({ trigger: null, steps })),
+ };
+ const workflowVersionStepOperationsWorkspaceService = {
+ runStepCreationSideEffectsAndBuildStep: jest.fn(),
+ runWorkflowVersionStepDeletionSideEffects: jest.fn(),
+ };
+
+ const testingModule = await Test.createTestingModule({
+ providers: [
+ CoreWorkflowVersionMutationWorkspaceService,
+ {
+ provide: getWorkspaceScopedRepositoryToken(WorkflowVersionEntity),
+ useValue: {},
+ },
+ { provide: CoreWorkflowIdResolutionService, useValue: {} },
+ {
+ provide: CoreWorkflowVersionWriteService,
+ useValue: coreWorkflowVersionWriteService,
+ },
+ { provide: CoreWorkflowVersionListService, useValue: {} },
+ { provide: WorkflowCoreSyncService, useValue: {} },
+ {
+ provide: WorkflowVersionStepOperationsWorkspaceService,
+ useValue: workflowVersionStepOperationsWorkspaceService,
+ },
+ { provide: CacheLockService, useValue: {} },
+ ],
+ }).compile();
+
+ return {
+ service: testingModule.get(CoreWorkflowVersionMutationWorkspaceService),
+ coreWorkflowVersionWriteService,
+ workflowVersionStepOperationsWorkspaceService,
+ };
+};
+
+describe('CoreWorkflowVersionMutationWorkspaceService.updateStep', () => {
+ it.each([
+ ['removes its agent', { agentId: 'agent-id' }, {}],
+ ['adds an agent', {}, { agentId: 'agent-id' }],
+ ['changes its agent', { agentId: 'agent-id' }, { agentId: 'other-id' }],
+ ])(
+ 'refuses to update an AI step that %s',
+ async (_, existingInput, updatedInput) => {
+ const { service, coreWorkflowVersionWriteService } = await buildService({
+ existingStep: buildAiAgentStep({
+ input: { ...existingInput, prompt: 'Qualify' },
+ }),
+ });
+
+ await expect(
+ service.updateStep({
+ workspaceId: WORKSPACE_ID,
+ userWorkspaceId: undefined,
+ coreWorkflowVersionId: CORE_WORKFLOW_VERSION_ID,
+ step: buildAiAgentStep({
+ input: { ...updatedInput, prompt: 'Qualify' },
+ }),
+ }),
+ ).rejects.toThrow('Create a new step instead');
+ expect(
+ coreWorkflowVersionWriteService.writeContent,
+ ).not.toHaveBeenCalled();
+ },
+ );
+
+ it('updates an AI step in place when its agent is unchanged', async () => {
+ const existingStep = buildAiAgentStep({
+ input: { agentId: 'agent-id', prompt: 'Qualify' },
+ });
+ const {
+ service,
+ coreWorkflowVersionWriteService,
+ workflowVersionStepOperationsWorkspaceService,
+ } = await buildService({ existingStep });
+ const step = buildAiAgentStep({
+ input: { agentId: 'agent-id', prompt: 'Qualify the lead' },
+ });
+
+ const updatedStep = await service.updateStep({
+ workspaceId: WORKSPACE_ID,
+ userWorkspaceId: undefined,
+ coreWorkflowVersionId: CORE_WORKFLOW_VERSION_ID,
+ step,
+ });
+
+ expect(updatedStep).toEqual(step);
+ expect(coreWorkflowVersionWriteService.writeContent).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ coreWorkflowVersionId: CORE_WORKFLOW_VERSION_ID,
+ expectedVersion: { id: CORE_WORKFLOW_VERSION_ID },
+ trigger: null,
+ steps: [step],
+ });
+ expect(
+ workflowVersionStepOperationsWorkspaceService.runStepCreationSideEffectsAndBuildStep,
+ ).not.toHaveBeenCalled();
+ expect(
+ workflowVersionStepOperationsWorkspaceService.runWorkflowVersionStepDeletionSideEffects,
+ ).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
index fbc750568bc..18568972155 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
@@ -46,6 +46,7 @@ import {
import { type WorkflowStepConnectionOptions } from 'src/modules/workflow/workflow-builder/workflow-version-step/types/workflow-step-connection-options.type';
import { getNextStepIdsForStepTypeChange } from 'src/modules/workflow/workflow-builder/workflow-version-step/utils/get-next-step-ids-for-step-type-change.util';
import { insertStep } from 'src/modules/workflow/workflow-builder/workflow-version-step/utils/insert-step';
+import { isWorkflowAiAgentStepKindChanged } from 'src/modules/workflow/workflow-builder/workflow-version-step/utils/is-workflow-ai-agent-step-kind-changed.util';
import { removeStep } from 'src/modules/workflow/workflow-builder/workflow-version-step/utils/remove-step';
import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
@@ -220,6 +221,17 @@ export class CoreWorkflowVersionMutationWorkspaceService {
);
}
+ // an AI step's kind and agent are fixed once it exists: a different agent is a new step
+ if (isWorkflowAiAgentStepKindChanged({ existingStep, updatedStep: step })) {
+ throw new WorkflowVersionStepException(
+ 'An AI step cannot switch between generating and running an agent, or to another agent. Create a new step instead.',
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ {
+ userFriendlyMessage: msg`An AI step cannot change its agent. Create a new step instead.`,
+ },
+ );
+ }
+
const isStepTypeChanged = existingStep.type !== step.type;
const { updatedStep, additionalCreatedSteps } = isStepTypeChanged
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 7c828229c08..6b0e4098e59 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
@@ -17,10 +17,13 @@ import { DeliverAgentRunOutcomeJob } from 'src/engine/metadata-modules/ai/ai-age
import { RunAgentJob } from 'src/engine/metadata-modules/ai/ai-agent-execution/jobs/run-agent.job';
import { AgentMessagePartResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-message-part.resolver';
import { AgentMessageResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-message.resolver';
+import { AiGenerateService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/ai-generate.service';
import { AgentRunResolver } from 'src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { AgentRunCallerContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service';
import { AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
import { AgentRunJobScopeService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service';
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { AgentRunPendingWakeUpHandlerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service';
@@ -41,6 +44,7 @@ import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/ag
import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
import { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-billing.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
+import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { PermissionsModule } from 'src/engine/permissions/permissions.module';
import { SkillModule } from 'src/engine/metadata-modules/skill/skill.module';
import { UserRoleModule } from 'src/engine/permissions/role-assignment/user-role.module';
@@ -66,6 +70,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
SkillModule,
ToolProviderModule,
WorkspaceCacheModule,
+ WorkspaceManyOrAllFlatEntityMapsCacheModule,
TypeOrmModule.forFeature([
AgentEntity,
FileEntity,
@@ -76,14 +81,17 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
providers: [
AgentActorContextService,
AgentCallerConversationService,
+ AgentRunCallerContextService,
AgentRunCallerHandlerRegistryService,
AgentRunConversationService,
AgentRunJobScopeService,
+ AgentRunPersonaService,
AgentRunSuspensionService,
AgentMessagePartResolver,
AgentMessageResolver,
AgentRunResolver,
AgentRunService,
+ AiGenerateService,
AgentRunSettlementService,
AgentRunnerService,
AgentStepLoopService,
@@ -105,6 +113,8 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
AgentCallerConversationService,
AgentRunCallerHandlerRegistryService,
AgentRunConversationService,
+ AgentRunService,
+ AgentRunPersonaService,
AgentRunSuspensionService,
AgentRunnerService,
AgentTurnService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-out-of-credits-error.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-out-of-credits-error.const.ts
new file mode 100644
index 00000000000..49cea3ab3f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-out-of-credits-error.const.ts
@@ -0,0 +1,2 @@
+export const AGENT_RUN_OUT_OF_CREDITS_ERROR =
+ 'Agent stopped: no more available credits.';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stopped-error.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stopped-error.constant.ts
new file mode 100644
index 00000000000..dd2e45db641
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stopped-error.constant.ts
@@ -0,0 +1 @@
+export const AGENT_RUN_STOPPED_ERROR = 'The run was stopped';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stream-channel-id-namespace.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stream-channel-id-namespace.const.ts
new file mode 100644
index 00000000000..c6f69c4cd6e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stream-channel-id-namespace.const.ts
@@ -0,0 +1,2 @@
+export const AGENT_RUN_STREAM_CHANNEL_ID_NAMESPACE =
+ '202c7b8e-183c-4693-9c43-550fb7da4e34';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/scoped-agent-run-action-tool-names.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/scoped-agent-run-action-tool-names.const.ts
new file mode 100644
index 00000000000..84cba6af4c8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/constants/scoped-agent-run-action-tool-names.const.ts
@@ -0,0 +1,12 @@
+import { type ActionToolId } from 'src/engine/core-modules/tool-provider/constants/action-tool-label.constant';
+
+// these act with the run's permissions or the workspace's connected accounts; tools acting as the system or a member are left out
+export const SCOPED_AGENT_RUN_ACTION_TOOL_NAMES: ReadonlySet<string> =
+ new Set<ActionToolId>([
+ 'http_request',
+ 'send_email',
+ 'draft_email',
+ 'find_connected_accounts',
+ 'create_calendar_event',
+ 'save_campaign',
+ ]);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/ai-run-usage.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/ai-run-usage.dto.ts
new file mode 100644
index 00000000000..ace8512b5d6
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/ai-run-usage.dto.ts
@@ -0,0 +1,12 @@
+import { Field, Int, ObjectType } from '@nestjs/graphql';
+
+import { type AiRunUsage } from 'twenty-shared/application';
+
+@ObjectType('AiRunUsage')
+export class AiRunUsageDTO implements AiRunUsage {
+ @Field(() => Int)
+ inputTokens: number;
+
+ @Field(() => Int)
+ outputTokens: number;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate-result.dto.ts
new file mode 100644
index 00000000000..e67003449bb
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate-result.dto.ts
@@ -0,0 +1,28 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import GraphQLJSON from 'graphql-type-json';
+import { type GenerateResult } from 'twenty-shared/application';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { AiRunUsageDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/ai-run-usage.dto';
+
+@ObjectType('GenerateResult')
+export class GenerateResultDTO implements GenerateResult {
+ @Field()
+ success: boolean;
+
+ @Field(() => String, { nullable: true })
+ text: string | null;
+
+ @Field(() => GraphQLJSON, { nullable: true })
+ object: Record<string, unknown> | null;
+
+ @Field(() => String, { nullable: true })
+ error: string | null;
+
+ @Field(() => UUIDScalarType)
+ runId: string;
+
+ @Field(() => AiRunUsageDTO)
+ usage: AiRunUsageDTO;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input.ts
new file mode 100644
index 00000000000..a26dc83e9ba
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input.ts
@@ -0,0 +1,55 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { Type } from 'class-transformer';
+import GraphQLJSON from 'graphql-type-json';
+import { type AgentResponseFormat, type AiRunScope } from 'twenty-shared/ai';
+import {
+ ArrayMaxSize,
+ ArrayNotEmpty,
+ IsArray,
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ IsUUID,
+ ValidateNested,
+} from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { RunAgentMessageInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-message.input';
+
+// the service parses the JSON fields with generateJsonFieldsSchema
+@InputType('GenerateInput')
+export class GenerateInputDTO {
+ @IsArray()
+ @ArrayNotEmpty()
+ @ArrayMaxSize(100)
+ @ValidateNested({ each: true })
+ @Type(() => RunAgentMessageInputDTO)
+ @Field(() => [RunAgentMessageInputDTO])
+ input: RunAgentMessageInputDTO[];
+
+ @IsOptional()
+ @IsString()
+ @IsNotEmpty()
+ @Field(() => String, { nullable: true })
+ instructions?: string | null;
+
+ @IsOptional()
+ @IsString()
+ @IsNotEmpty()
+ @Field(() => String, { nullable: true })
+ modelId?: string | null;
+
+ @IsOptional()
+ @Field(() => GraphQLJSON, { nullable: true })
+ responseFormat?: AgentResponseFormat | null;
+
+ @IsOptional()
+ @Field(() => GraphQLJSON, { nullable: true })
+ scope?: AiRunScope | null;
+
+ @IsOptional()
+ @IsUUID()
+ @Field(() => UUIDScalarType, { nullable: true })
+ runId?: string | null;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts
index 151d1b705cc..6cb911038e9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto.ts
@@ -10,6 +10,9 @@ export class RunAgentResultDTO implements RunAgentResult {
@Field(() => UUIDScalarType)
threadId: string;
+ @Field(() => UUIDScalarType)
+ runId: string;
+
@Field(() => String)
status: RunAgentResult['status'];
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 4c20d2f7060..9375815a687 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
@@ -22,9 +22,12 @@ import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { GenerateInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input';
+import { GenerateResultDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate-result.dto';
import { RunAgentInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent.input';
import { RunAgentResultDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/run-agent-result.dto';
import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';
+import { AiGenerateService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/ai-generate.service';
import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
@@ -51,7 +54,10 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt
@UsePipes(ResolverValidationPipe)
@MetadataResolver()
export class AgentRunResolver {
- constructor(private readonly agentRunService: AgentRunService) {}
+ constructor(
+ private readonly agentRunService: AgentRunService,
+ private readonly aiGenerateService: AiGenerateService,
+ ) {}
@Mutation(() => RunAgentResultDTO)
async runAgent(
@@ -74,4 +80,26 @@ export class AgentRunResolver {
input,
});
}
+
+ @Mutation(() => GenerateResultDTO)
+ async generate(
+ @Args('input') input: GenerateInputDTO,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @AuthApplication({ allowUndefined: true })
+ callerApplication: FlatApplication | undefined,
+ @AuthApiKey() callerApiKey: FlatApiKey | undefined,
+ @AuthWorkspaceMemberId()
+ workspaceMemberId: string | undefined,
+ ): Promise<GenerateResultDTO> {
+ return this.aiGenerateService.generate({
+ workspace,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ requestWorkspaceMemberId: workspaceMemberId ?? null,
+ callerApplication,
+ callerApiKey,
+ input,
+ });
+ }
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
index e1c9edcdb16..e760a1e46ff 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts
@@ -52,7 +52,6 @@ const buildService = ({ isCreated = true } = {}) => {
agentInboxService as never,
agentRunSuspensionService as never,
{} as never,
- {} as never,
);
return { service, agentInboxService, agentRunSuspensionService };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-job-scope.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-job-scope.service.spec.ts
index 2c4da2fa7d6..0b6cf0ea7d8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-job-scope.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-job-scope.service.spec.ts
@@ -22,8 +22,16 @@ const buildService = () => {
createEmptyFlatEntityMaps(),
);
+ const flatApplicationMaps = {
+ byId: {
+ 'application-c-id': { universalIdentifier: 'application-c' },
+ },
+ };
+
return new AgentRunJobScopeService({
- getOrRecompute: jest.fn().mockResolvedValue({ flatAgentMaps }),
+ getOrRecompute: jest
+ .fn()
+ .mockResolvedValue({ flatAgentMaps, flatApplicationMaps }),
} as never);
};
@@ -32,13 +40,19 @@ describe('AgentRunJobScopeService', () => {
const service = buildService();
await expect(
- service.resolve({ workspaceId: WORKSPACE_ID, agentId: 'agent-a' }),
+ service.resolve({
+ workspaceId: WORKSPACE_ID,
+ spec: { agentId: 'agent-a' },
+ }),
).resolves.toEqual({
workspaceId: WORKSPACE_ID,
applicationUniversalIdentifier: 'application-a',
});
await expect(
- service.resolve({ workspaceId: WORKSPACE_ID, agentId: 'agent-b' }),
+ service.resolve({
+ workspaceId: WORKSPACE_ID,
+ spec: { agentId: 'agent-b' },
+ }),
).resolves.toEqual({
workspaceId: WORKSPACE_ID,
applicationUniversalIdentifier: 'application-b',
@@ -49,7 +63,50 @@ describe('AgentRunJobScopeService', () => {
await expect(
buildService().resolve({
workspaceId: WORKSPACE_ID,
- agentId: 'deleted-agent',
+ spec: { agentId: 'deleted-agent' },
+ }),
+ ).resolves.toEqual({ workspaceId: WORKSPACE_ID, isWorkspaceJob: true });
+ });
+
+ it('scopes a run without an agent to the application it runs under', async () => {
+ const inlineConfig = {
+ instructions: 'Summarize the record.',
+ modelId: 'model-id',
+ modelConfiguration: null,
+ scope: null,
+ promptCacheKey: 'workflow-step:step-id',
+ };
+
+ await expect(
+ buildService().resolve({
+ workspaceId: WORKSPACE_ID,
+ spec: {
+ agentId: null,
+ inlineConfig: { ...inlineConfig, applicationId: 'application-c-id' },
+ },
+ }),
+ ).resolves.toEqual({
+ workspaceId: WORKSPACE_ID,
+ applicationUniversalIdentifier: 'application-c',
+ });
+ });
+
+ // like a deleted agent's, the run then fails resolving its persona
+ it('falls back to a workspace scope for an application that no longer exists', async () => {
+ await expect(
+ buildService().resolve({
+ workspaceId: WORKSPACE_ID,
+ spec: {
+ agentId: null,
+ inlineConfig: {
+ instructions: 'Summarize the record.',
+ modelId: 'model-id',
+ modelConfiguration: null,
+ scope: null,
+ promptCacheKey: 'workflow-step:step-id',
+ applicationId: 'deleted-application-id',
+ },
+ },
}),
).resolves.toEqual({ workspaceId: WORKSPACE_ID, isWorkspaceJob: true });
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-persona.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-persona.service.spec.ts
new file mode 100644
index 00000000000..cff673827b2
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-persona.service.spec.ts
@@ -0,0 +1,100 @@
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
+import { type AgentRunInlineConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+
+const WORKSPACE_ID = 'workspace-id';
+
+const INLINE_CONFIG: AgentRunInlineConfig = {
+ instructions: 'Summarize the record.',
+ modelId: 'model-id',
+ modelConfiguration: null,
+ scope: {},
+ promptCacheKey: 'workflow-step:step-id',
+ applicationId: 'application-id',
+};
+
+const buildService = (flatApplicationsById: Record<string, object>) =>
+ new AgentRunPersonaService(
+ {} as never,
+ {} as never,
+ {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ flatApplicationMaps: { byId: flatApplicationsById },
+ }),
+ } as never,
+ {} as never,
+ );
+
+describe('AgentRunPersonaService', () => {
+ it('runs a step without an agent under its application', async () => {
+ const persona = await buildService({
+ 'application-id': { id: 'application-id', deletedAt: null },
+ }).resolveOrThrow({
+ workspaceId: WORKSPACE_ID,
+ spec: { agentId: null, inlineConfig: INLINE_CONFIG },
+ });
+
+ expect(persona.applicationId).toBe('application-id');
+ expect(persona.permissions.scope).toEqual({});
+ });
+
+ it.each([
+ ['no longer exists', {}],
+ [
+ 'was deleted',
+ { 'application-id': { id: 'application-id', deletedAt: new Date() } },
+ ],
+ ])(
+ 'fails a step without an agent whose application %s',
+ async (_, flatApplicationsById) => {
+ await expect(
+ buildService(flatApplicationsById).resolveOrThrow({
+ workspaceId: WORKSPACE_ID,
+ spec: { agentId: null, inlineConfig: INLINE_CONFIG },
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });
+ },
+ );
+});
+
+describe('AgentRunPersonaService.resolveRolePermissionConfig', () => {
+ const service = buildService({});
+ const agentRunRoleIds = { applicationRoleId: 'application-role-id' };
+
+ it("narrows the agent's role to the run's roles", async () => {
+ expect(
+ await service.resolveRolePermissionConfig({
+ workspaceId: WORKSPACE_ID,
+ persona: {
+ permissions: {
+ agentRoleId: 'agent-role-id',
+ scope: null,
+ explicitObjectGrants: { objectPermissions: [] },
+ },
+ },
+ agentRunRoleIds,
+ }),
+ ).toEqual({
+ intersectionOf: {
+ applicationRoleId: 'application-role-id',
+ agentRoleId: 'agent-role-id',
+ },
+ });
+ });
+
+ it('reads nothing for a run handed no data access', async () => {
+ expect(
+ await service.resolveRolePermissionConfig({
+ workspaceId: WORKSPACE_ID,
+ persona: {
+ permissions: {
+ agentRoleId: null,
+ scope: null,
+ explicitObjectGrants: null,
+ },
+ },
+ agentRunRoleIds,
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.schedule-continuation.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.schedule-continuation.spec.ts
index cb7e3235da5..7b92a27ae7a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.schedule-continuation.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.schedule-continuation.spec.ts
@@ -6,10 +6,12 @@ const WORKSPACE_ID = 'workspace-id';
const buildService = (wakeUp: object | null) => {
const messageQueueService = { add: jest.fn().mockResolvedValue(undefined) };
const agentRunJobScopeService = {
- resolve: jest.fn(async ({ agentId }: { agentId: string }) => ({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: `application-of-${agentId}`,
- })),
+ resolve: jest.fn(
+ async ({ spec: { agentId } }: { spec: { agentId: string } }) => ({
+ workspaceId: WORKSPACE_ID,
+ applicationUniversalIdentifier: `application-of-${agentId}`,
+ }),
+ ),
};
const service = new AgentRunSuspensionService(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-turn.service.start-turn.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-turn.service.start-turn.spec.ts
new file mode 100644
index 00000000000..a397e211903
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-turn.service.start-turn.spec.ts
@@ -0,0 +1,103 @@
+import { type AgentResponseFormat, ToolCategory } from 'twenty-shared/ai';
+
+import { AgentRunTurnService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
+
+const JSON_RESPONSE_FORMAT: AgentResponseFormat = {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { answer: { type: 'string' } },
+ required: ['answer'],
+ },
+};
+
+const buildPersona = (
+ explicitObjectGrants: ResolvedAgentRunPersona['permissions']['explicitObjectGrants'],
+): ResolvedAgentRunPersona => ({
+ agentId: null,
+ applicationId: 'application-id',
+ instructions: 'Answer.',
+ modelId: 'model-id',
+ modelConfiguration: null,
+ responseFormat: null,
+ promptCacheKey: 'prompt-cache-key',
+ permissions: { agentRoleId: null, scope: null, explicitObjectGrants },
+});
+
+const startTurn = async (persona: ResolvedAgentRunPersona) => {
+ const startAgentTurn = jest.fn().mockResolvedValue({
+ stream: { stream: new ReadableStream() },
+ modelConfig: {},
+ });
+ const service = new AgentRunTurnService(
+ { start: startAgentTurn } as never,
+ {
+ assertAiExecutionAllowed: jest.fn().mockResolvedValue(undefined),
+ } as never,
+ {
+ resolveRolePermissionConfig: jest
+ .fn()
+ .mockResolvedValue({ intersectionOf: {} }),
+ } as never,
+ {} as never,
+ { findOneBy: jest.fn().mockResolvedValue(null) } as never,
+ );
+
+ const started = await service.startTurn({
+ persona,
+ responseFormat: JSON_RESPONSE_FORMAT,
+ messages: [{ role: 'user', content: 'Hi' }],
+ baseSystemPrompt: 'Base prompt.',
+ workspaceId: 'workspace-id',
+ executionContext: {
+ authContext: {} as never,
+ turnCreatedBy: {} as never,
+ userWorkspaceId: null,
+ },
+ });
+
+ return {
+ started,
+ output: startAgentTurn.mock.calls[0][0].output,
+ registryAccess: startAgentTurn.mock.calls[0][0].toolset.registryAccess,
+ };
+};
+
+describe('AgentRunTurnService.startTurn', () => {
+ it('asks for the structured output in the same request when the turn has no tools', async () => {
+ const { started, output } = await startTurn(buildPersona(null));
+
+ expect(started.isStructuredOutputInSameRequest).toBe(true);
+ expect(output).toBeDefined();
+ });
+
+ it('asks for the structured output in a follow-up request when the turn has tools', async () => {
+ const { started, output } = await startTurn(
+ buildPersona({ objectPermissions: [] }),
+ );
+
+ expect(started.isStructuredOutputInSameRequest).toBe(false);
+ expect(output).toBeUndefined();
+ });
+
+ it('offers a scoped run only database tools and the action tools its scope bounds', async () => {
+ const { registryAccess } = await startTurn({
+ ...buildPersona({ objectPermissions: [] }),
+ permissions: {
+ agentRoleId: null,
+ scope: { objectPermissions: [] },
+ explicitObjectGrants: { objectPermissions: [] },
+ },
+ });
+ const isOffered = (name: string, category: ToolCategory) =>
+ registryAccess.isToolOffered({ name, category });
+
+ expect(isOffered('find_many_people', ToolCategory.DATABASE_CRUD)).toBe(
+ true,
+ );
+ expect(isOffered('send_email', ToolCategory.ACTION)).toBe(true);
+ expect(isOffered('code_interpreter', ToolCategory.ACTION)).toBe(false);
+ expect(isOffered('send_campaign', ToolCategory.ACTION)).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
index c7bf07735c5..4149fef3198 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
@@ -1,5 +1,6 @@
import { type AgentResponseFormat } from 'twenty-shared/ai';
+import { AgentRunCallerContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service';
import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';
import {
AiException,
@@ -63,7 +64,11 @@ const buildService = (overrides: Record<string, unknown>) => {
{} as never,
{} as never,
{} as never,
- {} as never,
+ new AgentRunCallerContextService(
+ agentActorContextService as never,
+ {} as never,
+ {} as never,
+ ),
{} as never,
applicationLookupService as never,
agentRepository as never,
@@ -86,6 +91,35 @@ const runAgent = (service: AgentRunService) =>
});
describe('AgentRunService', () => {
+ describe('buildExecutionContext', () => {
+ it('reads the thread as the calling application when a run resumes', async () => {
+ const { service } = buildService({});
+
+ const executionContext = await service.buildExecutionContext({
+ workspaceId: WORKSPACE_ID,
+ caller: {
+ type: 'AGENT_API_RUN',
+ ref: {
+ agentId: AGENT_ID,
+ runAsWorkspaceMemberId: null,
+ requestUserWorkspaceId: null,
+ createdBy: {
+ source: 'APPLICATION',
+ name: APPLICATION.name,
+ workspaceMemberId: null,
+ context: { applicationId: APPLICATION_ID },
+ },
+ },
+ },
+ });
+
+ expect(executionContext.conversationViewer).toEqual({
+ workspaceMemberId: undefined,
+ applicationId: APPLICATION_ID,
+ });
+ });
+ });
+
describe('run', () => {
it('runs with the overridden label and response format', async () => {
const { service, agentRunnerService } = buildService({
@@ -105,6 +139,18 @@ describe('AgentRunService', () => {
);
});
+ it('returns the id of the turn the run opens', async () => {
+ const { service, agentRunnerService } = buildService({});
+
+ const { runId } = await runAgent(service);
+
+ expect(agentRunnerService.start).toHaveBeenCalledWith(
+ expect.objectContaining({
+ turnId: runId,
+ }),
+ );
+ });
+
it('rejects an overridden response format without output fields', async () => {
const { service, agentRunnerService } = buildService({
responseFormat: { type: 'json', schema: { type: 'object' } },
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.run-started.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.run-started.spec.ts
new file mode 100644
index 00000000000..aa32928f69c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.run-started.spec.ts
@@ -0,0 +1,126 @@
+import { Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { type RunAgentJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type';
+import { AGENT_TURN_INTERRUPTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+
+const JOB_DATA = {
+ workspaceId: 'workspace-id',
+ conversation: { threadId: 'thread-id', isCreated: true },
+ caller: { type: 'AGENT_API_RUN', ref: { runId: 'run-id' } },
+ spec: { agentId: 'agent-id', title: 'Follow up' },
+ turnId: 'run-id',
+ prompt: {
+ messages: [{ role: 'user', content: 'Follow up tomorrow' }],
+ senderUserWorkspaceId: null,
+ senderApplicationId: 'application-id',
+ },
+} as unknown as RunAgentJobData;
+
+const buildRunner = (recordedTurn: { status: AgentTurnStatus } | null) => {
+ const handler = {
+ getWaitingState: jest.fn().mockResolvedValue('WAITING'),
+ buildExecutionContext: jest.fn().mockResolvedValue({ authContext: {} }),
+ };
+ const agentRunConversationService = {
+ claimThread: jest.fn().mockResolvedValue(true),
+ openTurn: jest.fn().mockRejectedValue(new Error('Model unavailable')),
+ };
+ const agentRunSuspensionService = {
+ deliverOutcome: jest.fn().mockResolvedValue(undefined),
+ };
+ const turnRecorderService = {
+ findTurn: jest
+ .fn()
+ .mockResolvedValue(
+ isDefined(recordedTurn) ? { id: 'run-id', ...recordedTurn } : null,
+ ),
+ finish: jest.fn().mockResolvedValue(true),
+ };
+
+ const runner = new AgentRunnerService(
+ {} as never,
+ agentRunConversationService as never,
+ {} as never,
+ {} as never,
+ agentRunSuspensionService as never,
+ { getHandlerOrThrow: () => handler } as never,
+ {} as never,
+ {
+ runClaimed: ({
+ work,
+ }: {
+ work: (abortSignal: AbortSignal) => Promise<unknown>;
+ }) => work(new AbortController().signal),
+ } as never,
+ {} as never,
+ {} as never,
+ { shouldRunLegacyParkedCopy: jest.fn().mockResolvedValue(true) } as never,
+ {} as never,
+ {} as never,
+ {
+ resolveOrThrow: jest.fn().mockResolvedValue({ agentId: 'agent-id' }),
+ } as never,
+ turnRecorderService as never,
+ );
+
+ return {
+ runner,
+ agentRunConversationService,
+ agentRunSuspensionService,
+ turnRecorderService,
+ };
+};
+
+describe('AgentRunnerService runStarted on a stalled job retried with its run id', () => {
+ beforeEach(() => {
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
+ });
+
+ afterEach(() => jest.restoreAllMocks());
+
+ it('ends a turn its dead worker left running as interrupted, without running the agent again', async () => {
+ const {
+ runner,
+ agentRunConversationService,
+ agentRunSuspensionService,
+ turnRecorderService,
+ } = buildRunner({ status: AgentTurnStatus.RUNNING });
+
+ await runner.runStarted(JOB_DATA);
+
+ expect(agentRunConversationService.openTurn).not.toHaveBeenCalled();
+ expect(turnRecorderService.finish).toHaveBeenCalledTimes(1);
+ expect(turnRecorderService.finish).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ turnId: 'run-id',
+ status: AgentTurnStatus.FAILED,
+ error: AGENT_TURN_INTERRUPTED_ERROR,
+ });
+ expect(agentRunSuspensionService.deliverOutcome).toHaveBeenCalledTimes(1);
+ expect(agentRunSuspensionService.deliverOutcome).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ caller: JOB_DATA.caller,
+ threadId: 'thread-id',
+ outcome: {
+ status: 'FAILED',
+ error: AGENT_TURN_INTERRUPTED_ERROR.message,
+ },
+ summary: null,
+ });
+ });
+
+ it('opens the turn of a run that has not started yet with its run id', async () => {
+ const { runner, agentRunConversationService } = buildRunner(null);
+
+ await runner.runStarted(JOB_DATA);
+
+ expect(agentRunConversationService.openTurn).toHaveBeenCalledTimes(1);
+ expect(agentRunConversationService.openTurn).toHaveBeenCalledWith(
+ expect.objectContaining({ threadId: 'thread-id', turnId: 'run-id' }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
index cb565916eff..7c34c0a47f3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts
@@ -11,9 +11,7 @@ import { type ProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-a
import { findMissingRequiredToolArguments } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-missing-required-tool-arguments.util';
import { readProposedToolCallAnswer } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-proposed-tool-call-answer.util';
import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
-import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
-import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
@@ -32,7 +30,11 @@ const isThreadNotFoundError = (error: unknown) =>
type AgentCallerAwaitedToolCall = {
toolName: string;
arguments: Record<string, unknown>;
- caller: AgentRunCaller;
+ // the caller's own permissions, the ones the call is resolved and run with
+ permissions: Pick<
+ ToolContext,
+ 'authContext' | 'rolePermissionConfig' | 'application'
+ >;
// called before the call is posted, so its answer always finds the caller waiting
waitOnAnswer: (postedCall: {
threadId: string;
@@ -48,7 +50,6 @@ export class AgentCallerConversationService {
constructor(
private readonly agentInboxService: AgentInboxService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
- private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
private readonly toolRegistryService: ToolRegistryService,
) {}
@@ -258,25 +259,23 @@ export class AgentCallerConversationService {
);
}
- // resolved with the caller's permissions, the ones it acts with itself
private async buildPendingToolCall({
workspaceId,
- awaitedToolCall: { toolName, arguments: toolArguments, caller },
+ awaitedToolCall: {
+ toolName,
+ arguments: toolArguments,
+ permissions: { authContext, rolePermissionConfig, application },
+ },
summary,
}: {
workspaceId: string;
awaitedToolCall: AgentCallerAwaitedToolCall;
summary: string;
}) {
- const { authContext, rolePermissionConfig, application } =
- await this.callerHandlerRegistry
- .getHandlerOrThrow(caller.type)
- .buildExecutionContext({ workspaceId, caller });
-
const toolContext = {
workspaceId,
- rolePermissionConfig,
authContext,
+ rolePermissionConfig,
application,
} satisfies ToolContext;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service.ts
new file mode 100644
index 00000000000..81f65b5a348
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service.ts
@@ -0,0 +1,136 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
+import { ApiKeyService } from 'src/engine/core-modules/api-key/services/api-key.service';
+import { fromApiKeyEntityToFlat } from 'src/engine/core-modules/api-key/utils/from-api-key-entity-to-flat.util';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type ApplicationWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { buildApiKeyAuthContext } from 'src/engine/core-modules/auth/utils/build-api-key-auth-context.util';
+import { buildApplicationAuthContext } from 'src/engine/core-modules/auth/utils/build-application-auth-context.util';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { type AgentRunCallerContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type';
+import { type AgentRunCallerRef } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema';
+import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
+import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
+import { buildAgentRunTurnCreatedBy } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-turn-created-by.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';
+
+@Injectable()
+export class AgentRunCallerContextService {
+ constructor(
+ private readonly agentActorContextService: AgentActorContextService,
+ private readonly apiKeyService: ApiKeyService,
+ private readonly apiKeyRoleService: ApiKeyRoleService,
+ ) {}
+
+ async buildExecutionContext({
+ workspace,
+ callerRef,
+ requestUserWorkspaceId,
+ application,
+ callerApplication,
+ }: {
+ workspace: FlatWorkspace;
+ callerRef: AgentRunCallerRef;
+ requestUserWorkspaceId: string | null;
+ application: FlatApplication | undefined;
+ // differs from application when an application runs an agent of another one
+ callerApplication: FlatApplication | undefined;
+ }): Promise<AgentRunExecutionContext> {
+ const { authContext, actorContext, callerRoleIds } =
+ await this.buildCallerContextOrThrow({
+ workspace,
+ callerRef,
+ applicationAuthContext: isDefined(application)
+ ? buildApplicationAuthContext({ workspace, application })
+ : undefined,
+ });
+ const agentRunRoleIds: AgentRunRoleIds = {
+ ...callerRoleIds,
+ ...resolveApplicationRoleId({ application }),
+ };
+
+ return {
+ authContext,
+ actorContext,
+ turnCreatedBy: buildAgentRunTurnCreatedBy({
+ actorContext,
+ callerApplication,
+ authContext,
+ }),
+ userWorkspaceId: isUserAuthContext(authContext)
+ ? authContext.userWorkspaceId
+ : requestUserWorkspaceId,
+ agentRunRoleIds,
+ conversationViewer: {
+ workspaceMemberId: isUserAuthContext(authContext)
+ ? authContext.workspaceMemberId
+ : undefined,
+ applicationId: callerApplication?.id,
+ },
+ };
+ }
+
+ // the API key is looked up again, so a run continued after its revocation stops
+ private async buildCallerContextOrThrow({
+ workspace,
+ callerRef,
+ applicationAuthContext,
+ }: {
+ workspace: FlatWorkspace;
+ callerRef: AgentRunCallerRef;
+ applicationAuthContext?: ApplicationWorkspaceAuthContext;
+ }): Promise<AgentRunCallerContext> {
+ if (isDefined(callerRef.callerWorkspaceMemberId)) {
+ const { authContext, actorContext, roleId } =
+ await this.agentActorContextService.buildRunAsWorkspaceMemberContext({
+ workspaceMemberId: callerRef.callerWorkspaceMemberId,
+ workspaceId: workspace.id,
+ viaApplication: applicationAuthContext?.application,
+ });
+
+ return {
+ authContext,
+ actorContext,
+ callerRoleIds: { userWorkspaceRoleId: roleId },
+ };
+ }
+
+ if (isDefined(callerRef.callerApiKeyId)) {
+ const apiKey = await this.apiKeyService.validateApiKey(
+ callerRef.callerApiKeyId,
+ workspace.id,
+ );
+
+ return {
+ authContext: buildApiKeyAuthContext({
+ workspace,
+ apiKey: fromApiKeyEntityToFlat(apiKey),
+ }),
+ callerRoleIds: {
+ apiKeyRoleId: await this.apiKeyRoleService.getRoleIdForApiKeyId(
+ apiKey.id,
+ workspace.id,
+ ),
+ },
+ };
+ }
+
+ if (!isDefined(applicationAuthContext)) {
+ throw new AiException(
+ 'The call has no application to act as',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ return { authContext: applicationAuthContext, callerRoleIds: {} };
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
index 721f63b3c03..ff59ae66d3d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service.ts
@@ -80,6 +80,7 @@ export class AgentRunConversationService {
workspaceId,
threadId,
agentId,
+ turnId: requestedTurnId,
senderUserWorkspaceId,
senderApplicationId,
createdBy,
@@ -88,6 +89,7 @@ export class AgentRunConversationService {
workspaceId: string;
threadId: string;
agentId: string | null;
+ turnId?: string;
senderUserWorkspaceId: string | null;
senderApplicationId: string | null;
createdBy: ActorMetadata;
@@ -104,6 +106,7 @@ export class AgentRunConversationService {
workspaceId,
threadId,
agentId,
+ id: requestedTurnId,
status: AgentTurnStatus.RUNNING,
createdBy,
scope,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service.ts
index e39c48a4c81..19c2e983280 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service.ts
@@ -3,6 +3,7 @@ import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { type QueueJobScope } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
+import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -11,28 +12,61 @@ export class AgentRunJobScopeService {
constructor(private readonly workspaceCacheService: WorkspaceCacheService) {}
async resolve({
+ workspaceId,
+ spec,
+ }: {
+ workspaceId: string;
+ spec: Pick<AgentRunSpec, 'agentId' | 'inlineConfig'>;
+ }): Promise<QueueJobScope> {
+ const applicationUniversalIdentifier = isDefined(spec.agentId)
+ ? await this.findAgentApplicationUniversalIdentifier({
+ workspaceId,
+ agentId: spec.agentId,
+ })
+ : await this.findApplicationUniversalIdentifier({
+ workspaceId,
+ applicationId: spec.inlineConfig?.applicationId ?? null,
+ });
+
+ return isDefined(applicationUniversalIdentifier)
+ ? { workspaceId, applicationUniversalIdentifier }
+ : { workspaceId, isWorkspaceJob: true };
+ }
+
+ private async findAgentApplicationUniversalIdentifier({
workspaceId,
agentId,
}: {
workspaceId: string;
agentId: string;
- }): Promise<QueueJobScope> {
+ }): Promise<string | undefined> {
const { flatAgentMaps } = await this.workspaceCacheService.getOrRecompute(
workspaceId,
['flatAgentMaps'],
);
- const flatAgent = findFlatEntityByIdInFlatEntityMaps({
+ return findFlatEntityByIdInFlatEntityMaps({
flatEntityId: agentId,
flatEntityMaps: flatAgentMaps,
- });
+ })?.applicationUniversalIdentifier;
+ }
- return isDefined(flatAgent)
- ? {
- workspaceId,
- applicationUniversalIdentifier:
- flatAgent.applicationUniversalIdentifier,
- }
- : { workspaceId, isWorkspaceJob: true };
+ private async findApplicationUniversalIdentifier({
+ workspaceId,
+ applicationId,
+ }: {
+ workspaceId: string;
+ applicationId: string | null;
+ }): Promise<string | undefined> {
+ if (!isDefined(applicationId)) {
+ return undefined;
+ }
+
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+
+ return flatApplicationMaps.byId[applicationId]?.universalIdentifier;
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
index 035734e4e14..1e02cba5061 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
@@ -1,11 +1,14 @@
import { Injectable, type OnModuleInit } from '@nestjs/common';
+import { isDefined } from 'twenty-shared/utils';
+
import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-owner-handler-registry.service';
import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-outcome.type';
import { type PendingWakeUpOwnerHandler } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-handler.type';
import { type PendingWakeUpOwnerState } from 'src/engine/core-modules/pending-wake-up/types/pending-wake-up-owner-state.type';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
import { type AgentRunSuspension } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-suspension.type';
@@ -18,6 +21,7 @@ export class AgentRunPendingWakeUpHandlerService
private readonly pendingWakeUpOwnerHandlerRegistryService: PendingWakeUpOwnerHandlerRegistryService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
+ private readonly agentRunPersonaService: AgentRunPersonaService,
) {}
onModuleInit(): void {
@@ -38,17 +42,33 @@ export class AgentRunPendingWakeUpHandlerService
return status === 'NOT_READY' ? { status } : { status, owner: suspension };
}
- // the run reads what its caller lets it read
+ // the run reads what it acts with, so an event never shows it a record its tools could not read
async getReadPermissions({
wakeUp: { workspaceId },
- owner: { caller },
+ owner: { caller, runSpec },
}: {
wakeUp: PendingWakeUpEntity;
owner: AgentRunSuspension;
}) {
- return this.callerHandlerRegistry
- .getHandlerOrThrow(caller.type)
- .buildExecutionContext({ workspaceId, caller });
+ const [{ authContext, agentRunRoleIds }, persona] = await Promise.all([
+ this.callerHandlerRegistry
+ .getHandlerOrThrow(caller.type)
+ .buildExecutionContext({ workspaceId, caller }),
+ this.agentRunPersonaService.resolveOrThrow({
+ workspaceId,
+ spec: runSpec,
+ }),
+ ]);
+ const rolePermissionConfig =
+ await this.agentRunPersonaService.resolveRolePermissionConfig({
+ workspaceId,
+ persona,
+ agentRunRoleIds,
+ });
+
+ return isDefined(rolePermissionConfig)
+ ? { authContext, rolePermissionConfig }
+ : null;
}
// the run removes its wake-up once it went on, so the conversation waits until then
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service.ts
new file mode 100644
index 00000000000..7b07ba6fbd1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service.ts
@@ -0,0 +1,192 @@
+import { Injectable } from '@nestjs/common';
+
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
+import { type AgentRunPersonaSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
+import { buildRoleExplicitObjectGrants } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-role-explicit-object-grants.util';
+import { resolveAgentRunPersonaFromAgent } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-agent.util';
+import { resolveAgentRunPersonaFromInlineConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-inline-config.util';
+import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';
+import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { resolveEffectiveAgent } from 'src/engine/metadata-modules/flat-agent/utils/resolve-effective-agent.util';
+import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
+import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
+import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
+import { resolveAiRunPermissionScope } from 'src/engine/permissions/role/utils/resolve-ai-run-permission-scope.util';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@Injectable()
+export class AgentRunPersonaService {
+ constructor(
+ @InjectWorkspaceScopedRepository(AgentEntity)
+ private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
+ private readonly aiAgentRoleService: AiAgentRoleService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
+ ) {}
+
+ async resolveOrThrow({
+ workspaceId,
+ spec,
+ }: {
+ workspaceId: string;
+ spec: AgentRunPersonaSpec;
+ }): Promise<ResolvedAgentRunPersona> {
+ if (spec.agentId === null) {
+ await this.assertApplicationExistsOrThrow({
+ workspaceId,
+ applicationId: spec.inlineConfig.applicationId,
+ });
+
+ return resolveAgentRunPersonaFromInlineConfig(spec.inlineConfig);
+ }
+
+ const agent = await this.agentRepository.findOne(workspaceId, {
+ where: { id: spec.agentId },
+ });
+
+ if (!isDefined(agent)) {
+ throw new AiException(
+ `Agent with id ${spec.agentId} not found`,
+ AiExceptionCode.AGENT_NOT_FOUND,
+ );
+ }
+
+ const effectiveAgent = resolveEffectiveAgent(agent);
+
+ if (!effectiveAgent.isActive) {
+ const { label } = effectiveAgent;
+
+ throw new AiException(
+ `Agent "${label}" is archived`,
+ AiExceptionCode.AGENT_IS_INACTIVE,
+ { userFriendlyMessage: msg`Agent "${label}" is archived.` },
+ );
+ }
+
+ return resolveAgentRunPersonaFromAgent({
+ agent: effectiveAgent,
+ ...(await this.resolveAgentRoleGrants({
+ workspaceId,
+ agentId: effectiveAgent.id,
+ })),
+ });
+ }
+
+ // What the run reads and acts with, for its tools as for the records that wake it up. Null when it may read nothing
+ async resolveRolePermissionConfig({
+ workspaceId,
+ persona: {
+ permissions: { agentRoleId, scope, explicitObjectGrants },
+ },
+ agentRunRoleIds,
+ }: {
+ workspaceId: string;
+ persona: Pick<ResolvedAgentRunPersona, 'permissions'>;
+ agentRunRoleIds: AgentRunRoleIds | undefined;
+ }): Promise<RolePermissionConfig | null> {
+ if (!isDefined(explicitObjectGrants)) {
+ return null;
+ }
+
+ const intersectionOf = {
+ ...agentRunRoleIds,
+ ...(isDefined(agentRoleId) ? { agentRoleId } : {}),
+ };
+
+ if (!isDefined(scope)) {
+ return { intersectionOf };
+ }
+
+ const { flatObjectMetadataMaps, flatFieldMetadataMaps } =
+ await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
+ {
+ workspaceId,
+ flatMapsKeys: ['flatObjectMetadataMaps', 'flatFieldMetadataMaps'],
+ },
+ );
+
+ return {
+ intersectionOf,
+ scope: resolveAiRunPermissionScope({
+ scope,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ }),
+ };
+ }
+
+ // like a deleted agent, a deleted application fails the run rather than letting it act for the workspace
+ private async assertApplicationExistsOrThrow({
+ workspaceId,
+ applicationId,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ }): Promise<void> {
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+
+ const application = flatApplicationMaps.byId[applicationId];
+
+ if (!isDefined(application) || isDefined(application.deletedAt)) {
+ throw new AiException(
+ `Application with id ${applicationId} not found`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+ }
+
+ private async resolveAgentRoleGrants({
+ workspaceId,
+ agentId,
+ }: {
+ workspaceId: string;
+ agentId: string;
+ }): Promise<
+ Pick<
+ ResolvedAgentRunPersona['permissions'],
+ 'agentRoleId' | 'explicitObjectGrants'
+ >
+ > {
+ const agentRoleId = await this.aiAgentRoleService.findAgentRoleId({
+ workspaceId,
+ agentId,
+ });
+
+ if (!isDefined(agentRoleId)) {
+ return { agentRoleId: null, explicitObjectGrants: null };
+ }
+
+ const { flatObjectPermissionMaps, flatRoleMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectPermissionMaps',
+ 'flatRoleMaps',
+ ]);
+ const agentRole = findFlatEntityByIdInFlatEntityMaps({
+ flatEntityId: agentRoleId,
+ flatEntityMaps: flatRoleMaps,
+ });
+
+ return {
+ agentRoleId,
+ explicitObjectGrants: isDefined(agentRole)
+ ? buildRoleExplicitObjectGrants({
+ role: agentRole,
+ flatObjectPermissionMaps,
+ })
+ : { objectPermissions: [] },
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
index 11b27259db7..175a0fa13d6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts
@@ -173,7 +173,7 @@ export class AgentRunSuspensionService {
return this.agentRunJobScopeService.resolve({
workspaceId,
- agentId: suspension.runSpec.agentId,
+ spec: suspension.runSpec,
});
}
@@ -238,9 +238,13 @@ export class AgentRunSuspensionService {
return;
}
} catch (error) {
+ const threadLabel = isDefined(delivery.threadId)
+ ? ` in thread ${delivery.threadId}`
+ : '';
+
// the run already ended, so a failed delivery is tried again rather than lost with the job
this.logger.warn(
- `Could not deliver the outcome of the run in thread ${delivery.threadId} of workspace ${workspaceId}: ${formatErrorWithCause(error)}`,
+ `Could not deliver the outcome of the run${threadLabel} of workspace ${workspaceId}: ${formatErrorWithCause(error)}`,
);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts
index 656d01c1aba..d30f05ef546 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts
@@ -5,6 +5,8 @@ import {
convertToModelMessages,
generateText,
jsonSchema,
+ NoObjectGeneratedError,
+ NoOutputGeneratedError,
Output,
type TextStreamPart,
type ToolSet,
@@ -12,13 +14,11 @@ import {
import { type RunAgentMessage } from 'twenty-shared/application';
import {
type AgentResponseFormat,
+ type AgentResponseSchema,
type ExtendedUIMessage,
+ ToolCategory,
} from 'twenty-shared/ai';
-import {
- isDefined,
- isNonEmptyArray,
- tipTapDocumentToMarkdown,
-} from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
import { type Repository } from 'typeorm';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
@@ -32,7 +32,9 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent
import { AGENT_RUN_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const';
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 { PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const';
+import { SCOPED_AGENT_RUN_ACTION_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/scoped-agent-run-action-tool-names.const';
import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util';
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
import { type AgentRegistryAccess } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service';
import {
type AgentTurn,
@@ -41,15 +43,13 @@ import {
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 AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-tool-loading-strategy.type';
import { assertAgentResponseFormatHasOutputFieldsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/assert-agent-response-format-has-output-fields-or-throw.util';
-import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
import { buildStrictAgentResponseSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-strict-agent-response-schema.util';
import { getCallLevelProviderOptions } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/provider-options.util';
import { replaceUnsupportedFileParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/replace-unsupported-file-parts.util';
-import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';
import { STRUCTURED_OUTPUT_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/structured-output-system-prompt.const';
-import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { NATIVE_WEB_SEARCH_COST_PER_CALL_DOLLARS } from 'src/engine/metadata-modules/ai/ai-billing/constants/native-web-search-cost-per-call-dollars';
import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
import { type AgentTurnUsageStep } from 'src/engine/metadata-modules/ai/ai-billing/utils/add-step-to-agent-turn-usage.util';
@@ -65,7 +65,7 @@ import {
} from 'src/engine/metadata-modules/ai/ai.exception';
type AgentRunTurnInput = {
- agent: AgentEntity;
+ persona: ResolvedAgentRunPersona;
responseFormat?: AgentResponseFormat;
messages: RunAgentMessage[];
// a continued conversation, with the tool calls and results plain run messages cannot carry
@@ -83,20 +83,27 @@ type AgentRunTurnInput = {
export type StartedAgentRunTurn = {
turn: AgentTurn;
source: AgentTurnStreamSource;
+ // some models refuse a JSON response format alongside tools, so only a turn without any asks for it upfront
+ isStructuredOutputInSameRequest: boolean;
};
export type CompletedAgentRunTurn = AgentExecutionResult & {
- // the structured output request is not part of the stream, so the turn's usage must add it
+ // a follow-up structured output request is not part of the stream, so the turn's usage must add it
structuredOutputSteps: AgentTurnUsageStep[];
};
+const buildStructuredOutput = (schema: AgentResponseSchema) =>
+ Output.object({
+ schema: jsonSchema(buildStrictAgentResponseSchema(schema)),
+ });
+
const buildSpenders = ({
- agent,
+ persona,
executionContext,
-}: Pick<AgentRunTurnInput, 'agent' | 'executionContext'>): UsageSpenders => ({
+}: Pick<AgentRunTurnInput, 'persona' | 'executionContext'>): UsageSpenders => ({
userWorkspaceId: executionContext.userWorkspaceId,
- agentId: agent.id,
- applicationId: agent.applicationId,
+ agentId: persona.agentId,
+ applicationId: persona.applicationId,
});
@Injectable()
@@ -104,14 +111,14 @@ export class AgentRunTurnService {
constructor(
private readonly agentTurnService: AgentTurnService,
private readonly aiBillingService: AiBillingService,
- private readonly aiAgentRoleService: AiAgentRoleService,
+ private readonly agentRunPersonaService: AgentRunPersonaService,
private readonly runAgentAttachmentService: RunAgentAttachmentService,
@InjectRepository(WorkspaceEntity)
private readonly workspaceRepository: Repository<WorkspaceEntity>,
) {}
async startTurn({
- agent,
+ persona,
responseFormat,
messages,
baseSystemPrompt,
@@ -133,12 +140,12 @@ export class AgentRunTurnService {
assertAgentResponseFormatHasOutputFieldsOrThrow(responseFormat);
- const { userWorkspaceId, usageOperationType } = executionContext;
- const spenders = buildSpenders({ agent, executionContext });
+ const { userWorkspaceId } = executionContext;
+ const spenders = buildSpenders({ persona, executionContext });
await this.aiBillingService.assertAiExecutionAllowed({
workspaceId,
- operationType: usageOperationType,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
spenders,
});
@@ -146,27 +153,35 @@ export class AgentRunTurnService {
id: workspaceId,
});
const registryAccess = await this.buildAgentRegistryAccess({
- agent,
+ persona,
+ workspaceId,
executionContext,
additionalExcludedToolNames,
toolLoadingStrategy,
});
+ const hasTools =
+ registryAccess.type !== 'none' ||
+ canAskHumans ||
+ isNonEmptyArray(Object.keys(pausingTools)) ||
+ (persona.modelConfiguration?.webSearch?.enabled ?? false) ||
+ (persona.modelConfiguration?.twitterSearch?.enabled ?? false);
+
const turn = await this.agentTurnService.start({
workspace: workspace ?? undefined,
- modelId: agent.modelId,
+ modelId: persona.modelId,
toolset: {
registryAccess,
nativeToolOptions: {
- webSearch: agent.modelConfiguration?.webSearch?.enabled === true,
+ webSearch: persona.modelConfiguration?.webSearch?.enabled ?? false,
twitterSearch:
- agent.modelConfiguration?.twitterSearch?.enabled === true,
+ persona.modelConfiguration?.twitterSearch?.enabled ?? false,
},
canAskHumans,
waitTools: pausingTools,
},
buildContext: async ({ modelConfig, toolset }) => ({
- systemPrompt: `${baseSystemPrompt}\n\n${tipTapDocumentToMarkdown(agent.prompt)}${
+ systemPrompt: `${baseSystemPrompt}\n\n${persona.instructions}${
registryAccess.type === 'catalog'
? buildToolCatalogSection(toolset.toolCatalog, [])
: ''
@@ -186,11 +201,15 @@ export class AgentRunTurnService {
})),
],
}),
- promptCacheKey: agent.id,
+ promptCacheKey: persona.promptCacheKey,
+ output:
+ !hasTools && responseFormat?.type === 'json'
+ ? buildStructuredOutput(responseFormat.schema)
+ : undefined,
abortSignal,
billing: {
workspaceId,
- operationType: usageOperationType,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
webSearchOperationType: UsageOperationType.AI_WORKFLOW_WEB_SEARCH,
spenders,
},
@@ -198,7 +217,7 @@ export class AgentRunTurnService {
functionId: 'agent-execution',
workspaceId,
userWorkspaceId,
- agentId: agent.id,
+ agentId: persona.agentId ?? undefined,
},
// nobody resends a background run, so a provider error after streaming started is retried here
streamRetries: 2,
@@ -227,20 +246,21 @@ export class AgentRunTurnService {
modelConfig: turn.modelConfig,
getStreamError: () => streamError,
},
+ isStructuredOutputInSameRequest: !hasTools,
};
}
- // the structured output request is not part of the stream, so its usage is added to the turn's here
+ // a follow-up structured output request is not part of the stream, so its usage is added to the turn's here
async completeTurn({
- started: { turn },
- agent,
+ started: { turn, isStructuredOutputInSameRequest },
+ persona,
responseFormat,
workspaceId,
executionContext,
abortSignal,
}: Pick<
AgentRunTurnInput,
- | 'agent'
+ | 'persona'
| 'responseFormat'
| 'workspaceId'
| 'executionContext'
@@ -248,8 +268,8 @@ export class AgentRunTurnService {
> & {
started: StartedAgentRunTurn;
}): Promise<CompletedAgentRunTurn> {
- const { userWorkspaceId, usageOperationType } = executionContext;
- const spenders = buildSpenders({ agent, executionContext });
+ const { userWorkspaceId } = executionContext;
+ const spenders = buildSpenders({ persona, executionContext });
const [text, loopUsage, loopSteps] = await Promise.all([
turn.stream.text,
turn.stream.usage,
@@ -269,7 +289,13 @@ export class AgentRunTurnService {
let steps = loopSteps;
let structuredOutputSteps: AgentTurnUsageStep[] = [];
- if (isDefined(agentSchema) && !isPaused) {
+ // a stopped run fails whatever it returned, so it spends no request on its output
+ const isStructuredOutputExpected =
+ isDefined(agentSchema) && !isPaused && !isDefined(stopReason);
+
+ if (isStructuredOutputExpected && isStructuredOutputInSameRequest) {
+ result = await this.readSameRequestOutputOrThrow(turn);
+ } else if (isStructuredOutputExpected) {
const structuredResult = await generateText({
instructions: STRUCTURED_OUTPUT_SYSTEM_PROMPT,
model: registeredModel.model,
@@ -278,20 +304,18 @@ export class AgentRunTurnService {
Execution Results: ${text}
Please generate the structured output based on the execution results and context above.`,
- output: Output.object({
- schema: jsonSchema(buildStrictAgentResponseSchema(agentSchema)),
- }),
+ output: buildStructuredOutput(agentSchema),
abortSignal,
providerOptions: getCallLevelProviderOptions({
sdkPackage: registeredModel.sdkPackage,
providerOptions: undefined,
- promptCacheKey: agent.id,
+ promptCacheKey: persona.promptCacheKey,
}),
...buildAiTelemetry({
functionId: 'agent-structured-output',
workspaceId,
userWorkspaceId,
- agentId: agent.id,
+ agentId: persona.agentId ?? undefined,
}),
});
@@ -304,7 +328,7 @@ export class AgentRunTurnService {
),
},
workspaceId,
- operationType: usageOperationType,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
spenders,
});
@@ -343,37 +367,75 @@ export class AgentRunTurnService {
};
}
+ private async readSameRequestOutputOrThrow(
+ turn: Pick<AgentTurn, 'stream'>,
+ ): Promise<object> {
+ let formatError: unknown;
+ const output: unknown = await Promise.resolve(turn.stream.output).catch(
+ (error: unknown) => {
+ // only a reply that parses into no object is a format failure; anything else keeps its own cause
+ if (
+ NoObjectGeneratedError.isInstance(error) ||
+ NoOutputGeneratedError.isInstance(error)
+ ) {
+ formatError = error;
+
+ return undefined;
+ }
+
+ throw error;
+ },
+ );
+
+ if (!isPlainObject(output)) {
+ // the generation error keeps the text the model returned, which a failed parse is diagnosed from
+ throw Object.assign(
+ new AiException(
+ 'The model did not return an object matching the response format',
+ AiExceptionCode.AGENT_EXECUTION_FAILED,
+ ),
+ { cause: formatError },
+ );
+ }
+
+ return output;
+ }
+
private async buildAgentRegistryAccess({
- agent,
+ persona,
+ workspaceId,
executionContext: { authContext, actorContext, agentRunRoleIds },
additionalExcludedToolNames,
toolLoadingStrategy,
}: Pick<
Required<AgentRunTurnInput>,
- | 'agent'
+ | 'persona'
+ | 'workspaceId'
| 'executionContext'
| 'additionalExcludedToolNames'
| 'toolLoadingStrategy'
>): Promise<AgentRegistryAccess> {
- const agentRoleId = await this.aiAgentRoleService.findAgentRoleId({
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- });
+ const rolePermissionConfig =
+ await this.agentRunPersonaService.resolveRolePermissionConfig({
+ workspaceId,
+ persona,
+ agentRunRoleIds,
+ });
- if (!isDefined(agentRoleId)) {
+ if (
+ !isDefined(rolePermissionConfig) ||
+ !isDefined(persona.permissions.explicitObjectGrants)
+ ) {
return { type: 'none' };
}
const toolContext: ToolContext = {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
+ workspaceId,
+ agentId: persona.agentId ?? undefined,
authContext,
application: getAuthContextApplication(authContext),
actorContext,
- rolePermissionConfig: buildAgentRolePermissionConfig({
- agentRoleId,
- agentRunRoleIds,
- }),
+ rolePermissionConfig,
...(isDefined(authContext) && isUserAuthContext(authContext)
? {
userId: authContext.user.id,
@@ -387,8 +449,10 @@ export class AgentRunTurnService {
...additionalExcludedToolNames,
];
+ const isScoped = isDefined(persona.permissions.scope);
+
// open-ended agents reach too many tools to send them all; a few granted ones are cheaper sent than learned
- return toolLoadingStrategy === 'lazy'
+ return toolLoadingStrategy === 'lazy' && !isScoped
? {
type: 'catalog',
toolContext,
@@ -398,9 +462,13 @@ export class AgentRunTurnService {
: {
type: 'granted',
toolContext,
- agentRoleId,
+ explicitObjectGrants: persona.permissions.explicitObjectGrants,
categories: PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES,
- excludedToolNames,
+ isToolOffered: ({ name, category }) =>
+ !excludedToolNames.includes(name) &&
+ (!isScoped ||
+ category === ToolCategory.DATABASE_CRUD ||
+ SCOPED_AGENT_RUN_ACTION_TOOL_NAMES.has(name)),
};
}
}
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 55f5ad1ba76..d4e30b1cf8e 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
@@ -13,51 +13,40 @@ import {
type RunAgentResult,
type RunAgentThread,
} from 'twenty-shared/application';
-import { type AgentResponseFormat } from 'twenty-shared/ai';
import { type ActorMetadata } from 'twenty-shared/types';
import { isDefined, isPlainObject } from 'twenty-shared/utils';
import { agentResponseFormatSchema } from 'twenty-shared/workflow';
import { z } from 'zod';
-import { buildActorMetadataFromAuthContext } from 'src/engine/core-modules/actor/utils/build-actor-metadata-from-auth-context.util';
-import { buildCreatedByFromApplication } from 'src/engine/core-modules/actor/utils/build-created-by-from-application.util';
import { ApiKeyException } from 'src/engine/core-modules/api-key/exceptions/api-key.exception';
-import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
import { ApiKeyService } from 'src/engine/core-modules/api-key/services/api-key.service';
import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-key.type';
-import { fromApiKeyEntityToFlat } from 'src/engine/core-modules/api-key/utils/from-api-key-entity-to-flat.util';
import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';
+import { type ApplicationCallerOperation } from 'src/engine/core-modules/application/types/application-caller-operation.type';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { canCallerReachApplication } from 'src/engine/core-modules/application/utils/can-caller-reach-application.util';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
-import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import {
- type ApplicationWorkspaceAuthContext,
- type UserWorkspaceAuthContext,
-} from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { buildApiKeyAuthContext } from 'src/engine/core-modules/auth/utils/build-api-key-auth-context.util';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UserWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { AgentRunCallerContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { assertAgentResponseFormatHasOutputFieldsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/assert-agent-response-format-has-output-fields-or-throw.util';
import { RUN_AGENT_MAX_WAIT_MS } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/run-agent-max-wait-ms.const';
import { AgentRunSettlementService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-settlement.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
-import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';
-import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
-import { type AgentRunCallerContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type';
import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
+import { agentRunCallerRefSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema';
import { type AgentRunCallerInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type';
import { type AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type';
import { type OwnerWaitingState } from 'src/engine/core-modules/pending-wake-up/types/owner-waiting-state.type';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
-import { type RunAsWorkspaceMemberContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/run-as-workspace-member-context.type';
import { type SettledAgentRun } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/settled-agent-run.type';
-import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';
+import { parseAgentInputOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util';
+import { resolveAgentRunCallerRefOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-caller-ref-or-throw.util';
import { resolveRunAgentMessagesOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util';
import { AGENT_RUN_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/agent-run-base-system-prompt.const';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
@@ -70,6 +59,10 @@ import {
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+type CallingApplication = NonNullable<
+ ApplicationCallerOperation['callingApplication']
+>;
+
type RunAgentServiceInput = {
agentUniversalIdentifier: string;
input?: RunAgentMessage[] | null;
@@ -82,14 +75,11 @@ type RunAgentServiceInput = {
waitForCompletion?: boolean | null;
};
-const agentApiRunCallerRefSchema = z.object({
+const agentApiRunCallerRefSchema = agentRunCallerRefSchema.extend({
// what a call waiting on the run listens to; absent on runs suspended before calls could wait
runId: z.string().optional(),
agentId: z.string(),
runAsWorkspaceMemberId: z.string().nullable(),
- // who a run that names no member acts as, when it is not the agent's application
- callerWorkspaceMemberId: z.string().optional(),
- callerApiKeyId: z.string().optional(),
requestUserWorkspaceId: z.string().nullable(),
// the request's own actor cannot be read back once it is over
createdBy: z.custom<ActorMetadata>(isPlainObject),
@@ -113,7 +103,7 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
private readonly agentRunSettlementService: AgentRunSettlementService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
- private readonly apiKeyRoleService: ApiKeyRoleService,
+ private readonly agentRunCallerContextService: AgentRunCallerContextService,
private readonly apiKeyService: ApiKeyService,
private readonly applicationLookupService: ApplicationLookupService,
@InjectWorkspaceScopedRepository(AgentEntity)
@@ -154,13 +144,6 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
const thread = input.thread ?? null;
- if (isDefined(thread) && !isDefined(callerApplication)) {
- throw new AiException(
- 'Continuing a conversation requires an application access token',
- AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
- );
- }
-
if (
isDefined(thread) &&
messages.some((message) => message.role !== 'user')
@@ -171,23 +154,18 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
);
}
- const responseFormat = this.parseResponseFormatOrThrow(
- input.responseFormat,
- );
-
- const agentRow = await this.agentRepository.findOne(workspace.id, {
- where: {
- universalIdentifier: input.agentUniversalIdentifier,
- },
+ const responseFormat = parseAgentInputOrThrow({
+ schema: agentResponseFormatSchema.nullish(),
+ input: input.responseFormat,
+ label: 'response format',
});
- if (!isDefined(agentRow)) {
- throw new NotFoundException(
- `Agent ${input.agentUniversalIdentifier} not found`,
- );
- }
-
- const agent = resolveEffectiveAgent(agentRow);
+ const agent = await this.findCallerAgentOrThrow({
+ workspace,
+ callerApplication,
+ agentUniversalIdentifier: input.agentUniversalIdentifier,
+ operation: 'trigger',
+ });
if (!agent.isActive) {
throw new AiException(
@@ -196,20 +174,6 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
);
}
- if (
- !canCallerReachApplication({
- callingApplication: callerApplication,
- applicationId: agent.applicationId,
- operation: 'trigger',
- workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
- })
- ) {
- throw new AiException(
- `Agent ${input.agentUniversalIdentifier} belongs to another application`,
- AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
- );
- }
-
const application = await this.applicationLookupService.findById({
id: agent.applicationId,
workspaceId: workspace.id,
@@ -221,19 +185,16 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
);
}
- const runAsContext = await this.resolveRunAsContext({
+ this.assertCanRunAsWorkspaceMemberOrThrow({
runAsWorkspaceMemberId: input.runAsWorkspaceMemberId,
callerApplication,
requestUserWorkspaceId,
requestWorkspaceMemberId,
- workspaceId: workspace.id,
- application,
});
- // keyed by the caller, so an application never continues another one's conversation with a shared agent
const threadId = isDefined(thread)
- ? buildAgentRunThreadId({
- applicationId: callerApplication?.id ?? application.id,
+ ? this.buildCallerThreadIdOrThrow({
+ callerApplication,
agentId: agent.id,
threadKey: thread.key,
})
@@ -242,9 +203,9 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
const callerRef: AgentApiRunCallerRef = {
agentId: agent.id,
runAsWorkspaceMemberId: input.runAsWorkspaceMemberId ?? null,
- ...(isDefined(runAsContext)
+ ...(isDefined(input.runAsWorkspaceMemberId)
? {}
- : this.resolveCallerRef({
+ : resolveAgentRunCallerRefOrThrow({
callerApplication,
callerApiKey,
requestUserWorkspaceId,
@@ -253,9 +214,11 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
requestUserWorkspaceId,
};
- const executionContext = await this.buildRunExecutionContext({
- workspaceId: workspace.id,
+ const executionContext = await this.buildCallerExecutionContext({
+ workspace,
ref: callerRef,
+ application,
+ callerApplication,
});
const memberUserWorkspaceId = isUserAuthContext(
@@ -264,10 +227,6 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
? executionContext.authContext.userWorkspaceId
: null;
- const createdBy =
- executionContext.actorContext ??
- this.buildRunCreator({ callerApplication, application });
-
const isContinuingConversation = isDefined(thread);
// a conversation waiting on an earlier run refuses the call, rather than a run that fails later
@@ -302,7 +261,11 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
conversation: { threadId, isCreated: !isContinuingConversation },
caller: {
type: 'AGENT_API_RUN',
- ref: { ...callerRef, runId, createdBy },
+ ref: {
+ ...callerRef,
+ runId,
+ createdBy: executionContext.turnCreatedBy,
+ },
},
spec: {
agentId: agent.id,
@@ -317,6 +280,7 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
},
toolLoadingStrategy: 'lazy',
},
+ turnId: runId,
prompt: {
messages,
senderUserWorkspaceId: memberUserWorkspaceId,
@@ -325,7 +289,7 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
});
if (input.waitForCompletion === false) {
- return this.buildRunAgentResult({ threadId, status: 'RUNNING' });
+ return this.buildRunAgentResult({ threadId, runId, status: 'RUNNING' });
}
const settledRun = await this.agentRunSettlementService.waitFor({
@@ -335,10 +299,101 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
return this.buildRunAgentResult({
threadId,
+ runId,
...(settledRun ?? { status: 'RUNNING' }),
});
}
+ async resolveConversationThreadIdOrThrow({
+ workspace,
+ callerApplication,
+ agentUniversalIdentifier,
+ threadKey,
+ }: {
+ workspace: Pick<FlatWorkspace, 'id' | 'workspaceCustomApplicationId'>;
+ callerApplication: CallingApplication;
+ agentUniversalIdentifier: string;
+ threadKey: string;
+ }): Promise<string> {
+ const agent = await this.findCallerAgentOrThrow({
+ workspace,
+ callerApplication,
+ agentUniversalIdentifier,
+ operation: 'read',
+ });
+
+ return this.buildCallerThreadIdOrThrow({
+ callerApplication,
+ agentId: agent.id,
+ threadKey,
+ });
+ }
+
+ private async findCallerAgentOrThrow({
+ workspace,
+ callerApplication,
+ agentUniversalIdentifier,
+ operation,
+ }: {
+ workspace: Pick<FlatWorkspace, 'id' | 'workspaceCustomApplicationId'>;
+ callerApplication: CallingApplication | undefined;
+ agentUniversalIdentifier: string;
+ operation: 'read' | 'trigger';
+ }) {
+ const agentRow = await this.agentRepository.findOne(workspace.id, {
+ where: { universalIdentifier: agentUniversalIdentifier },
+ });
+
+ if (!isDefined(agentRow)) {
+ throw new AiException(
+ `Agent ${agentUniversalIdentifier} not found`,
+ AiExceptionCode.AGENT_NOT_FOUND,
+ );
+ }
+
+ const agent = resolveEffectiveAgent(agentRow);
+
+ if (
+ !canCallerReachApplication({
+ callingApplication: callerApplication,
+ applicationId: agent.applicationId,
+ operation,
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
+ })
+ ) {
+ throw new AiException(
+ `Agent ${agentUniversalIdentifier} belongs to another application`,
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ return agent;
+ }
+
+ // keyed by the caller, so an application never reaches another one's conversation with a shared agent
+ private buildCallerThreadIdOrThrow({
+ callerApplication,
+ agentId,
+ threadKey,
+ }: {
+ callerApplication: Pick<FlatApplication, 'id'> | undefined;
+ agentId: string;
+ threadKey: string;
+ }): string {
+ if (!isDefined(callerApplication)) {
+ throw new AiException(
+ 'Continuing a conversation requires an application access token',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ return buildAgentRunThreadId({
+ applicationId: callerApplication.id,
+ agentId,
+ threadKey,
+ });
+ }
+
private async claimThreadForMember({
threadId,
authContext,
@@ -425,13 +480,15 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
private buildRunAgentResult({
threadId,
+ runId,
status,
result = null,
error = null,
- }: Pick<RunAgentResult, 'threadId' | 'status'> &
+ }: Pick<RunAgentResult, 'threadId' | 'runId' | 'status'> &
Partial<Pick<RunAgentResult, 'result' | 'error'>>): RunAgentResult {
return {
threadId,
+ runId,
status,
result,
error,
@@ -445,21 +502,6 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
caller,
}: AgentRunCallerInput): Promise<AgentRunExecutionContext> {
const ref = agentApiRunCallerRefSchema.parse(caller.ref);
-
- return {
- ...(await this.buildRunExecutionContext({ workspaceId, ref })),
- turnCreatedBy: ref.createdBy,
- };
- }
-
- // run() builds the context before its caller, whose turn author depends on it
- private async buildRunExecutionContext({
- workspaceId,
- ref,
- }: {
- workspaceId: string;
- ref: AgentApiRunCallerRef;
- }): Promise<Omit<AgentRunExecutionContext, 'turnCreatedBy'>> {
const agent = await this.agentRepository.findOne(workspaceId, {
where: { id: ref.agentId },
});
@@ -477,54 +519,47 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
);
}
- const runAsContext = isDefined(ref.runAsWorkspaceMemberId)
- ? await this.agentActorContextService.buildRunAsWorkspaceMemberContext({
- workspaceMemberId: ref.runAsWorkspaceMemberId,
- workspaceId,
- viaApplication: agentContext.application,
- })
- : undefined;
-
- const { authContext, actorContext, callerRoleIds }: AgentRunCallerContext =
- isDefined(runAsContext)
- ? {
- authContext: runAsContext.authContext,
- actorContext: runAsContext.actorContext,
- callerRoleIds: { userWorkspaceRoleId: runAsContext.roleId },
- }
- : await this.resolveCallerContext({
- workspaceId,
- ref,
- agentAuthContext: agentContext.authContext,
- });
-
- const memberWorkspaceMemberId = isUserAuthContext(authContext)
- ? authContext.workspaceMemberId
- : null;
-
- // a run never exceeds the agent's application, whoever calls it
- const agentRunRoleIds: AgentRunRoleIds = {
- ...callerRoleIds,
- ...resolveApplicationRoleId({ application: agentContext.application }),
- };
+ const executionContext = await this.buildCallerExecutionContext({
+ workspace: agentContext.authContext.workspace,
+ ref,
+ application: agentContext.application,
+ callerApplication: undefined,
+ });
+ // the calling application is kept on the run's author, so a resumed run reads the thread as it did
return {
- authContext,
- actorContext,
- userWorkspaceId:
- runAsContext?.authContext.userWorkspaceId ?? ref.requestUserWorkspaceId,
- rolePermissionConfig: buildAgentRolePermissionConfig({
- agentRoleId: agentContext.agentRoleId,
- agentRunRoleIds,
- }),
- agentRunRoleIds,
- conversationActor: isDefined(memberWorkspaceMemberId)
- ? { type: 'user', workspaceMemberId: memberWorkspaceMemberId }
- : { type: 'application', applicationId: agentContext.application.id },
- usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ ...executionContext,
+ turnCreatedBy: ref.createdBy,
+ conversationViewer: {
+ workspaceMemberId:
+ executionContext.conversationViewer?.workspaceMemberId,
+ applicationId: ref.createdBy.context?.applicationId,
+ },
};
}
+ private buildCallerExecutionContext({
+ workspace,
+ ref,
+ application,
+ callerApplication,
+ }: {
+ workspace: FlatWorkspace;
+ ref: AgentApiRunCallerRef;
+ application: FlatApplication;
+ callerApplication: FlatApplication | undefined;
+ }): Promise<AgentRunExecutionContext> {
+ return this.agentRunCallerContextService.buildExecutionContext({
+ workspace,
+ callerRef: isDefined(ref.runAsWorkspaceMemberId)
+ ? { callerWorkspaceMemberId: ref.runAsWorkspaceMemberId }
+ : ref,
+ requestUserWorkspaceId: ref.requestUserWorkspaceId,
+ application,
+ callerApplication,
+ });
+ }
+
async getWaitingState({
workspaceId,
caller,
@@ -584,117 +619,20 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
}
}
- private resolveCallerRef({
- callerApplication,
- callerApiKey,
- requestUserWorkspaceId,
- requestWorkspaceMemberId,
- }: {
- callerApplication?: FlatApplication;
- callerApiKey?: FlatApiKey;
- requestUserWorkspaceId: string | null;
- requestWorkspaceMemberId: string | null;
- }): Pick<AgentApiRunCallerRef, 'callerWorkspaceMemberId' | 'callerApiKeyId'> {
- if (isDefined(requestWorkspaceMemberId)) {
- return { callerWorkspaceMemberId: requestWorkspaceMemberId };
- }
-
- if (isDefined(callerApplication) && !isDefined(requestUserWorkspaceId)) {
- return {};
- }
-
- if (isDefined(callerApiKey)) {
- return { callerApiKeyId: callerApiKey.id };
- }
-
- throw new AiException(
- 'Running an agent requires a workspace member, an API key or the agent application',
- AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
- );
- }
-
- private async resolveCallerContext({
- workspaceId,
- ref,
- agentAuthContext,
- }: {
- workspaceId: string;
- ref: AgentApiRunCallerRef;
- agentAuthContext: ApplicationWorkspaceAuthContext;
- }): Promise<AgentRunCallerContext> {
- if (isDefined(ref.callerWorkspaceMemberId)) {
- const { authContext, actorContext, roleId } =
- await this.agentActorContextService.buildRunAsWorkspaceMemberContext({
- workspaceMemberId: ref.callerWorkspaceMemberId,
- workspaceId,
- viaApplication: agentAuthContext.application,
- });
-
- return {
- authContext,
- actorContext,
- callerRoleIds: { userWorkspaceRoleId: roleId },
- };
- }
-
- if (isDefined(ref.callerApiKeyId)) {
- const apiKey = await this.apiKeyService.validateApiKey(
- ref.callerApiKeyId,
- workspaceId,
- );
-
- return {
- authContext: buildApiKeyAuthContext({
- workspace: agentAuthContext.workspace,
- apiKey: fromApiKeyEntityToFlat(apiKey),
- }),
- callerRoleIds: {
- apiKeyRoleId: await this.apiKeyRoleService.getRoleIdForApiKeyId(
- apiKey.id,
- workspaceId,
- ),
- },
- };
- }
-
- return { authContext: agentAuthContext };
- }
-
- private buildRunCreator({
- callerApplication,
- application,
- }: {
- callerApplication?: FlatApplication;
- application: FlatApplication;
- }): ActorMetadata {
- if (isDefined(callerApplication)) {
- return buildCreatedByFromApplication({ application: callerApplication });
- }
-
- const requestAuthContext = workspaceAuthContextStorage.getStore();
-
- return isDefined(requestAuthContext)
- ? buildActorMetadataFromAuthContext(requestAuthContext)
- : buildCreatedByFromApplication({ application });
- }
-
- private async resolveRunAsContext({
+ // the member itself is resolved with the run's execution context
+ private assertCanRunAsWorkspaceMemberOrThrow({
runAsWorkspaceMemberId,
callerApplication,
requestUserWorkspaceId,
requestWorkspaceMemberId,
- workspaceId,
- application,
}: {
runAsWorkspaceMemberId?: string;
callerApplication?: FlatApplication;
requestUserWorkspaceId: string | null;
requestWorkspaceMemberId: string | null;
- workspaceId: string;
- application: FlatApplication;
- }): Promise<RunAsWorkspaceMemberContext | undefined> {
+ }): void {
if (!isDefined(runAsWorkspaceMemberId)) {
- return undefined;
+ return;
}
if (!isDefined(callerApplication)) {
@@ -713,34 +651,5 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_ALLOWED,
);
}
-
- return this.agentActorContextService.buildRunAsWorkspaceMemberContext({
- workspaceMemberId: runAsWorkspaceMemberId,
- workspaceId,
- viaApplication: application,
- });
- }
-
- // the resolver runs no validation pipe, so the format is checked here before it reaches the model
- private parseResponseFormatOrThrow(
- responseFormat: unknown,
- ): AgentResponseFormat | undefined {
- if (!isDefined(responseFormat)) {
- return undefined;
- }
-
- const parsedResponseFormat =
- agentResponseFormatSchema.safeParse(responseFormat);
-
- if (!parsedResponseFormat.success) {
- throw new AiException(
- `Invalid response format: ${parsedResponseFormat.error.issues
- .map((issue) => issue.message)
- .join(', ')}`,
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
-
- return parsedResponseFormat.data;
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
index 292d9143fde..1d84607e5cc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
@@ -1,8 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
+import { randomUUID } from 'node:crypto';
+
import { isNonEmptyString } from '@sniptt/guards';
import { generateId } from 'ai';
-import { type AgentRunSummary } from 'twenty-shared/ai';
+import { type AgentRunSummary, type ExtendedUIMessage } from 'twenty-shared/ai';
import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
import { isDefined } from 'twenty-shared/utils';
@@ -16,25 +18,28 @@ import { RUN_AGENT_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-exec
import { AGENT_WAIT_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-prompt.constant';
import { createAgentWaitTools } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/create-agent-wait-tools.util';
import { findAgentRunWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/find-agent-run-wait.util';
+import { AGENT_RUN_STOPPED_ERROR } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stopped-error.constant';
+import { AGENT_RUN_OUT_OF_CREDITS_ERROR } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-out-of-credits-error.const';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
import { AgentRunJobScopeService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-job-scope.service';
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
import { AgentRunTurnService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service';
+import { AGENT_TURN_INTERRUPTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { addStepToAgentTurnUsage } from 'src/engine/metadata-modules/ai/ai-billing/utils/add-step-to-agent-turn-usage.util';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
+import { type InRequestAgentRun } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/in-request-agent-run.type';
import { type AgentRunSuspension } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-suspension.type';
import { type ContinueAgentRunJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type';
import { type AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type';
import { type RunAgentJobData } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type';
import { buildAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-summary.util';
import { sumAgentRunSummaries } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/sum-agent-run-summaries.util';
-import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
-import { resolveEffectiveAgent } from 'src/engine/metadata-modules/flat-agent/utils/resolve-effective-agent.util';
import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
import {
type AgentChatStreamClaim,
@@ -44,13 +49,9 @@ import { AgentChatWaitingRunService } from 'src/engine/metadata-modules/ai/ai-ch
import { AgentTurnStreamService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service';
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
+import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
import { withDedicatedAiTrace } from 'src/engine/metadata-modules/ai/ai-models/utils/with-dedicated-ai-trace.util';
-import {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
const AGENT_RUN_MAX_CONTINUATIONS = 50;
@@ -67,6 +68,11 @@ type AgentRunnerResult = {
summary: AgentRunSummary;
};
+type OpenedAgentRunTurn = {
+ turnId: string;
+ priorMessages: ExtendedUIMessage[];
+};
+
@Injectable()
export class AgentRunnerService {
private readonly logger = new Logger(AgentRunnerService.name);
@@ -75,6 +81,7 @@ export class AgentRunnerService {
private readonly agentRunTurnService: AgentRunTurnService,
private readonly agentRunConversationService: AgentRunConversationService,
private readonly conversationReaderService: AgentConversationReaderService,
+ private readonly conversationWriterService: AgentConversationWriterService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
private readonly pendingWakeUpService: PendingWakeUpService,
@@ -85,27 +92,88 @@ export class AgentRunnerService {
private readonly agentRunJobScopeService: AgentRunJobScopeService,
@InjectMessageQueue(MessageQueue.aiQueue)
private readonly messageQueueService: MessageQueueService,
- @InjectWorkspaceScopedRepository(AgentEntity)
- private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
+ private readonly agentRunPersonaService: AgentRunPersonaService,
+ private readonly turnRecorderService: AgentTurnRecorderService,
) {}
async start(input: RunAgentJobData): Promise<void> {
await this.messageQueueService.add<RunAgentJobData>(
RUN_AGENT_JOB_NAME,
- input,
+ { ...input, turnId: input.turnId ?? randomUUID() },
await this.agentRunJobScopeService.resolve({
workspaceId: input.workspaceId,
- agentId: input.spec.agentId,
+ spec: input.spec,
}),
);
}
+ // a failure after the turn is recorded comes back as the outcome, so the caller still gets the run id
+ async runInRequest({
+ streamChannelId,
+ ...input
+ }: Omit<AgentRunnerRunInput, 'conversation' | 'caller' | 'persona'> & {
+ streamChannelId?: string;
+ }): Promise<InRequestAgentRun> {
+ const persona = await this.agentRunPersonaService.resolveOrThrow({
+ workspaceId: input.workspaceId,
+ spec: input.spec,
+ });
+ const runInput: AgentRunnerRunInput = {
+ ...input,
+ conversation: null,
+ caller: null,
+ persona,
+ };
+
+ return workspaceAuthContextStorage.run(
+ input.executionContext.authContext,
+ async () => {
+ const openedTurn = await this.openTurn({
+ input: runInput,
+ suspension: null,
+ });
+ const { turnId } = openedTurn;
+ const outcome = await this.runOpenedTurn({
+ input: runInput,
+ suspension: null,
+ stream: null,
+ streamChannelId,
+ openedTurn,
+ }).then(
+ (result): AgentRunnerOutcome => result.outcome,
+ (error: unknown): AgentRunnerOutcome => {
+ this.logger.error(
+ `Agent run ${turnId} of workspace ${input.workspaceId} failed`,
+ error instanceof Error ? error.stack : error,
+ );
+
+ return {
+ status: 'FAILED',
+ error: error instanceof Error ? error.message : String(error),
+ };
+ },
+ );
+
+ return {
+ runId: turnId,
+ outcome,
+ usage: await this.turnRecorderService.findUsageOrThrow({
+ workspaceId: input.workspaceId,
+ turnId,
+ }),
+ };
+ },
+ );
+ }
+
async runStarted(jobData: RunAgentJobData): Promise<void> {
const { workspaceId, conversation, caller, parkId } = jobData;
+ const threadId = conversation?.threadId ?? null;
if (
+ isDefined(threadId) &&
!(await this.waitingRunService.shouldRunLegacyParkedCopy({
- threadId: conversation.threadId,
+ threadId,
parkId,
}))
) {
@@ -119,7 +187,7 @@ export class AgentRunnerService {
await this.agentRunSuspensionService.deliverOutcome({
workspaceId,
caller,
- threadId: conversation.threadId,
+ threadId,
outcome: {
status: 'FAILED',
error: 'The caller stopped waiting before the run started',
@@ -130,22 +198,39 @@ export class AgentRunnerService {
return;
}
- const result = await this.runClaimedOrDeliverFailure({ jobData, handler });
+ const result = await this.runOrDeliverFailure({ jobData, handler });
if (!isDefined(result)) {
return;
}
+ if (result !== CONVERSATION_BUSY && result.outcome.status !== 'SUSPENDED') {
+ await this.agentRunSuspensionService.deliverOutcome({
+ workspaceId,
+ caller,
+ threadId,
+ outcome: result.outcome,
+ summary: result.summary,
+ });
+
+ return;
+ }
+
+ // only a run holding a conversation finds it busy or pauses in it
+ if (!isDefined(threadId)) {
+ return;
+ }
+
if (result === CONVERSATION_BUSY) {
await this.waitingRunService.wait({
workspaceId,
- threadId: conversation.threadId,
+ threadId,
run: {
jobName: RUN_AGENT_JOB_NAME,
jobData: { ...jobData, parkId: undefined },
scope: await this.agentRunJobScopeService.resolve({
workspaceId,
- agentId: jobData.spec.agentId,
+ spec: jobData.spec,
}),
},
});
@@ -153,71 +238,99 @@ export class AgentRunnerService {
return;
}
- if (result.outcome.status === 'SUSPENDED') {
- await this.showSuspension({
- workspaceId,
- caller,
- threadId: conversation.threadId,
- summary: result.summary,
- });
-
- return;
- }
-
- await this.agentRunSuspensionService.deliverOutcome({
+ await this.showSuspension({
workspaceId,
caller,
- threadId: conversation.threadId,
- outcome: result.outcome,
+ threadId,
summary: result.summary,
});
}
// a run that fails before it settles is delivered as failed here, so null means nothing is left to do
- private async runClaimedOrDeliverFailure({
- jobData: { workspaceId, conversation, caller, spec, prompt },
+ private async runOrDeliverFailure({
+ jobData: { workspaceId, conversation, turnId, caller, spec, prompt },
handler,
}: {
jobData: RunAgentJobData;
handler: AgentRunCallerHandler;
}): Promise<AgentRunnerResult | typeof CONVERSATION_BUSY | null> {
try {
- const [executionContext, agent] = await Promise.all([
+ const [executionContext, persona] = await Promise.all([
handler.buildExecutionContext({ workspaceId, caller }),
- this.findAgentOrThrow({ workspaceId, agentId: spec.agentId }),
+ this.agentRunPersonaService.resolveOrThrow({ workspaceId, spec }),
]);
+ const run = async (
+ stream: AgentRunStream | null,
+ ): Promise<AgentRunnerResult | null> => {
+ const retriedTurn = isDefined(turnId)
+ ? await this.turnRecorderService.findTurn({ workspaceId, turnId })
+ : null;
+
+ // a stalled job's retry must not act twice; a waiting run goes on through its wake-up
+ if (isDefined(retriedTurn)) {
+ if (retriedTurn.status === AgentTurnStatus.RUNNING) {
+ await this.turnRecorderService.finish({
+ workspaceId,
+ turnId: retriedTurn.id,
+ status: AgentTurnStatus.FAILED,
+ error: AGENT_TURN_INTERRUPTED_ERROR,
+ });
+ }
- return await this.withClaimedConversation({
- workspaceId,
- threadId: conversation.threadId,
- title: spec.title,
- work: (stream) =>
- workspaceAuthContextStorage.run(executionContext.authContext, () =>
+ if (retriedTurn.status !== AgentTurnStatus.WAITING_FOR_INPUT) {
+ await this.agentRunSuspensionService.deliverOutcome({
+ workspaceId,
+ caller,
+ threadId: conversation?.threadId ?? null,
+ outcome: {
+ status: 'FAILED',
+ error: AGENT_TURN_INTERRUPTED_ERROR.message,
+ },
+ summary: null,
+ });
+ }
+
+ return null;
+ }
+
+ return workspaceAuthContextStorage.run(
+ executionContext.authContext,
+ () =>
this.runTurn({
input: {
workspaceId,
conversation,
+ turnId,
caller,
spec,
- agent,
+ persona,
prompt,
executionContext,
},
suspension: null,
stream,
}),
- ),
- });
+ );
+ };
+
+ return isDefined(conversation)
+ ? await this.withClaimedConversation({
+ workspaceId,
+ threadId: conversation.threadId,
+ title: spec.title,
+ work: run,
+ })
+ : await run(null);
} catch (error) {
this.logger.error(
- `Agent run in thread ${conversation.threadId} of workspace ${workspaceId} failed`,
+ `Agent run in thread ${conversation?.threadId ?? 'none'} of workspace ${workspaceId} failed`,
error instanceof Error ? error.stack : error,
);
await this.agentRunSuspensionService.deliverOutcome({
workspaceId,
caller,
- threadId: conversation.threadId,
+ threadId: conversation?.threadId ?? null,
outcome: {
status: 'FAILED',
error: error instanceof Error ? error.message : String(error),
@@ -294,7 +407,7 @@ export class AgentRunnerService {
jobData: { ...jobData, parkId: undefined },
scope: await this.agentRunJobScopeService.resolve({
workspaceId,
- agentId: suspension.runSpec.agentId,
+ spec: suspension.runSpec,
}),
},
});
@@ -415,8 +528,11 @@ export class AgentRunnerService {
});
}
- const [agent, executionContext] = await Promise.all([
- this.findAgentOrThrow({ workspaceId, agentId: runSpec.agentId }),
+ const [persona, executionContext] = await Promise.all([
+ this.agentRunPersonaService.resolveOrThrow({
+ workspaceId,
+ spec: runSpec,
+ }),
handler.buildExecutionContext({ workspaceId, caller }),
]);
@@ -429,7 +545,7 @@ export class AgentRunnerService {
conversation: { threadId, isCreated: false },
caller,
spec: runSpec,
- agent,
+ persona,
prompt: null,
executionContext,
},
@@ -476,74 +592,55 @@ export class AgentRunnerService {
private async runTurn({
input,
suspension,
- stream: { claim, abortSignal },
+ stream,
}: {
input: AgentRunnerRunInput;
// what a continued run resumes from
suspension: AgentRunSuspension | null;
- stream: AgentRunStream;
+ // null for a run without a conversation, which streams to no one
+ stream: AgentRunStream | null;
}): Promise<AgentRunnerResult> {
- const {
- workspaceId,
- conversation: { threadId, isCreated },
- spec,
- agent,
- prompt,
- executionContext,
- } = input;
-
- if (!isCreated && !isDefined(suspension)) {
- await this.agentRunSuspensionService.assertConversationNotSuspended({
- workspaceId,
- threadId,
- });
- }
-
- const { turnId, promptMessageIds, hasTakenQueuedMessages } =
- await this.agentRunConversationService.openTurn({
- workspaceId,
- threadId,
- agentId: agent.id,
- senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,
- senderApplicationId: prompt?.senderApplicationId ?? null,
- createdBy: executionContext.turnCreatedBy,
- messages: prompt?.messages ?? [],
- });
-
- if (hasTakenQueuedMessages) {
- await this.eventPublisherService.publish({
- workspaceId,
- threadId,
- event: { type: 'queue-updated' },
- });
- }
+ return this.runOpenedTurn({
+ input,
+ suspension,
+ stream,
+ openedTurn: await this.openTurn({ input, suspension }),
+ });
+ }
- // read once the turn is open, so it holds the messages the turn took, while its prompt goes to the model as is
- const conversationMessages =
- await this.conversationReaderService.loadMessages({
- workspaceId,
- threadId,
- actor: executionContext.conversationActor,
- });
- const priorMessages = conversationMessages.filter(
- ({ id }) => !promptMessageIds.includes(id),
- );
+ private async runOpenedTurn({
+ input,
+ suspension,
+ stream,
+ streamChannelId,
+ openedTurn: { turnId, priorMessages },
+ }: {
+ input: AgentRunnerRunInput;
+ suspension: AgentRunSuspension | null;
+ stream: AgentRunStream | null;
+ streamChannelId?: string;
+ openedTurn: OpenedAgentRunTurn;
+ }): Promise<AgentRunnerResult> {
+ const { workspaceId, spec, persona, prompt, executionContext } = input;
+ const abortSignal = stream?.abortSignal;
+ const canPause = isDefined(stream);
const startedAtMs = Date.now();
const turnInput = {
- agent,
+ persona,
messages: prompt?.messages ?? [],
priorMessages,
// every run here goes on in the background, unlike a chat, so it can wait. The wait tools are
// the engine's, so it explains them; the caller's own instructions come last
baseSystemPrompt: [
spec.baseSystemPrompt,
- AGENT_WAIT_PROMPT,
+ ...(canPause ? [AGENT_WAIT_PROMPT] : []),
...(isNonEmptyString(spec.instructions) ? [spec.instructions] : []),
].join('\n\n'),
- pausingTools: createAgentWaitTools(),
- canAskHumans: spec.capabilities.canAskHumans,
- responseFormat: spec.responseFormat ?? agent.responseFormat,
+ pausingTools: canPause ? createAgentWaitTools() : {},
+ canAskHumans: canPause && spec.capabilities.canAskHumans,
+ responseFormat:
+ spec.responseFormat ?? persona.responseFormat ?? undefined,
workspaceId,
executionContext,
additionalExcludedToolNames: spec.additionalExcludedToolNames,
@@ -553,12 +650,13 @@ export class AgentRunnerService {
// the toolset and prompt come from the spec alone, so a continued run gets those it paused with
const {
- streamed,
- completion: { execution, wait },
+ completion: { execution, wait, isAborted },
finish,
} = await withDedicatedAiTrace(() =>
this.turnStreamService.streamTurn({
- claim,
+ workspaceId,
+ claim: stream?.claim ?? null,
+ streamChannelId,
turnId,
abortSignal,
startTurn: () => this.agentRunTurnService.startTurn(turnInput),
@@ -576,10 +674,13 @@ export class AgentRunnerService {
execution.steps[execution.steps.length - 1]?.toolResults ?? [],
)
: undefined;
+ // a stop can land after the stream ended; read once so the turn and its caller agree
+ const isAborted = streamed.isAborted || abortSignal?.aborted === true;
return {
execution,
wait,
+ isAborted,
modelId: execution.modelId,
stopReason: execution.stopReason,
isWaiting: isDefined(wait),
@@ -610,30 +711,112 @@ export class AgentRunnerService {
return {
summary,
- // a stop can also land while the structured output is asked for, after the stream ended
- outcome:
- streamed.isAborted || abortSignal.aborted
- ? { status: 'FAILED', error: 'The run was stopped' }
- : await this.settleTurn({
- input,
- execution,
- wait,
- isAwaitingAnswer: finish?.isAwaitingAnswer ?? false,
- summary,
- suspension,
- streamId: claim.streamId,
- }),
+ outcome: isAborted
+ ? { status: 'FAILED', error: AGENT_RUN_STOPPED_ERROR }
+ : await this.settleTurn({
+ input,
+ execution,
+ wait,
+ isAwaitingAnswer: finish?.isAwaitingAnswer ?? false,
+ summary,
+ suspension,
+ stream,
+ }),
+ };
+ }
+
+ private async openTurn({
+ input: {
+ workspaceId,
+ conversation,
+ turnId,
+ persona,
+ prompt,
+ executionContext,
+ },
+ suspension,
+ }: {
+ input: Pick<
+ AgentRunnerRunInput,
+ | 'workspaceId'
+ | 'conversation'
+ | 'turnId'
+ | 'persona'
+ | 'prompt'
+ | 'executionContext'
+ >;
+ suspension: AgentRunSuspension | null;
+ }): Promise<OpenedAgentRunTurn> {
+ if (!isDefined(conversation)) {
+ return {
+ turnId: await this.conversationWriterService.insertTurn({
+ workspaceId,
+ id: turnId,
+ threadId: null,
+ agentId: persona.agentId,
+ status: AgentTurnStatus.RUNNING,
+ createdBy: executionContext.turnCreatedBy,
+ }),
+ priorMessages: [],
+ };
+ }
+
+ const { threadId, isCreated } = conversation;
+
+ if (!isCreated && !isDefined(suspension)) {
+ await this.agentRunSuspensionService.assertConversationNotSuspended({
+ workspaceId,
+ threadId,
+ });
+ }
+
+ const {
+ turnId: openedTurnId,
+ promptMessageIds,
+ hasTakenQueuedMessages,
+ } = await this.agentRunConversationService.openTurn({
+ workspaceId,
+ threadId,
+ agentId: persona.agentId,
+ turnId,
+ senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,
+ senderApplicationId: prompt?.senderApplicationId ?? null,
+ createdBy: executionContext.turnCreatedBy,
+ messages: prompt?.messages ?? [],
+ });
+
+ if (hasTakenQueuedMessages) {
+ await this.eventPublisherService.publish({
+ workspaceId,
+ threadId,
+ event: { type: 'queue-updated' },
+ });
+ }
+
+ // read once the turn is open, so it holds the messages the turn took, while its prompt goes to the model as is
+ const conversationMessages =
+ await this.conversationReaderService.loadMessages({
+ workspaceId,
+ threadId,
+ viewer: executionContext.conversationViewer,
+ });
+
+ return {
+ turnId: openedTurnId,
+ priorMessages: conversationMessages.filter(
+ ({ id }) => !promptMessageIds.includes(id),
+ ),
};
}
private async settleTurn({
- input: { workspaceId, conversation, caller, spec },
+ input: { workspaceId, caller, spec },
execution,
wait,
isAwaitingAnswer,
summary,
suspension,
- streamId,
+ stream,
}: {
input: AgentRunnerRunInput;
execution: AgentExecutionResult;
@@ -641,13 +824,18 @@ export class AgentRunnerService {
isAwaitingAnswer: boolean;
summary: AgentRunSummary;
suspension: AgentRunSuspension | null;
- streamId: string;
+ stream: AgentRunStream | null;
}): Promise<AgentRunnerOutcome> {
if (!isDefined(execution.stopReason) && !execution.isPaused) {
return { status: 'COMPLETED', result: execution.result };
}
- const { threadId } = conversation;
+ // offered no way to pause, a run without a conversation or a caller stops early only when out of credits
+ if (!isDefined(stream) || !isDefined(caller)) {
+ return { status: 'FAILED', error: AGENT_RUN_OUT_OF_CREDITS_ERROR };
+ }
+
+ const { threadId, streamId } = stream.claim;
const continuationCount = isDefined(suspension)
? suspension.continuationCount + 1
: 0;
@@ -708,7 +896,7 @@ export class AgentRunnerService {
if (isDefined(execution.stopReason)) {
return {
status: 'FAILED',
- error: 'Agent stopped: no more available credits.',
+ error: AGENT_RUN_OUT_OF_CREDITS_ERROR,
};
}
@@ -727,36 +915,6 @@ export class AgentRunnerService {
};
}
- private async findAgentOrThrow({
- workspaceId,
- agentId,
- }: {
- workspaceId: string;
- agentId: string;
- }): Promise<AgentEntity> {
- const agent = await this.agentRepository.findOne(workspaceId, {
- where: { id: agentId },
- });
-
- if (!isDefined(agent)) {
- throw new AiException(
- `Agent with id ${agentId} not found`,
- AiExceptionCode.AGENT_NOT_FOUND,
- );
- }
-
- const effectiveAgent = resolveEffectiveAgent(agent);
-
- if (!effectiveAgent.isActive) {
- throw new AiException(
- `Agent "${effectiveAgent.label}" is archived`,
- AiExceptionCode.AGENT_IS_INACTIVE,
- );
- }
-
- return effectiveAgent;
- }
-
// A record of the run, not its outcome, so a write failure must not fail the run
private async tryRecording<TResult>(
description: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-step-loop.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-step-loop.service.ts
index 7189a35c956..761c4c6663c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-step-loop.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-step-loop.service.ts
@@ -1,10 +1,11 @@
import { Injectable, Logger } from '@nestjs/common';
-import { type ProviderOptions } from '@ai-sdk/provider-utils';
+import { type Context, type ProviderOptions } from '@ai-sdk/provider-utils';
import {
isStepCount,
type ModelMessage,
NoOutputGeneratedError,
+ type OutputInterface,
type StepResult,
type StopCondition,
streamText,
@@ -52,6 +53,8 @@ import {
// chat and agent runs report to their own metric keys, so existing dashboards keep their series
type AgentStepLoopMetricsScope = 'chat' | 'agent';
+type AgentStepLoopOutput = OutputInterface<unknown, unknown, never>;
+
type ToolMetricKeys = {
succeeded: MetricsKeys;
failed: MetricsKeys;
@@ -97,6 +100,7 @@ export type AgentStepLoopInput = {
messages: ModelMessage[];
tools: ToolSet;
toolChoice?: 'auto' | 'required';
+ output?: AgentStepLoopOutput;
abortSignal?: AbortSignal;
offeredPausingToolNames: string[];
shouldStopAfterStep?: StopCondition<ToolSet>;
@@ -119,7 +123,7 @@ export type AgentStepLoopInput = {
};
export type AgentStepLoop = {
- stream: ReturnType<typeof streamText<ToolSet>>;
+ stream: ReturnType<typeof streamText<ToolSet, Context, AgentStepLoopOutput>>;
getStopReason: () => StepDebitResult['stopReason'];
};
@@ -152,6 +156,7 @@ export class AgentStepLoopService {
messages,
tools,
toolChoice = 'auto',
+ output,
abortSignal,
offeredPausingToolNames,
shouldStopAfterStep,
@@ -250,12 +255,13 @@ export class AgentStepLoopService {
providerOptions: getCacheProviderOptions(modelConfig),
};
- const stream = streamText({
+ const stream = streamText<ToolSet, Context, AgentStepLoopOutput>({
model: registeredModel.model,
instructions: [systemMessage, ...contextMessages],
messages,
tools,
toolChoice,
+ output,
abortSignal,
streamRetries,
stopWhen: async (step) =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
index ddcc6585b2e..33ef1788367 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
@@ -22,6 +22,7 @@ import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/to
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { buildToolNotAvailableOutput } from 'src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util';
import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
import { createProposeToolCallTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/tools/propose-tool-call.tool';
import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
@@ -45,13 +46,12 @@ export type AgentRegistryAccess =
categories: readonly ToolCategory[];
excludedToolNames: readonly string[];
}
- // an agent limited to the objects it was granted, whose few tools are sent with the turn
| {
type: 'granted';
toolContext: ToolContext;
- agentRoleId: string;
+ explicitObjectGrants: ExplicitObjectGrants;
categories: readonly ToolCategory[];
- excludedToolNames: readonly string[];
+ isToolOffered: (tool: ToolIndexEntry) => boolean;
}
| { type: 'none' };
@@ -245,11 +245,11 @@ export class AgentToolsetService {
const directTools = await this.toolRegistry.getToolsByCategories(
{
...toolContext,
- explicitObjectGrantsRoleId: registryAccess.agentRoleId,
+ explicitObjectGrants: registryAccess.explicitObjectGrants,
},
{
categories: [...registryAccess.categories],
- excludeTools: new Set(registryAccess.excludedToolNames),
+ isToolOffered: registryAccess.isToolOffered,
},
);
// the context lacks the explicit grants the tools were built with, so calls stay within them
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/ai-generate.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/ai-generate.service.ts
new file mode 100644
index 00000000000..5524e084e20
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/ai-generate.service.ts
@@ -0,0 +1,194 @@
+import { Injectable } from '@nestjs/common';
+
+import { randomUUID } from 'node:crypto';
+
+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
+import {
+ generateJsonFieldsSchema,
+ type GenerateResult,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-key.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AgentRunCallerContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-context.service';
+import { type GenerateInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input';
+import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { buildAgentRunStreamChannelId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util';
+import { assertAgentResponseFormatHasOutputFieldsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/assert-agent-response-format-has-output-fields-or-throw.util';
+import { parseAgentInputOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util';
+import { readGeneratedOutputOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/read-generated-output-or-throw.util';
+import { resolveRunAgentMessagesOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util';
+import { resolveAgentRunCallerRefOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-caller-ref-or-throw.util';
+import { AGENT_RUN_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/agent-run-base-system-prompt.const';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { type AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
+import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+const buildRunAlreadyExistsException = (runId: string) =>
+ new AiException(
+ `Run ${runId} already exists; pass a new runId`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+
+@Injectable()
+export class AiGenerateService {
+ constructor(
+ private readonly agentRunCallerContextService: AgentRunCallerContextService,
+ private readonly agentRunnerService: AgentRunnerService,
+ @InjectAgentHistoryRepository('agentTurn')
+ private readonly turnRepository: AgentHistoryRepository<AgentTurnWorkspaceEntity>,
+ ) {}
+
+ async generate({
+ workspace,
+ requestUserWorkspaceId,
+ requestWorkspaceMemberId,
+ callerApplication,
+ callerApiKey,
+ input,
+ }: {
+ workspace: FlatWorkspace;
+ requestUserWorkspaceId: string | null;
+ requestWorkspaceMemberId: string | null;
+ callerApplication?: FlatApplication;
+ callerApiKey?: FlatApiKey;
+ input: GenerateInputDTO;
+ }): Promise<GenerateResult> {
+ const messages = resolveRunAgentMessagesOrThrow({ input: input.input });
+ const jsonFields = parseAgentInputOrThrow({
+ schema: generateJsonFieldsSchema,
+ input: { responseFormat: input.responseFormat, scope: input.scope },
+ });
+ const responseFormat = jsonFields.responseFormat ?? undefined;
+ const requestedRunId = input.runId ?? undefined;
+
+ assertAgentResponseFormatHasOutputFieldsOrThrow(responseFormat);
+
+ // the application's role is the ceiling of what its generate may reach, so it cannot run without one. The AI
+ // guard refuses other roleless applications first; an OAuth-only one acting with its member's role gets here
+ if (
+ isDefined(callerApplication) &&
+ !isDefined(callerApplication.defaultRoleId)
+ ) {
+ throw new AiException(
+ 'ai.generate needs a default role on the application; declare one with defineApplicationRole()',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ const streamChannelId = isDefined(requestedRunId)
+ ? await this.resolveStreamChannelIdOrThrow({
+ workspaceId: workspace.id,
+ callerApplication,
+ callerWorkspaceMemberId: requestWorkspaceMemberId,
+ runId: requestedRunId,
+ })
+ : undefined;
+
+ const executionContext =
+ await this.agentRunCallerContextService.buildExecutionContext({
+ workspace,
+ callerRef: resolveAgentRunCallerRefOrThrow({
+ callerApplication,
+ callerApiKey,
+ requestUserWorkspaceId,
+ requestWorkspaceMemberId,
+ }),
+ requestUserWorkspaceId,
+ application: callerApplication,
+ callerApplication,
+ });
+
+ const { runId, outcome, usage } = await this.agentRunnerService
+ .runInRequest({
+ workspaceId: workspace.id,
+ executionContext,
+ spec: {
+ agentId: null,
+ inlineConfig: {
+ instructions: input.instructions ?? '',
+ modelId: input.modelId ?? AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ modelConfiguration: null,
+ scope: jsonFields.scope ?? null,
+ // a call without an application belongs to the workspace custom application
+ applicationId:
+ callerApplication?.id ?? workspace.workspaceCustomApplicationId,
+ promptCacheKey: `ai-generate:${callerApplication?.id ?? workspace.id}`,
+ },
+ title: 'Generate',
+ baseSystemPrompt: AGENT_RUN_BASE_SYSTEM_PROMPT,
+ instructions: null,
+ responseFormat,
+ capabilities: { canAskHumans: false },
+ },
+ turnId: requestedRunId ?? randomUUID(),
+ prompt: {
+ messages,
+ senderUserWorkspaceId: requestUserWorkspaceId,
+ senderApplicationId: callerApplication?.id ?? null,
+ },
+ streamChannelId,
+ })
+ .catch((error: unknown) => {
+ if (isDefined(requestedRunId) && isUniqueViolationError(error)) {
+ throw buildRunAlreadyExistsException(requestedRunId);
+ }
+
+ throw error;
+ });
+
+ const output = readGeneratedOutputOrThrow({
+ outcome,
+ isJsonResponse: responseFormat?.type === 'json',
+ });
+
+ return {
+ ...output,
+ success: !isDefined(output.error),
+ runId,
+ usage,
+ };
+ }
+
+ private async resolveStreamChannelIdOrThrow({
+ workspaceId,
+ callerApplication,
+ callerWorkspaceMemberId,
+ runId,
+ }: {
+ workspaceId: string;
+ callerApplication: Pick<FlatApplication, 'id'> | undefined;
+ callerWorkspaceMemberId: string | null;
+ runId: string;
+ }): Promise<string> {
+ if (!isDefined(callerApplication)) {
+ throw new AiException(
+ 'runId needs an application access token',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ // a concurrent call that passes this check still fails on the turn's primary key
+ const existingTurn = await this.turnRepository.findOne(workspaceId, {
+ where: { id: runId },
+ select: ['id'],
+ });
+
+ if (isDefined(existingTurn)) {
+ throw buildRunAlreadyExistsException(runId);
+ }
+
+ return buildAgentRunStreamChannelId({
+ applicationId: callerApplication.id,
+ callerWorkspaceMemberId,
+ runId,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
index d49f6233a58..a182d5c8614 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type.ts
@@ -23,7 +23,7 @@ export type AgentRunCallerHandler = {
// absent for a caller that only records the run, whose outcome is already in its conversation
onOutcome?(
input: AgentRunCallerInput & {
- threadId: string;
+ threadId: string | null;
outcome: AgentRunCallerOutcome;
// null when the run recorded none
summary: AgentRunSummary | null;
@@ -33,7 +33,7 @@ export type AgentRunCallerHandler = {
// the caller can no longer take the outcome, but something may still wait on the run, such as a request
onCallerGone?(
input: AgentRunCallerInput & {
- threadId: string;
+ threadId: string | null;
outcome: AgentRunCallerOutcome;
},
): Promise<void>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema.ts
new file mode 100644
index 00000000000..4b194a290c4
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+
+// neither set means the call acts as the application it comes through
+export const agentRunCallerRefSchema = z.object({
+ callerWorkspaceMemberId: z.string().optional(),
+ callerApiKeyId: z.string().optional(),
+});
+
+export type AgentRunCallerRef = z.infer<typeof agentRunCallerRefSchema>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
index b660a5fb76c..ee62a2879f5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
@@ -1,27 +1,17 @@
import { type ActorMetadata } from 'twenty-shared/types';
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
-import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
-import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
+import { type AgentConversationViewer } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-viewer.type';
-// How a run acts and is billed, which its caller derives on each segment instead of the engine storing it
+// How a run acts, which its caller derives on each segment instead of the engine storing it
export type AgentRunExecutionContext = {
authContext: WorkspaceAuthContext;
actorContext?: ActorMetadata;
// who the run's turns are recorded as sent by
turnCreatedBy: ActorMetadata;
userWorkspaceId: string | null;
- // what the run itself can read, such as the record an awaited event is about
- rolePermissionConfig: RolePermissionConfig;
// narrows the agent's own role, such as to the application a run belongs to
agentRunRoleIds?: AgentRunRoleIds;
- // who the continued conversation is read for, so turns others acted on read as theirs
- conversationActor?: AgentConversationActor;
- // the application the caller is bound to, whose tools are the only ones a call it posts can propose
- application?: FlatApplication;
- // what the run's tokens are billed and reported as
- usageOperationType: UsageOperationType;
+ conversationViewer?: AgentConversationViewer;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type.ts
new file mode 100644
index 00000000000..9abad08f2ee
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type.ts
@@ -0,0 +1,11 @@
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
+
+// What an agent row would otherwise supply, carried by the run so a paused one continues as it started
+export type AgentRunInlineConfig = Pick<
+ ResolvedAgentRunPersona,
+ 'instructions' | 'modelId' | 'modelConfiguration' | 'promptCacheKey'
+> &
+ Pick<ResolvedAgentRunPersona['permissions'], 'scope'> & {
+ // the application the caller runs under, so the run is never left to the workspace
+ applicationId: string;
+ };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type.ts
index 07d785dc70b..cd0b53497f5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type.ts
@@ -6,7 +6,7 @@ import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-ag
export type AgentRunOutcomeDelivery = {
workspaceId: string;
caller: AgentRunCaller;
- threadId: string;
+ threadId: string | null;
outcome: AgentRunCallerOutcome;
summary: AgentRunSummary | null;
attempt?: number;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
index 215b9388144..e8bee679d97 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
@@ -1,11 +1,15 @@
import { type AgentResponseFormat } from 'twenty-shared/ai';
+import { type AgentRunInlineConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type';
import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-tool-loading-strategy.type';
// What a suspended run needs to continue without its caller building it again.
-// Permissions are left out: the caller derives them anew on each continuation
-export type AgentRunSpec = {
- agentId: string;
+// The caller's roles are left out and derived anew on each continuation; an inline scope is kept with the run
+export type AgentRunPersonaSpec =
+ | { agentId: string; inlineConfig?: never }
+ | { agentId: null; inlineConfig: AgentRunInlineConfig };
+
+export type AgentRunSpec = AgentRunPersonaSpec & {
title: string;
baseSystemPrompt: string;
// the caller's own instructions, after what the engine says about its pausing tools
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
index 185d096e607..2de791bef3e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
@@ -4,16 +4,20 @@ import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-exe
import { type AgentRunConversation } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-conversation.type';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
-import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
// A run that pauses is suspended with its spec, and the engine continues it on its own and hands
// the outcome to its caller's handler
export type AgentRunnerRunInput = {
workspaceId: string;
- conversation: AgentRunConversation;
- caller: AgentRunCaller;
+ // null for a one-shot run: no thread, no claim, and nothing to pause on
+ conversation: AgentRunConversation | null;
+ // chosen before the run starts, so a retried job finds the turn its first attempt left
+ turnId?: string;
+ // null for a run answered within its caller's request, which pauses on nothing and is called back by no one
+ caller: AgentRunCaller | null;
spec: AgentRunSpec;
- agent: AgentEntity;
+ persona: ResolvedAgentRunPersona;
// what the run is asked and who asked it; absent when the run continues its conversation without a new message
prompt: {
messages: RunAgentMessage[];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/in-request-agent-run.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/in-request-agent-run.type.ts
new file mode 100644
index 00000000000..3b3b3528567
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/in-request-agent-run.type.ts
@@ -0,0 +1,10 @@
+import { type AiRunUsage } from 'twenty-shared/application';
+
+import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
+
+export type InRequestAgentRun = {
+ runId: string;
+ outcome: AgentRunnerOutcome;
+ // read back from the turn, which records what a failed run spent too
+ usage: AiRunUsage;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type.ts
new file mode 100644
index 00000000000..75d1bf9aab8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type.ts
@@ -0,0 +1,24 @@
+import {
+ type AgentResponseFormat,
+ type AiRunScope,
+ type ModelConfiguration,
+} from 'twenty-shared/ai';
+
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
+
+export type ResolvedAgentRunPersona = {
+ agentId: string | null;
+ // the application the run is queued and billed under
+ applicationId: string | null;
+ instructions: string;
+ modelId: string;
+ modelConfiguration: ModelConfiguration | null;
+ responseFormat: AgentResponseFormat | null;
+ promptCacheKey: string;
+ permissions: {
+ agentRoleId: string | null;
+ scope: AiRunScope | null;
+ // null when the run may use no data tools at all
+ explicitObjectGrants: ExplicitObjectGrants | null;
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type.ts
index 825049dc0f3..1d9d77b1c71 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/run-agent-job-data.type.ts
@@ -1,10 +1,12 @@
+import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunnerRunInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type';
-// the agent and how the run acts are read again in the job from the spec and the caller
+// what the run acts as, and how, are read again in the job from the spec and the caller
export type RunAgentJobData = Omit<
AgentRunnerRunInput,
- 'agent' | 'executionContext'
+ 'persona' | 'executionContext' | 'caller'
> & {
+ caller: AgentRunCaller;
// only on a delayed copy parked in Redis by the previous release
parkId?: string;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts
deleted file mode 100644
index 8cdb8ab1f60..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
-
-describe('buildAgentRolePermissionConfig', () => {
- it('keeps the agent role alone without restrictions', () => {
- expect(
- buildAgentRolePermissionConfig({ agentRoleId: 'agent-role-id' }),
- ).toEqual({ intersectionOf: { agentRoleId: 'agent-role-id' } });
- });
-
- it('bounds the agent role by the roles of the run that executes it', () => {
- expect(
- buildAgentRolePermissionConfig({
- agentRoleId: 'agent-role-id',
- agentRunRoleIds: {
- userWorkspaceRoleId: 'member-role-id',
- applicationRoleId: 'application-role-id',
- },
- }),
- ).toEqual({
- intersectionOf: {
- agentRoleId: 'agent-role-id',
- userWorkspaceRoleId: 'member-role-id',
- applicationRoleId: 'application-role-id',
- },
- });
- });
-
- it('denies an agent without a role, whatever restricts it', () => {
- expect(
- buildAgentRolePermissionConfig({
- agentRoleId: undefined,
- agentRunRoleIds: { userWorkspaceRoleId: 'member-role-id' },
- }),
- ).toEqual({
- intersectionOf: {
- agentRoleId: null,
- userWorkspaceRoleId: 'member-role-id',
- },
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-stream-channel-id.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-stream-channel-id.util.spec.ts
new file mode 100644
index 00000000000..a8e212962fb
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-stream-channel-id.util.spec.ts
@@ -0,0 +1,49 @@
+import { buildAgentRunStreamChannelId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util';
+
+const applicationId = '20202020-1c25-4d02-bf25-6aeccf7ea419';
+const runId = '3f1c9a52-7b0e-4d6a-8c2f-9e4b5a6d7c81';
+const memberId = '20202020-0687-4c41-b707-ed1bfca972a7';
+const otherMemberId = '20202020-77d5-4cb6-b60a-f4a835a85d61';
+
+const channelOf = ({
+ callerWorkspaceMemberId = memberId,
+ ...overrides
+}: Partial<Parameters<typeof buildAgentRunStreamChannelId>[0]> = {}) =>
+ buildAgentRunStreamChannelId({
+ applicationId,
+ callerWorkspaceMemberId,
+ runId,
+ ...overrides,
+ });
+
+describe('buildAgentRunStreamChannelId', () => {
+ it('should derive the same channel for the same run of the same caller', () => {
+ expect(channelOf()).toBe(channelOf());
+ });
+
+ it('should give another member naming the same run another channel', () => {
+ expect(channelOf({ callerWorkspaceMemberId: otherMemberId })).not.toBe(
+ channelOf(),
+ );
+ });
+
+ it('should give an application-only token its own channel, apart from every member', () => {
+ expect(channelOf({ callerWorkspaceMemberId: null })).toBe(
+ channelOf({ callerWorkspaceMemberId: null }),
+ );
+ expect(channelOf({ callerWorkspaceMemberId: null })).not.toBe(channelOf());
+ });
+
+ it('should give another run or another application another channel', () => {
+ expect(
+ channelOf({ runId: '8d2e4f6a-1b3c-4d5e-9f70-a1b2c3d4e5f6' }),
+ ).not.toBe(channelOf());
+ expect(
+ channelOf({ applicationId: '20202020-3d15-4f4d-a9b6-1fd1d0a8b5c0' }),
+ ).not.toBe(channelOf());
+ });
+
+ it('should not reuse the run id itself as the channel', () => {
+ expect(channelOf()).not.toBe(runId);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-turn-created-by.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-turn-created-by.util.spec.ts
new file mode 100644
index 00000000000..a40519e065b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-run-turn-created-by.util.spec.ts
@@ -0,0 +1,66 @@
+import { FieldActorSource } from 'twenty-shared/types';
+
+import { buildAgentRunTurnCreatedBy } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-turn-created-by.util';
+
+const CALLER_APPLICATION = { id: 'caller-application-id', name: 'Caller' };
+const MEMBER_ACTOR = {
+ source: FieldActorSource.MANUAL,
+ name: 'Ada Lovelace',
+ workspaceMemberId: 'member-id',
+ context: {},
+};
+const APPLICATION_AUTH_CONTEXT = {
+ type: 'application',
+ application: { id: 'auth-application-id', name: 'Auth app' },
+};
+
+describe('buildAgentRunTurnCreatedBy', () => {
+ it('keeps the calling application on a turn it runs as a member', () => {
+ expect(
+ buildAgentRunTurnCreatedBy({
+ actorContext: MEMBER_ACTOR,
+ callerApplication: CALLER_APPLICATION as never,
+ authContext: APPLICATION_AUTH_CONTEXT as never,
+ }),
+ ).toEqual({
+ ...MEMBER_ACTOR,
+ context: { applicationId: CALLER_APPLICATION.id },
+ });
+ });
+
+ it('credits a member turn to the member alone without a calling application', () => {
+ expect(
+ buildAgentRunTurnCreatedBy({
+ actorContext: MEMBER_ACTOR,
+ callerApplication: undefined,
+ authContext: APPLICATION_AUTH_CONTEXT as never,
+ }),
+ ).toEqual(MEMBER_ACTOR);
+ });
+
+ it('credits a turn without a member to the calling application', () => {
+ expect(
+ buildAgentRunTurnCreatedBy({
+ actorContext: undefined,
+ callerApplication: CALLER_APPLICATION as never,
+ authContext: APPLICATION_AUTH_CONTEXT as never,
+ }),
+ ).toMatchObject({
+ workspaceMemberId: null,
+ context: { applicationId: CALLER_APPLICATION.id },
+ });
+ });
+
+ it('credits a turn without a member or calling application to whoever authenticated', () => {
+ expect(
+ buildAgentRunTurnCreatedBy({
+ actorContext: undefined,
+ callerApplication: undefined,
+ authContext: APPLICATION_AUTH_CONTEXT as never,
+ }),
+ ).toMatchObject({
+ workspaceMemberId: null,
+ context: { applicationId: APPLICATION_AUTH_CONTEXT.application.id },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-role-explicit-object-grants.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-role-explicit-object-grants.util.spec.ts
new file mode 100644
index 00000000000..a365793c21c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-role-explicit-object-grants.util.spec.ts
@@ -0,0 +1,84 @@
+import { buildExplicitObjectPermissionByObjectId } from 'src/engine/core-modules/tool-provider/utils/build-explicit-object-permission-by-object-id.util';
+import { buildRoleExplicitObjectGrants } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-role-explicit-object-grants.util';
+
+const ROLE_WITHOUT_ROLE_WIDE_GRANTS = {
+ id: 'agent-role-id',
+ canReadAllObjectRecords: false,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+};
+
+describe('buildRoleExplicitObjectGrants', () => {
+ it('keeps only the rows of the role, without null values', () => {
+ expect(
+ buildRoleExplicitObjectGrants({
+ role: ROLE_WITHOUT_ROLE_WIDE_GRANTS,
+ flatObjectPermissionMaps: {
+ byUniversalIdentifier: {
+ 'agent-person': {
+ roleId: 'agent-role-id',
+ objectMetadataUniversalIdentifier: 'person',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: null,
+ canSoftDeleteObjectRecords: null,
+ canDestroyObjectRecords: null,
+ },
+ 'member-company': {
+ roleId: 'member-role-id',
+ objectMetadataUniversalIdentifier: 'company',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
+ canDestroyObjectRecords: true,
+ },
+ },
+ },
+ }),
+ ).toEqual({
+ canReadAllObjectRecords: false,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: undefined,
+ canSoftDeleteObjectRecords: undefined,
+ canDestroyObjectRecords: undefined,
+ },
+ ],
+ });
+ });
+
+ it('hands an agent whose role reads every object tools to read each of them', () => {
+ const explicitPermissionByObjectId =
+ buildExplicitObjectPermissionByObjectId({
+ explicitObjectGrants: buildRoleExplicitObjectGrants({
+ role: {
+ ...ROLE_WITHOUT_ROLE_WIDE_GRANTS,
+ canReadAllObjectRecords: true,
+ },
+ flatObjectPermissionMaps: { byUniversalIdentifier: {} },
+ }),
+ flatObjectMetadataMaps: {
+ byUniversalIdentifier: {
+ person: { id: 'person-id', universalIdentifier: 'person' },
+ company: { id: 'company-id', universalIdentifier: 'company' },
+ } as never,
+ },
+ });
+
+ expect([...explicitPermissionByObjectId.keys()]).toEqual([
+ 'person-id',
+ 'company-id',
+ ]);
+ expect(explicitPermissionByObjectId.get('person-id')).toEqual({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/parse-agent-input-or-throw.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/parse-agent-input-or-throw.util.spec.ts
new file mode 100644
index 00000000000..483a888bbe6
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/parse-agent-input-or-throw.util.spec.ts
@@ -0,0 +1,21 @@
+import { agentResponseFormatSchema } from 'twenty-shared/workflow';
+
+import { parseAgentInputOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+
+describe('parseAgentInputOrThrow', () => {
+ it('names the field it parses in the error', () => {
+ expect(() =>
+ parseAgentInputOrThrow({
+ schema: agentResponseFormatSchema,
+ input: { type: 'xml' },
+ label: 'response format',
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: AiExceptionCode.INVALID_AGENT_INPUT,
+ message: expect.stringMatching(/^Invalid response format: type: /),
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts
deleted file mode 100644
index f04dfa03319..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
-import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
-
-export const buildAgentRolePermissionConfig = ({
- agentRoleId,
- agentRunRoleIds = {},
-}: {
- agentRoleId: string | undefined;
- agentRunRoleIds?: AgentRunRoleIds;
-}): RolePermissionConfig => ({
- intersectionOf: { ...agentRunRoleIds, agentRoleId: agentRoleId ?? null },
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util.ts
new file mode 100644
index 00000000000..ff077bc1b29
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util.ts
@@ -0,0 +1,21 @@
+import { v5 } from 'uuid';
+
+import { AGENT_RUN_STREAM_CHANNEL_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-stream-channel-id-namespace.const';
+
+// a token without a member can never stand for one, so its channels are named apart from every member's
+const APPLICATION_ONLY_CALLER = 'application';
+
+// keyed by the caller as well as the application, so a member-bound token can only name its own member's runs
+export const buildAgentRunStreamChannelId = ({
+ applicationId,
+ callerWorkspaceMemberId,
+ runId,
+}: {
+ applicationId: string;
+ callerWorkspaceMemberId: string | null;
+ runId: string;
+}): string =>
+ v5(
+ `${applicationId}:${callerWorkspaceMemberId ?? APPLICATION_ONLY_CALLER}:${runId}`,
+ AGENT_RUN_STREAM_CHANNEL_ID_NAMESPACE,
+ );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-turn-created-by.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-turn-created-by.util.ts
new file mode 100644
index 00000000000..05d16be6771
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-turn-created-by.util.ts
@@ -0,0 +1,33 @@
+import { type ActorMetadata } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildActorMetadataFromAuthContext } from 'src/engine/core-modules/actor/utils/build-actor-metadata-from-auth-context.util';
+import { buildCreatedByFromApplication } from 'src/engine/core-modules/actor/utils/build-created-by-from-application.util';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+export const buildAgentRunTurnCreatedBy = ({
+ actorContext,
+ callerApplication,
+ authContext,
+}: {
+ actorContext: ActorMetadata | undefined;
+ callerApplication: FlatApplication | undefined;
+ authContext: WorkspaceAuthContext;
+}): ActorMetadata => {
+ if (!isDefined(actorContext)) {
+ return isDefined(callerApplication)
+ ? buildCreatedByFromApplication({ application: callerApplication })
+ : buildActorMetadataFromAuthContext(authContext);
+ }
+
+ if (!isDefined(callerApplication)) {
+ return actorContext;
+ }
+
+ // the application is kept on a turn it runs as a member, so it can read that turn back
+ return {
+ ...actorContext,
+ context: { ...actorContext.context, applicationId: callerApplication.id },
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-role-explicit-object-grants.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-role-explicit-object-grants.util.ts
new file mode 100644
index 00000000000..618bc76d4f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-role-explicit-object-grants.util.ts
@@ -0,0 +1,58 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ExplicitObjectGrants } from 'src/engine/core-modules/tool-provider/interfaces/explicit-object-grants.type';
+import { type FlatObjectPermission } from 'src/engine/metadata-modules/flat-object-permission/types/flat-object-permission.type';
+import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
+
+export const buildRoleExplicitObjectGrants = ({
+ role,
+ flatObjectPermissionMaps,
+}: {
+ role: Pick<
+ FlatRole,
+ | 'id'
+ | 'canReadAllObjectRecords'
+ | 'canUpdateAllObjectRecords'
+ | 'canSoftDeleteAllObjectRecords'
+ | 'canDestroyAllObjectRecords'
+ >;
+ flatObjectPermissionMaps: {
+ byUniversalIdentifier: Partial<
+ Record<
+ string,
+ Pick<
+ FlatObjectPermission,
+ | 'roleId'
+ | 'objectMetadataUniversalIdentifier'
+ | 'canReadObjectRecords'
+ | 'canUpdateObjectRecords'
+ | 'canSoftDeleteObjectRecords'
+ | 'canDestroyObjectRecords'
+ >
+ >
+ >;
+ };
+}): ExplicitObjectGrants => ({
+ // role-wide grants count, as an inline scope's do: the allowlist only picks the tools a run is handed
+ canReadAllObjectRecords: role.canReadAllObjectRecords,
+ canUpdateAllObjectRecords: role.canUpdateAllObjectRecords,
+ canSoftDeleteAllObjectRecords: role.canSoftDeleteAllObjectRecords,
+ canDestroyAllObjectRecords: role.canDestroyAllObjectRecords,
+ objectPermissions: Object.values(
+ flatObjectPermissionMaps.byUniversalIdentifier,
+ )
+ .filter(isDefined)
+ .filter((flatObjectPermission) => flatObjectPermission.roleId === role.id)
+ .map((flatObjectPermission) => ({
+ objectUniversalIdentifier:
+ flatObjectPermission.objectMetadataUniversalIdentifier,
+ canReadObjectRecords:
+ flatObjectPermission.canReadObjectRecords ?? undefined,
+ canUpdateObjectRecords:
+ flatObjectPermission.canUpdateObjectRecords ?? undefined,
+ canSoftDeleteObjectRecords:
+ flatObjectPermission.canSoftDeleteObjectRecords ?? undefined,
+ canDestroyObjectRecords:
+ flatObjectPermission.canDestroyObjectRecords ?? undefined,
+ })),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util.ts
new file mode 100644
index 00000000000..8b574889b5a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/parse-agent-input-or-throw.util.ts
@@ -0,0 +1,34 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { type z } from 'zod';
+
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+// the resolvers check only the GraphQL shape, so the JSON fields are parsed here before they reach the model
+export const parseAgentInputOrThrow = <TSchema extends z.ZodType>({
+ schema,
+ input,
+ label = 'input',
+}: {
+ schema: TSchema;
+ input: unknown;
+ // names the field the schema parses, since issue paths are relative to it
+ label?: string;
+}): z.infer<TSchema> => {
+ const parsedInput = schema.safeParse(input);
+
+ if (!parsedInput.success) {
+ throw new AiException(
+ `Invalid ${label}: ${parsedInput.error.issues
+ .map(({ path, message }) =>
+ isNonEmptyArray(path) ? `${path.join('.')}: ${message}` : message,
+ )
+ .join(', ')}`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ return parsedInput.data;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/read-generated-output-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/read-generated-output-or-throw.util.ts
new file mode 100644
index 00000000000..e44b775a477
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/read-generated-output-or-throw.util.ts
@@ -0,0 +1,44 @@
+import { isString } from '@sniptt/guards';
+import { type GenerateResult } from 'twenty-shared/application';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type AgentRunnerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-outcome.type';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+type GeneratedOutput = Pick<GenerateResult, 'text' | 'object' | 'error'>;
+
+// a completed run always holds an object, with a text response for a text format
+export const readGeneratedOutputOrThrow = ({
+ outcome,
+ isJsonResponse,
+}: {
+ outcome: AgentRunnerOutcome;
+ isJsonResponse: boolean;
+}): GeneratedOutput => {
+ if (outcome.status === 'FAILED') {
+ return { text: null, object: null, error: outcome.error };
+ }
+
+ if (outcome.status !== 'COMPLETED' || !isPlainObject(outcome.result)) {
+ throw new AiException(
+ `A run without a conversation ended ${outcome.status} without a result`,
+ AiExceptionCode.AGENT_EXECUTION_FAILED,
+ );
+ }
+
+ if (isJsonResponse) {
+ return { text: null, object: outcome.result, error: null };
+ }
+
+ if (!isString(outcome.result.response)) {
+ throw new AiException(
+ 'A completed text run returned no text',
+ AiExceptionCode.AGENT_EXECUTION_FAILED,
+ );
+ }
+
+ return { text: outcome.result.response, object: null, error: null };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-caller-ref-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-caller-ref-or-throw.util.ts
new file mode 100644
index 00000000000..89c81dc75b8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-caller-ref-or-throw.util.ts
@@ -0,0 +1,38 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-key.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type AgentRunCallerRef } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-ref.schema';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+export const resolveAgentRunCallerRefOrThrow = ({
+ callerApplication,
+ callerApiKey,
+ requestUserWorkspaceId,
+ requestWorkspaceMemberId,
+}: {
+ callerApplication?: FlatApplication;
+ callerApiKey?: Pick<FlatApiKey, 'id'>;
+ requestUserWorkspaceId: string | null;
+ requestWorkspaceMemberId: string | null;
+}): AgentRunCallerRef => {
+ if (isDefined(requestWorkspaceMemberId)) {
+ return { callerWorkspaceMemberId: requestWorkspaceMemberId };
+ }
+
+ if (isDefined(callerApplication) && !isDefined(requestUserWorkspaceId)) {
+ return {};
+ }
+
+ if (isDefined(callerApiKey)) {
+ return { callerApiKeyId: callerApiKey.id };
+ }
+
+ throw new AiException(
+ 'An AI run requires a workspace member, an API key or an application',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-agent.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-agent.util.ts
new file mode 100644
index 00000000000..e0242ca355e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-agent.util.ts
@@ -0,0 +1,32 @@
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
+
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
+import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
+
+export const resolveAgentRunPersonaFromAgent = ({
+ agent,
+ agentRoleId,
+ explicitObjectGrants,
+}: {
+ agent: Pick<
+ AgentEntity,
+ | 'id'
+ | 'applicationId'
+ | 'prompt'
+ | 'modelId'
+ | 'modelConfiguration'
+ | 'responseFormat'
+ >;
+} & Pick<
+ ResolvedAgentRunPersona['permissions'],
+ 'agentRoleId' | 'explicitObjectGrants'
+>): ResolvedAgentRunPersona => ({
+ agentId: agent.id,
+ applicationId: agent.applicationId,
+ instructions: tipTapDocumentToMarkdown(agent.prompt),
+ modelId: agent.modelId,
+ modelConfiguration: agent.modelConfiguration ?? null,
+ responseFormat: agent.responseFormat ?? null,
+ promptCacheKey: agent.id,
+ permissions: { agentRoleId, scope: null, explicitObjectGrants },
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-inline-config.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-inline-config.util.ts
new file mode 100644
index 00000000000..73b278885c3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-persona-from-inline-config.util.ts
@@ -0,0 +1,21 @@
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
+
+import { type AgentRunInlineConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-inline-config.type';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
+
+export const resolveAgentRunPersonaFromInlineConfig = (
+ inlineConfig: AgentRunInlineConfig,
+): ResolvedAgentRunPersona => ({
+ agentId: null,
+ applicationId: inlineConfig.applicationId,
+ instructions: tipTapDocumentToMarkdown(inlineConfig.instructions),
+ modelId: inlineConfig.modelId,
+ modelConfiguration: inlineConfig.modelConfiguration,
+ responseFormat: null,
+ promptCacheKey: inlineConfig.promptCacheKey,
+ permissions: {
+ agentRoleId: null,
+ scope: inlineConfig.scope,
+ explicitObjectGrants: inlineConfig.scope,
+ },
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts
index 764fe46f96c..d8464d99a2d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-run-agent-messages-or-throw.util.ts
@@ -1,5 +1,8 @@
import { isNonEmptyString } from '@sniptt/guards';
-import { type RunAgentMessage } from 'twenty-shared/application';
+import {
+ hasRunAgentMessageContentOrAttachments,
+ type RunAgentMessage,
+} from 'twenty-shared/application';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import {
@@ -7,10 +10,6 @@ import {
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
-const isBlankMessage = (message: RunAgentMessage): boolean =>
- !isNonEmptyString(message.content.trim()) &&
- !isNonEmptyArray(message.attachments);
-
// GraphQL cannot express XOR
export const resolveRunAgentMessagesOrThrow = ({
input,
@@ -50,7 +49,10 @@ export const resolveRunAgentMessagesOrThrow = ({
return messages;
}
- if (!isNonEmptyArray(input) || input.some(isBlankMessage)) {
+ if (
+ !isNonEmptyArray(input) ||
+ !input.every(hasRunAgentMessageContentOrAttachments)
+ ) {
throw new AiException(
'input must hold messages with content or attachments',
AiExceptionCode.INVALID_AGENT_INPUT,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-runs/dtos/agent-run.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-runs/dtos/agent-run.dto.ts
index 2db034a8ffe..03edcae0a2e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-runs/dtos/agent-run.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-runs/dtos/agent-run.dto.ts
@@ -8,8 +8,9 @@ export class AgentRunDTO {
@Field(() => UUIDScalarType)
id: string;
- @Field(() => UUIDScalarType)
- threadId: string;
+ // null for a one-shot run, which has no conversation
+ @Field(() => UUIDScalarType, { nullable: true })
+ threadId: string | null;
@Field(() => String, { nullable: true })
threadTitle: string | null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
index 70e50fb6584..e170510d551 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
@@ -6,7 +6,6 @@ import { v4 } from 'uuid';
import { z } from 'zod';
import { buildCreatedByFromAgent } from 'src/engine/core-modules/actor/utils/build-created-by-from-agent.util';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
@@ -16,7 +15,6 @@ import { type OwnerWaitingState } from 'src/engine/core-modules/pending-wake-up/
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';
import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
-import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';
import { AGENT_TRIGGER_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent-trigger/constants/agent-trigger-base-system-prompt.const';
import { type RunAgentTriggerJobData } from 'src/engine/metadata-modules/ai/ai-agent-trigger/types/run-agent-trigger-job-data.type';
@@ -223,12 +221,7 @@ export class AgentTriggerRunnerService
actorContext: createdBy,
turnCreatedBy: createdBy,
userWorkspaceId: null,
- rolePermissionConfig: buildAgentRolePermissionConfig({
- agentRoleId,
- agentRunRoleIds,
- }),
agentRunRoleIds,
- usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
},
};
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/__tests__/agent-tools.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/__tests__/agent-tools.spec.ts
index 218f056202b..6d093b002de 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/__tests__/agent-tools.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/__tests__/agent-tools.spec.ts
@@ -108,7 +108,6 @@ const buildAgentTools = (options?: {
const manageableAgentService = new ManageableAgentService(
agentService as unknown as AgentService,
applicationService as unknown as ApplicationService,
- workspaceCacheService as unknown as WorkspaceCacheService,
);
const tools = [
@@ -125,6 +124,7 @@ const buildAgentTools = (options?: {
new DeleteAgentTool(
agentService as unknown as AgentService,
manageableAgentService,
+ workspaceCacheService as unknown as WorkspaceCacheService,
),
];
@@ -176,21 +176,6 @@ const buildAgentTools = (options?: {
};
};
-const workflowVersionsWithAgentStep = {
- flatWorkflowVersionMaps: {
- byUniversalIdentifier: {
- 'workflow-version-id': {
- steps: [
- {
- type: WorkflowActionType.AI_AGENT,
- settings: { input: { agentId } },
- },
- ],
- },
- },
- },
-};
-
describe('Agent tools', () => {
describe('availability', () => {
it('is available when the caller has the AI settings permission', async () => {
@@ -421,23 +406,6 @@ describe('Agent tools', () => {
workspaceId,
});
});
-
- it('refuses to change an agent backing a workflow step', async () => {
- const { executeTool, agentService, workspaceCacheService } =
- buildAgentTools();
-
- workspaceCacheService.getOrRecompute.mockResolvedValue(
- workflowVersionsWithAgentStep,
- );
-
- await expect(
- executeTool({
- toolName: 'update_agent',
- args: { id: agentId, prompt: 'Something else' },
- }),
- ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });
- expect(agentService.updateOneAgent).not.toHaveBeenCalled();
- });
});
describe('delete_agent', () => {
@@ -457,13 +425,24 @@ describe('Agent tools', () => {
);
});
- it('refuses to delete an agent backing a workflow step', async () => {
+ it('refuses to delete a reusable agent that workflow steps run', async () => {
const { executeTool, agentService, workspaceCacheService } =
buildAgentTools();
- workspaceCacheService.getOrRecompute.mockResolvedValue(
- workflowVersionsWithAgentStep,
- );
+ workspaceCacheService.getOrRecompute.mockResolvedValue({
+ flatWorkflowVersionMaps: {
+ byUniversalIdentifier: {
+ 'workflow-version-id': {
+ steps: [
+ {
+ type: WorkflowActionType.AI_AGENT,
+ settings: { input: { agentId } },
+ },
+ ],
+ },
+ },
+ },
+ });
await expect(
executeTool({ toolName: 'delete_agent', args: { id: agentId } }),
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool.ts
index 3dfa1e2aceb..f66ec1ab620 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool.ts
@@ -1,6 +1,7 @@
import { ToolCategory } from 'twenty-shared/ai';
import { PermissionFlagType } from 'twenty-shared/constants';
import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
import { z } from 'zod';
import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
@@ -9,6 +10,12 @@ import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/type
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
import { AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent.service';
import { ManageableAgentService } from 'src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service';
+import { isAgentBackingWorkflowStep } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/is-agent-backing-workflow-step.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
const deleteAgentInputSchema = z.object({
id: z.uuid().describe('Id of the agent to delete'),
@@ -27,6 +34,7 @@ export class DeleteAgentTool extends BaseTool<typeof deleteAgentInputSchema> {
constructor(
private readonly agentService: AgentService,
private readonly manageableAgentService: ManageableAgentService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
) {
super();
}
@@ -40,6 +48,25 @@ export class DeleteAgentTool extends BaseTool<typeof deleteAgentInputSchema> {
context,
});
+ const { flatWorkflowVersionMaps } =
+ await this.workspaceCacheService.getOrRecompute(context.workspaceId, [
+ 'flatWorkflowVersionMaps',
+ ]);
+
+ if (
+ isAgentBackingWorkflowStep({
+ agentId: input.id,
+ flatWorkflowVersions: Object.values(
+ flatWorkflowVersionMaps.byUniversalIdentifier,
+ ).filter(isDefined),
+ })
+ ) {
+ throw new AiException(
+ 'Workflow AI steps run this agent: point them at another agent before deleting it',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
const agent = await this.agentService.deleteOneAgent(
input.id,
context.workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
index cd9066b33ce..e13d749d177 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
@@ -1,25 +1,20 @@
import { Injectable } from '@nestjs/common';
-import { isDefined } from 'twenty-shared/utils';
-
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { canCallerReachApplication } from 'src/engine/core-modules/application/utils/can-caller-reach-application.util';
import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
import { AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent.service';
-import { isAgentBackingWorkflowStep } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/is-agent-backing-workflow-step.util';
import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
import { type FlatAgentWithRoleId } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@Injectable()
export class ManageableAgentService {
constructor(
private readonly agentService: AgentService,
private readonly applicationService: ApplicationService,
- private readonly workspaceCacheService: WorkspaceCacheService,
) {}
async findManageableAgentOrThrow({
@@ -56,25 +51,6 @@ export class ManageableAgentService {
);
}
- const { flatWorkflowVersionMaps } =
- await this.workspaceCacheService.getOrRecompute(context.workspaceId, [
- 'flatWorkflowVersionMaps',
- ]);
-
- if (
- isAgentBackingWorkflowStep({
- agentId: agent.id,
- flatWorkflowVersions: Object.values(
- flatWorkflowVersionMaps.byUniversalIdentifier,
- ).filter(isDefined),
- })
- ) {
- throw new AiException(
- 'This agent is managed by a workflow AI step: configure it with update_workflow_agent, and remove the step to delete it',
- AiExceptionCode.INVALID_AGENT_INPUT,
- );
- }
-
return agent;
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
index dd592833341..d2ec1a9091d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
@@ -35,12 +35,14 @@ import { AgentChatChannelResolver } from 'src/engine/metadata-modules/ai/ai-chat
import { AgentChatThreadParticipantResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver';
import { AgentChatMessageReactionResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-message-reaction.resolver';
import { AgentChatMessageReactionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-message-reaction.service';
+import { AgentChatHistoryResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-history.resolver';
import { AgentChatSubscriptionResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-subscription.resolver';
import { AgentInboxResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver';
import { WorkspaceSetupChatResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/workspace-setup-chat.resolver';
import { WorkspaceSetupChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentChatConversationAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service';
import { AgentChatQueueService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service';
import { AgentChatThreadTargetService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service';
import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
@@ -79,6 +81,7 @@ import { AgentInboxAccessService } from 'src/engine/metadata-modules/ai/ai-chat/
AiChatUsageService,
AiChatUsageResolver,
AgentChatResolver,
+ AgentChatHistoryResolver,
AgentChatChannelResolver,
AgentChatThreadParticipantResolver,
AgentChatMessageReactionResolver,
@@ -88,6 +91,7 @@ import { AgentInboxAccessService } from 'src/engine/metadata-modules/ai/ai-chat/
AgentInboxResolver,
AgentInboxProposalService,
AgentChatQueueService,
+ AgentChatConversationAccessService,
AgentChatService,
AgentChatThreadTargetService,
AgentChatStreamingService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input.ts
new file mode 100644
index 00000000000..1d94568aac3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input.ts
@@ -0,0 +1,16 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+// a member names a thread by id; an application names its own conversation as it passes it to runAgent
+@ArgsType()
+export class AgentChatConversationInput {
+ @Field(() => UUIDScalarType, { nullable: true })
+ threadId?: string | null;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ agentUniversalIdentifier?: string | null;
+
+ @Field(() => String, { nullable: true })
+ threadKey?: string | null;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.dto.ts
index 01aa5ea168d..ff292720eaf 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.dto.ts
@@ -6,8 +6,8 @@ import GraphQLJSON from 'graphql-type-json';
// (a discriminated union defined in twenty-shared).
@ObjectType('AgentChatEvent')
export class AgentChatEventDTO {
- @Field(() => String)
- threadId: string;
+ @Field(() => String, { nullable: true })
+ threadId: string | null;
@Field(() => GraphQLJSON)
event: Record<string, unknown>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.input.ts
new file mode 100644
index 00000000000..26eea2c2f2a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.input.ts
@@ -0,0 +1,11 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { AgentChatConversationInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input';
+
+// an application also follows a run it starts with ai.generate, by the runId it passes
+@ArgsType()
+export class AgentChatEventInput extends AgentChatConversationInput {
+ @Field(() => UUIDScalarType, { nullable: true })
+ runId?: string | null;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
index e3e1abfca6e..1730834791a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
@@ -189,6 +189,7 @@ export class StreamAgentChatJob {
.catch(() => null);
const { finish } = await this.turnStreamService.streamTurn({
+ workspaceId: data.workspaceId,
claim,
turnId,
abortSignal,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat-subscription.resolver.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat-subscription.resolver.spec.ts
index b6bacbecd6a..9124e7c5e4c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat-subscription.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat-subscription.resolver.spec.ts
@@ -1,3 +1,6 @@
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
import {
AiException,
AiExceptionCode,
@@ -8,7 +11,24 @@ import { AGENT_CHAT_KEEPALIVE_INTERVAL_MS } from 'src/engine/metadata-modules/ai
const WORKSPACE_ID = 'workspace';
const THREAD_ID = 'thread';
const VIEWER_ID = 'viewer';
-const payload = {
+const WORKSPACE = {
+ id: WORKSPACE_ID,
+ workspaceCustomApplicationId: 'workspace-custom-application-id',
+};
+const APPLICATION = {
+ id: 'application',
+ universalIdentifier: 'application-universal-identifier',
+ sourceType: ApplicationRegistrationSourceType.NPM,
+};
+
+type AgentChatEventPayload = {
+ onAgentChatEvent: {
+ threadId: string | null;
+ event: AgentChatSubscriptionEvent;
+ };
+};
+
+const payload: AgentChatEventPayload = {
onAgentChatEvent: {
threadId: THREAD_ID,
event: {
@@ -17,13 +37,21 @@ const payload = {
},
},
};
+const toChunkPayload = (
+ chunk: Record<string, unknown>,
+): AgentChatEventPayload => ({
+ onAgentChatEvent: {
+ threadId: THREAD_ID,
+ event: { type: 'stream-chunk', chunk, seq: 1 },
+ },
+});
const denied = () =>
new AiException('Thread not found', AiExceptionCode.THREAD_NOT_FOUND);
const buildResolver = () => {
let resolvePending: (
- result: IteratorResult<typeof payload>,
+ result: IteratorResult<AgentChatEventPayload>,
) => void = () => {};
- const iterator: AsyncIterableIterator<typeof payload> = {
+ const iterator: AsyncIterableIterator<AgentChatEventPayload> = {
next: jest.fn().mockImplementation(
() =>
new Promise((resolve) => {
@@ -38,8 +66,13 @@ const buildResolver = () => {
return this;
},
};
- const sharingService = {
- getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),
+ const conversationAccessService = {
+ resolveReadableChannelOrThrow: jest
+ .fn()
+ .mockResolvedValue({ kind: 'thread', channelId: THREAD_ID }),
+ createLiveEventFilter: jest
+ .fn()
+ .mockReturnValue(async (event: AgentChatSubscriptionEvent) => event),
};
const subscriptionService = {
subscribeToAgentChat: jest.fn().mockResolvedValue(iterator),
@@ -48,15 +81,15 @@ const buildResolver = () => {
const resolver = new AgentChatSubscriptionResolver(
subscriptionService as never,
{} as never,
- sharingService as never,
+ conversationAccessService as never,
{ findOne: jest.fn().mockResolvedValue(null) } as never,
);
return {
resolver,
- sharingService,
+ conversationAccessService,
subscriptionService,
iterator,
- deliver: () => resolvePending({ done: false, value: payload }),
+ deliver: (value = payload) => resolvePending({ done: false, value }),
};
};
@@ -65,12 +98,16 @@ describe('Shared conversation subscriptions', () => {
afterEach(() => jest.useRealTimers());
it('refuses unauthorized subscriptions before opening a transport', async () => {
- const { resolver, sharingService, subscriptionService } = buildResolver();
- sharingService.getReadableThread.mockRejectedValue(denied());
+ const { resolver, conversationAccessService, subscriptionService } =
+ buildResolver();
+ conversationAccessService.resolveReadableChannelOrThrow.mockRejectedValue(
+ denied(),
+ );
await expect(
resolver.onAgentChatEvent(
- THREAD_ID,
- { id: WORKSPACE_ID } as never,
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
VIEWER_ID,
),
).rejects.toMatchObject({ extensions: { code: 'NOT_FOUND' } });
@@ -80,34 +117,108 @@ describe('Shared conversation subscriptions', () => {
it('delivers events to authorized viewers and closes cleanly on disconnect', async () => {
const context = buildResolver();
const subscription = await context.resolver.onAgentChatEvent(
- THREAD_ID,
- { id: WORKSPACE_ID } as never,
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
VIEWER_ID,
);
await subscription.next();
const pending = subscription.next();
context.deliver();
await expect(pending).resolves.toEqual({ done: false, value: payload });
- expect(context.sharingService.getReadableThread).toHaveBeenLastCalledWith({
- workspaceId: WORKSPACE_ID,
- threadId: THREAD_ID,
+ expect(
+ context.conversationAccessService.resolveReadableChannelOrThrow,
+ ).toHaveBeenLastCalledWith({
+ workspace: WORKSPACE,
+ callerApplication: undefined,
workspaceMemberId: VIEWER_ID,
+ source: { threadId: THREAD_ID },
});
await subscription.return?.();
expect(context.iterator.return).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(0);
});
+ it('follows the thread an application names by its agent and key', async () => {
+ const context = buildResolver();
+ const conversation = {
+ agentUniversalIdentifier: 'agent-universal-identifier',
+ threadKey: 'deal-42',
+ };
+ const subscription = await context.resolver.onAgentChatEvent(
+ conversation,
+ WORKSPACE,
+ APPLICATION,
+ undefined,
+ );
+
+ await expect(subscription.next()).resolves.toEqual({
+ done: false,
+ value: {
+ onAgentChatEvent: { threadId: THREAD_ID, event: { type: 'keepalive' } },
+ },
+ });
+ expect(
+ context.conversationAccessService.resolveReadableChannelOrThrow,
+ ).toHaveBeenCalledWith(expect.objectContaining({ source: conversation }));
+ expect(
+ context.subscriptionService.subscribeToAgentChat,
+ ).toHaveBeenCalledWith({ workspaceId: WORKSPACE_ID, threadId: THREAD_ID });
+ await subscription.return?.();
+ });
+
+ it('passes every event through the visibility filter for the viewer', async () => {
+ const context = buildResolver();
+ const maskedChunk = { type: 'message-metadata', messageMetadata: {} };
+
+ context.conversationAccessService.createLiveEventFilter.mockReturnValue(
+ async (event: AgentChatSubscriptionEvent) =>
+ event.type === 'stream-chunk'
+ ? { ...event, chunk: maskedChunk }
+ : event,
+ );
+
+ const subscription = await context.resolver.onAgentChatEvent(
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
+ VIEWER_ID,
+ );
+
+ await subscription.next();
+
+ const pending = subscription.next();
+
+ context.deliver(
+ toChunkPayload({ type: 'reasoning-delta', delta: 'Notes' }),
+ );
+ await expect(pending).resolves.toEqual({
+ done: false,
+ value: toChunkPayload(maskedChunk),
+ });
+ expect(
+ context.conversationAccessService.createLiveEventFilter,
+ ).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ threadId: THREAD_ID,
+ workspaceMemberId: VIEWER_ID,
+ });
+ await subscription.return?.();
+ });
+
it('rejects an already pending event when its authorization expires', async () => {
const context = buildResolver();
const subscription = await context.resolver.onAgentChatEvent(
- THREAD_ID,
- { id: WORKSPACE_ID } as never,
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
VIEWER_ID,
);
await subscription.next();
const pending = subscription.next();
- context.sharingService.getReadableThread.mockRejectedValue(denied());
+ context.conversationAccessService.resolveReadableChannelOrThrow.mockRejectedValue(
+ denied(),
+ );
jest.setSystemTime(Date.now() + AGENT_CHAT_KEEPALIVE_INTERVAL_MS);
context.deliver();
await expect(pending).rejects.toMatchObject({
@@ -120,8 +231,9 @@ describe('Shared conversation subscriptions', () => {
it('does not query authorization once per token during a burst', async () => {
const context = buildResolver();
const subscription = await context.resolver.onAgentChatEvent(
- THREAD_ID,
- { id: WORKSPACE_ID } as never,
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
VIEWER_ID,
);
await subscription.next();
@@ -130,15 +242,18 @@ describe('Shared conversation subscriptions', () => {
context.deliver();
await pending;
}
- expect(context.sharingService.getReadableThread).toHaveBeenCalledTimes(1);
+ expect(
+ context.conversationAccessService.resolveReadableChannelOrThrow,
+ ).toHaveBeenCalledTimes(1);
await subscription.return?.();
});
it('closes an idle subscription after revocation without waiting for content', async () => {
const context = buildResolver();
const subscription = await context.resolver.onAgentChatEvent(
- THREAD_ID,
- { id: WORKSPACE_ID } as never,
+ { threadId: THREAD_ID },
+ WORKSPACE,
+ undefined,
VIEWER_ID,
);
await subscription.next();
@@ -146,7 +261,9 @@ describe('Shared conversation subscriptions', () => {
const rejection = expect(pending).rejects.toMatchObject({
extensions: { code: 'NOT_FOUND' },
});
- context.sharingService.getReadableThread.mockRejectedValue(denied());
+ context.conversationAccessService.resolveReadableChannelOrThrow.mockRejectedValue(
+ denied(),
+ );
await jest.advanceTimersByTimeAsync(AGENT_CHAT_KEEPALIVE_INTERVAL_MS);
await rejection;
expect(
@@ -155,4 +272,60 @@ describe('Shared conversation subscriptions', () => {
expect(context.iterator.return).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(0);
});
+
+ it('streams a run channel as published, without a thread to filter or name', async () => {
+ const context = buildResolver();
+ const runChannelId = 'run-channel-id';
+
+ context.conversationAccessService.resolveReadableChannelOrThrow.mockResolvedValue(
+ { kind: 'run', channelId: runChannelId },
+ );
+
+ const subscription = await context.resolver.onAgentChatEvent(
+ { runId: 'run-id' },
+ WORKSPACE,
+ { id: 'application-id' } as never,
+ undefined,
+ );
+
+ await expect(subscription.next()).resolves.toEqual({
+ done: false,
+ value: {
+ onAgentChatEvent: { threadId: null, event: { type: 'keepalive' } },
+ },
+ });
+
+ const pending = subscription.next();
+
+ context.deliver({
+ onAgentChatEvent: {
+ threadId: runChannelId,
+ event: payload.onAgentChatEvent.event,
+ },
+ });
+
+ await expect(pending).resolves.toEqual({
+ done: false,
+ value: {
+ onAgentChatEvent: {
+ threadId: null,
+ event: payload.onAgentChatEvent.event,
+ },
+ },
+ });
+ expect(
+ context.subscriptionService.subscribeToAgentChat,
+ ).toHaveBeenCalledTimes(1);
+ expect(
+ context.subscriptionService.subscribeToAgentChat,
+ ).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE.id,
+ threadId: runChannelId,
+ });
+ expect(
+ context.conversationAccessService.createLiveEventFilter,
+ ).not.toHaveBeenCalled();
+
+ await subscription.return?.();
+ });
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-history.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-history.resolver.ts
new file mode 100644
index 00000000000..ba86391fb41
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-history.resolver.ts
@@ -0,0 +1,159 @@
+import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';
+import { Args, Query } from '@nestjs/graphql';
+
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+
+import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
+import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
+import { AgentMessageDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/agent-message.dto';
+import { AgentChatConversationInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input';
+import { ChatStreamCatchupChunksDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/chat-stream-catchup-chunks.dto';
+import { AgentChatConversationAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service';
+import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
+import { AgentChatMessageReactionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-message-reaction.service';
+import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
+import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
+import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: true,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: { withUser: true, withoutUser: false },
+ application: true,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.AI),
+)
+@UseInterceptors(AiGraphqlApiExceptionInterceptor)
+@UseFilters(AuthGraphqlApiExceptionFilter)
+@MetadataResolver()
+export class AgentChatHistoryResolver {
+ constructor(
+ private readonly agentChatService: AgentChatService,
+ private readonly conversationAccessService: AgentChatConversationAccessService,
+ private readonly streamRecoveryService: AgentChatStreamRecoveryService,
+ private readonly eventPublisherService: AgentChatEventPublisherService,
+ private readonly turnRecorderService: AgentTurnRecorderService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly messageReactionService: AgentChatMessageReactionService,
+ @InjectAgentHistoryRepository('agentChatThread')
+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
+ ) {}
+
+ @Query(() => [AgentMessageDTO])
+ async chatMessages(
+ @Args() conversation: AgentChatConversationInput,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthApplication({ allowUndefined: true })
+ callerApplication: FlatApplication | undefined,
+ @AuthWorkspaceMemberId() workspaceMemberId: string | undefined,
+ ) {
+ const workspaceId = workspace.id;
+ const threadId =
+ await this.conversationAccessService.resolveReadableThreadIdOrThrow({
+ workspace,
+ callerApplication,
+ workspaceMemberId,
+ conversation,
+ });
+ const messages = await this.agentChatService.getMessagesVisibleTo({
+ threadId,
+ workspaceMemberId,
+ applicationId: callerApplication?.id,
+ workspaceId,
+ });
+ const [{ flatWorkspaceMemberMaps }, reactionsByMessageId] =
+ await Promise.all([
+ this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatWorkspaceMemberMaps',
+ ]),
+ this.messageReactionService.findReactionsByMessageId({
+ workspaceId,
+ messageIds: messages.map(({ id }) => id),
+ }),
+ ]);
+
+ // fronts cached from the release before still name senders by their membership
+ return messages.map((message) => {
+ const senderUserId = isDefined(message.senderWorkspaceMemberId)
+ ? flatWorkspaceMemberMaps.byId[message.senderWorkspaceMemberId]?.userId
+ : undefined;
+
+ return {
+ ...message,
+ reactions: reactionsByMessageId.get(message.id) ?? [],
+ senderUserWorkspaceId: isDefined(senderUserId)
+ ? (flatWorkspaceMemberMaps.userWorkspaceIdByUserId[senderUserId] ??
+ null)
+ : null,
+ };
+ });
+ }
+
+ @Query(() => ChatStreamCatchupChunksDTO)
+ async chatStreamCatchupChunks(
+ @Args() conversation: AgentChatConversationInput,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthApplication({ allowUndefined: true })
+ callerApplication: FlatApplication | undefined,
+ @AuthWorkspaceMemberId() workspaceMemberId: string | undefined,
+ ) {
+ const workspaceId = workspace.id;
+ const threadId =
+ await this.conversationAccessService.resolveReadableThreadIdOrThrow({
+ workspace,
+ callerApplication,
+ workspaceMemberId,
+ conversation,
+ });
+ // an application's conversation has no thread until its first run starts
+ const thread = await this.threadRepository.findOne(workspaceId, {
+ where: { id: threadId },
+ select: ['id', 'activeStreamId'],
+ });
+
+ if (isDefined(thread)) {
+ await this.streamRecoveryService.reapDeadStream({ thread, workspaceId });
+ }
+
+ const { chunks, maxSeq } =
+ await this.eventPublisherService.getAccumulatedChunks(threadId);
+
+ const turnError = await this.turnRecorderService.findLatestTurnError({
+ workspaceId,
+ threadId,
+ });
+
+ return {
+ chunks: await this.conversationAccessService.getVisibleCatchupChunks({
+ workspaceId,
+ threadId,
+ workspaceMemberId,
+ applicationId: callerApplication?.id,
+ chunks,
+ }),
+ maxSeq,
+ error: isDefined(turnError)
+ ? { code: turnError.code, message: turnError.message }
+ : null,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-subscription.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-subscription.resolver.ts
index 75f2ab232d7..050a4826456 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-subscription.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-subscription.resolver.ts
@@ -1,18 +1,21 @@
import { createSubscriptionAuthorization } from 'src/engine/subscriptions/utils/create-subscription-authorization';
import { aiGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util';
-import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
+import { AgentChatConversationAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service';
+import { filterMapAsyncIterator } from 'src/engine/subscriptions/utils/filter-map-async-iterator';
import { withAsyncIteratorAuthorization } from 'src/engine/subscriptions/utils/with-async-iterator-authorization';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { UseGuards, UseInterceptors } from '@nestjs/common';
import { Args, Subscription } from '@nestjs/graphql';
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
import { PermissionFlagType } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
-import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { type ApplicationCallerOperation } from 'src/engine/core-modules/application/types/application-caller-operation.type';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
@@ -20,11 +23,20 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
import { AGENT_CHAT_KEEPALIVE_INTERVAL_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-keepalive-interval-ms.constant';
import { AGENT_CHAT_STREAM_REAP_CHECK_INTERVAL_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-stream-reap-check-interval-ms.constant';
+import { AgentChatEventInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.input';
+import { type AgentChatChannel } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-channel.type';
import { AgentChatEventDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.dto';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
import { wrapAsyncIteratorWithLifecycle } from 'src/engine/subscriptions/utils/wrap-async-iterator-with-lifecycle';
+type AgentChatEventPayload = {
+ onAgentChatEvent: {
+ threadId: string | null;
+ event: AgentChatSubscriptionEvent;
+ };
+};
+
@MetadataResolver()
@UseGuards(
AuthPrincipalGuard({
@@ -36,7 +48,7 @@ import { wrapAsyncIteratorWithLifecycle } from 'src/engine/subscriptions/utils/w
},
apiKey: false,
oauthClient: { withUser: true, withoutUser: false },
- application: { withUser: true, withoutUser: false },
+ application: true,
}),
)
@UseInterceptors(AiGraphqlApiExceptionInterceptor)
@@ -44,48 +56,65 @@ export class AgentChatSubscriptionResolver {
constructor(
private readonly subscriptionService: SubscriptionService,
private readonly streamRecoveryService: AgentChatStreamRecoveryService,
- private readonly sharingService: AgentChatSharingService,
+ private readonly conversationAccessService: AgentChatConversationAccessService,
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
) {}
- @Subscription(() => AgentChatEventDTO, {
- filter: (
- payload: { onAgentChatEvent: AgentChatEventDTO },
- variables: { threadId: string },
- ) => {
- return payload.onAgentChatEvent.threadId === variables.threadId;
- },
- })
+ @Subscription(() => AgentChatEventDTO)
@UseGuards(SettingsPermissionGuard(PermissionFlagType.AI))
async onAgentChatEvent(
- @Args('threadId', { type: () => UUIDScalarType }) threadId: string,
- @AuthWorkspace() workspace: WorkspaceEntity,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @Args() source: AgentChatEventInput,
+ @AuthWorkspace()
+ workspace: Pick<FlatWorkspace, 'id' | 'workspaceCustomApplicationId'>,
+ @AuthApplication({ allowUndefined: true })
+ callerApplication: ApplicationCallerOperation['callingApplication'],
+ @AuthWorkspaceMemberId() workspaceMemberId: string | undefined,
) {
+ let channel: AgentChatChannel = { kind: 'thread', channelId: '' };
const authorize = createSubscriptionAuthorization({
- check: () =>
- this.sharingService
- .getReadableThread({
- workspaceId: workspace.id,
- threadId,
+ check: async () => {
+ channel = await this.conversationAccessService
+ .resolveReadableChannelOrThrow({
+ workspace,
+ callerApplication,
workspaceMemberId,
+ source,
})
- .catch(aiGraphqlApiExceptionHandler),
+ .catch(aiGraphqlApiExceptionHandler);
+ },
maxAgeMs: AGENT_CHAT_KEEPALIVE_INTERVAL_MS,
});
+
await authorize();
- const iterator = await this.subscriptionService.subscribeToAgentChat({
- workspaceId: workspace.id,
- threadId,
- });
+ const { kind, channelId } = channel;
+ const threadId = kind === 'thread' ? channelId : null;
+ const filterVisibleEvent = isDefined(threadId)
+ ? this.conversationAccessService.createLiveEventFilter({
+ workspaceId: workspace.id,
+ threadId,
+ workspaceMemberId,
+ applicationId: callerApplication?.id,
+ })
+ : null;
- const keepalivePayload = {
- onAgentChatEvent: {
- threadId,
- event: { type: 'keepalive' as const },
- },
+ const iterator = filterMapAsyncIterator(
+ await this.subscriptionService.subscribeToAgentChat<AgentChatEventPayload>(
+ { workspaceId: workspace.id, threadId: channelId },
+ ),
+ async ({ onAgentChatEvent: { event } }) => ({
+ onAgentChatEvent: {
+ threadId,
+ event: isDefined(filterVisibleEvent)
+ ? await filterVisibleEvent(event)
+ : event,
+ },
+ }),
+ );
+
+ const keepalivePayload: AgentChatEventPayload = {
+ onAgentChatEvent: { threadId, event: { type: 'keepalive' } },
};
let lastReapCheckAt = 0;
@@ -97,8 +126,9 @@ export class AgentChatSubscriptionResolver {
onHeartbeat: async () => {
await authorize(true);
if (
+ isDefined(threadId) &&
Date.now() - lastReapCheckAt >=
- AGENT_CHAT_STREAM_REAP_CHECK_INTERVAL_MS
+ AGENT_CHAT_STREAM_REAP_CHECK_INTERVAL_MS
) {
lastReapCheckAt = Date.now();
await this.reapWatchedStreamIfDead(workspace.id, threadId);
@@ -106,7 +136,7 @@ export class AgentChatSubscriptionResolver {
await this.subscriptionService.publishToAgentChat({
workspaceId: workspace.id,
- threadId,
+ threadId: channelId,
payload: keepalivePayload,
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
index 17039787183..1e5c047a848 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
@@ -25,12 +25,10 @@ import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspac
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
-import { AgentMessageDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/agent-message.dto';
import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';
import { AgentChatThreadDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto';
import { FileAttachmentInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/file-attachment.input';
import { AiSystemPromptPreviewDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/ai-system-prompt-preview.dto';
-import { ChatStreamCatchupChunksDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/chat-stream-catchup-chunks.dto';
import { SendChatMessageResultDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-chat-message-result.dto';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
@@ -38,7 +36,6 @@ import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/a
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-import { AgentChatMessageReactionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-message-reaction.service';
import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { SystemPromptBuilderService } from 'src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service';
import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
@@ -50,8 +47,6 @@ import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billin
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
-import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
@UseGuards(
@@ -87,10 +82,7 @@ export class AgentChatResolver {
private readonly systemPromptBuilderService: SystemPromptBuilderService,
private readonly turnPreflightService: AgentChatTurnPreflightService,
private readonly threadLifecycleService: AgentChatThreadLifecycleService,
- private readonly turnRecorderService: AgentTurnRecorderService,
- private readonly workspaceCacheService: WorkspaceCacheService,
private readonly featureFlagService: FeatureFlagService,
- private readonly messageReactionService: AgentChatMessageReactionService,
) {}
@Query(() => AgentChatThreadDTO)
@@ -107,79 +99,6 @@ export class AgentChatResolver {
});
}
- @Query(() => [AgentMessageDTO])
- async chatMessages(
- @Args('threadId', { type: () => UUIDScalarType }) threadId: string,
-
- @AuthWorkspaceMemberId() workspaceMemberId: string,
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
- ) {
- const messages = await this.agentChatService.getMessagesForThread({
- threadId,
- workspaceMemberId,
- workspaceId,
- });
- const [{ flatWorkspaceMemberMaps }, reactionsByMessageId] =
- await Promise.all([
- this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'flatWorkspaceMemberMaps',
- ]),
- this.messageReactionService.findReactionsByMessageId({
- workspaceId,
- messageIds: messages.map(({ id }) => id),
- }),
- ]);
-
- // Fronts cached from the release before still name senders by their
- // membership, which messages no longer store
- return messages.map((message) => {
- const senderUserId = isDefined(message.senderWorkspaceMemberId)
- ? flatWorkspaceMemberMaps.byId[message.senderWorkspaceMemberId]?.userId
- : undefined;
-
- return {
- ...message,
- reactions: reactionsByMessageId.get(message.id) ?? [],
- senderUserWorkspaceId: isDefined(senderUserId)
- ? (flatWorkspaceMemberMaps.userWorkspaceIdByUserId[senderUserId] ??
- null)
- : null,
- };
- });
- }
-
- @Query(() => ChatStreamCatchupChunksDTO)
- async chatStreamCatchupChunks(
- @Args('threadId', { type: () => UUIDScalarType }) threadId: string,
-
- @AuthWorkspaceMemberId() workspaceMemberId: string,
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
- ) {
- const thread = await this.sharingService.getReadableThread({
- threadId,
- workspaceMemberId,
- workspaceId,
- });
-
- await this.reapDeadStream(thread, workspaceId);
-
- const { chunks, maxSeq } =
- await this.eventPublisherService.getAccumulatedChunks(threadId);
-
- const turnError = await this.turnRecorderService.findLatestTurnError({
- workspaceId,
- threadId,
- });
-
- return {
- chunks,
- maxSeq,
- error: turnError
- ? { code: turnError.code, message: turnError.message }
- : null,
- };
- }
-
@Mutation(() => AgentChatThreadDTO)
async createChatThread(
@AuthWorkspaceMemberId() workspaceMemberId: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-conversation-access.service.resolve-channel.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-conversation-access.service.resolve-channel.spec.ts
new file mode 100644
index 00000000000..3a387b5ccaf
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-conversation-access.service.resolve-channel.spec.ts
@@ -0,0 +1,164 @@
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { buildAgentRunStreamChannelId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util';
+import { AgentChatConversationAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+
+const WORKSPACE = {
+ id: 'workspace-id',
+ workspaceCustomApplicationId: 'workspace-custom-application-id',
+};
+const RUN_ID = '3f1c9a52-7b0e-4d6a-8c2f-9e4b5a6d7c81';
+const buildApplication = (id: string) => ({
+ id,
+ universalIdentifier: `${id}-universal-identifier`,
+ sourceType: ApplicationRegistrationSourceType.NPM,
+});
+
+const buildService = () => {
+ const agentRunService = {
+ resolveConversationThreadIdOrThrow: jest
+ .fn()
+ .mockResolvedValue('conversation-thread-id'),
+ };
+
+ return {
+ service: new AgentChatConversationAccessService(
+ {} as never,
+ agentRunService as never,
+ {} as never,
+ ),
+ agentRunService,
+ };
+};
+
+describe('AgentChatConversationAccessService.resolveReadableChannelOrThrow', () => {
+ it('names the channel of a run by the caller application and the run id', async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication: buildApplication('application-a'),
+ workspaceMemberId: undefined,
+ source: { runId: RUN_ID },
+ }),
+ ).resolves.toEqual({
+ kind: 'run',
+ channelId: buildAgentRunStreamChannelId({
+ applicationId: 'application-a',
+ callerWorkspaceMemberId: null,
+ runId: RUN_ID,
+ }),
+ });
+ });
+
+ describe('for a run another member started through the same application', () => {
+ const MEMBER_ID = 'member-a';
+ const OTHER_MEMBER_ID = 'member-b';
+ const otherMemberRunChannelId = buildAgentRunStreamChannelId({
+ applicationId: 'application-a',
+ callerWorkspaceMemberId: OTHER_MEMBER_ID,
+ runId: RUN_ID,
+ });
+ const resolveFor = (workspaceMemberId: string | undefined) =>
+ buildService().service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication: buildApplication('application-a'),
+ workspaceMemberId,
+ source: { runId: RUN_ID },
+ });
+
+ it('keeps a member from following it by its run id', async () => {
+ expect((await resolveFor(MEMBER_ID)).channelId).not.toBe(
+ otherMemberRunChannelId,
+ );
+ expect((await resolveFor(OTHER_MEMBER_ID)).channelId).toBe(
+ otherMemberRunChannelId,
+ );
+ });
+
+ it('keeps an application-only token from following it, which reads only runs the application started alone', async () => {
+ expect((await resolveFor(undefined)).channelId).not.toBe(
+ otherMemberRunChannelId,
+ );
+ expect((await resolveFor(undefined)).channelId).toBe(
+ buildAgentRunStreamChannelId({
+ applicationId: 'application-a',
+ callerWorkspaceMemberId: null,
+ runId: RUN_ID,
+ }),
+ );
+ });
+ });
+
+ it('gives another application naming the same run another channel', async () => {
+ const { service } = buildService();
+ const resolveFor = (applicationId: string) =>
+ service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication: buildApplication(applicationId),
+ workspaceMemberId: undefined,
+ source: { runId: RUN_ID },
+ });
+
+ expect((await resolveFor('application-b')).channelId).not.toBe(
+ (await resolveFor('application-a')).channelId,
+ );
+ });
+
+ it('refuses a run id without an application token', async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication: undefined,
+ workspaceMemberId: 'workspace-member-id',
+ source: { runId: RUN_ID },
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });
+ });
+
+ it('refuses a run id together with a conversation', async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication: buildApplication('application-a'),
+ workspaceMemberId: undefined,
+ source: {
+ runId: RUN_ID,
+ agentUniversalIdentifier: 'agent-universal-identifier',
+ threadKey: 'deal-42',
+ },
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_AGENT_INPUT });
+ });
+
+ it('resolves a conversation as before when no run id is given', async () => {
+ const { service, agentRunService } = buildService();
+ const callerApplication = buildApplication('application-a');
+
+ await expect(
+ service.resolveReadableChannelOrThrow({
+ workspace: WORKSPACE,
+ callerApplication,
+ workspaceMemberId: undefined,
+ source: {
+ runId: null,
+ agentUniversalIdentifier: 'agent-universal-identifier',
+ threadKey: 'deal-42',
+ },
+ }),
+ ).resolves.toEqual({ kind: 'thread', channelId: 'conversation-thread-id' });
+ expect(
+ agentRunService.resolveConversationThreadIdOrThrow,
+ ).toHaveBeenCalledWith({
+ workspace: WORKSPACE,
+ callerApplication,
+ agentUniversalIdentifier: 'agent-universal-identifier',
+ threadKey: 'deal-42',
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-turn-stream.service.stream-turn.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-turn-stream.service.stream-turn.spec.ts
new file mode 100644
index 00000000000..5e77ea00fae
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-turn-stream.service.stream-turn.spec.ts
@@ -0,0 +1,376 @@
+import { Test } from '@nestjs/testing';
+
+import { AgentChatCancelSubscriberService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-cancel-subscriber.service';
+import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
+import { AgentChatStreamHeartbeatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-heartbeat.service';
+import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentTurnStreamService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+import { getAgentHistoryRepositoryToken } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
+import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
+import { STREAM_EXECUTION_FAILED_CODE } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
+
+const buildService = async ({
+ finish,
+ eventPublisherService = {},
+}: {
+ finish: jest.Mock;
+ eventPublisherService?: Record<string, jest.Mock>;
+}) => {
+ const module = await Test.createTestingModule({
+ providers: [
+ AgentTurnStreamService,
+ {
+ provide: getAgentHistoryRepositoryToken('agentChatThread'),
+ useValue: {},
+ },
+ {
+ provide: AgentChatEventPublisherService,
+ useValue: eventPublisherService,
+ },
+ { provide: AgentChatCancelSubscriberService, useValue: {} },
+ { provide: AgentChatStreamHeartbeatService, useValue: {} },
+ { provide: AgentChatStreamRecoveryService, useValue: {} },
+ { provide: AgentConversationWriterService, useValue: {} },
+ {
+ provide: AgentTurnRecorderService,
+ useValue: { finish, recordUsage: jest.fn() },
+ },
+ { provide: AgentChatThreadService, useValue: {} },
+ ],
+ }).compile();
+
+ module.useLogger(false);
+
+ return module.get(AgentTurnStreamService);
+};
+
+const streamTurnWithoutClaim = ({
+ service,
+ turnError,
+ streamChannelId,
+}: {
+ service: AgentTurnStreamService;
+ turnError: Error;
+ streamChannelId?: string;
+}) =>
+ service.streamTurn({
+ workspaceId: 'workspace-id',
+ claim: null,
+ streamChannelId,
+ turnId: 'turn-id',
+ startTurn: () => Promise.reject(turnError),
+ completeTurn: jest.fn(),
+ isBackgroundRun: true,
+ });
+
+const REPLY_PARTS = [
+ { type: 'start' },
+ { type: 'text-start', id: 'text-1' },
+ { type: 'text-delta', id: 'text-1', text: 'Acme renews in May' },
+ { type: 'text-end', id: 'text-1' },
+ { type: 'finish', finishReason: 'stop', totalUsage: {} },
+];
+
+const streamPartsWithoutClaim = ({
+ service,
+ parts = REPLY_PARTS,
+ streamChannelId,
+}: {
+ service: AgentTurnStreamService;
+ parts?: Record<string, unknown>[];
+ streamChannelId?: string;
+}) =>
+ service.streamTurn({
+ workspaceId: 'workspace-id',
+ claim: null,
+ streamChannelId,
+ turnId: 'turn-id',
+ startTurn: async () => ({
+ source: {
+ modelConfig: {
+ contextWindowTokens: 1000,
+ inputCostPerMillionTokens: 1,
+ outputCostPerMillionTokens: 1,
+ } as never,
+ parts: new ReadableStream({
+ start(controller) {
+ parts.forEach((part) => controller.enqueue(part as never));
+ controller.close();
+ },
+ }),
+ },
+ }),
+ completeTurn: async () => ({ modelId: 'model-id', stopReason: null }),
+ isBackgroundRun: true,
+ });
+
+const expectFailureRecordedOnce = (finish: jest.Mock) => {
+ expect(finish).toHaveBeenCalledTimes(1);
+ expect(finish).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ turnId: 'turn-id',
+ status: AgentTurnStatus.FAILED,
+ error: {
+ code: STREAM_EXECUTION_FAILED_CODE,
+ message: 'Provider unavailable',
+ },
+ });
+};
+
+describe('AgentTurnStreamService streamTurn without a claim', () => {
+ it('records the turn as failed', async () => {
+ const finish = jest.fn().mockResolvedValue(true);
+ const turnError = new Error('Provider unavailable');
+
+ await expect(
+ streamTurnWithoutClaim({
+ service: await buildService({ finish }),
+ turnError,
+ }),
+ ).rejects.toBe(turnError);
+
+ expectFailureRecordedOnce(finish);
+ });
+
+ it('fails with the turn error when recording the failure fails', async () => {
+ const finish = jest
+ .fn()
+ .mockRejectedValue(new Error('Database unavailable'));
+ const turnError = new Error('Provider unavailable');
+
+ await expect(
+ streamTurnWithoutClaim({
+ service: await buildService({ finish }),
+ turnError,
+ }),
+ ).rejects.toBe(turnError);
+
+ expectFailureRecordedOnce(finish);
+ });
+});
+
+describe('AgentTurnStreamService streamTurn of a followed run', () => {
+ const buildPublisher = () => ({
+ publish: jest.fn().mockResolvedValue(undefined),
+ resetStreamState: jest.fn().mockResolvedValue(undefined),
+ });
+
+ it('publishes nothing when no one follows the run', async () => {
+ const eventPublisherService = buildPublisher();
+
+ await streamPartsWithoutClaim({
+ service: await buildService({ finish: jest.fn(), eventPublisherService }),
+ });
+
+ expect(eventPublisherService.publish).not.toHaveBeenCalled();
+ });
+
+ it('publishes each UI chunk to the run channel, then the end of the run, never a saved message', async () => {
+ const eventPublisherService = buildPublisher();
+
+ await streamPartsWithoutClaim({
+ service: await buildService({ finish: jest.fn(), eventPublisherService }),
+ streamChannelId: 'run-channel-id',
+ });
+
+ const publishedEvents = eventPublisherService.publish.mock.calls.map(
+ ([{ threadId, event }]) => {
+ expect(threadId).toBe('run-channel-id');
+
+ return event;
+ },
+ );
+
+ expect(
+ publishedEvents
+ .filter(({ type }) => type === 'stream-chunk')
+ .map(({ chunk }) => chunk.type),
+ ).toEqual(['start', 'text-start', 'text-delta', 'text-end', 'finish']);
+ expect(publishedEvents[publishedEvents.length - 1]).toEqual({
+ type: 'run-finished',
+ turnId: 'turn-id',
+ });
+ expect(publishedEvents.map(({ type }) => type)).not.toContain(
+ 'message-persisted',
+ );
+ });
+
+ it('keeps a finished run completed when its end event cannot be sent', async () => {
+ const finish = jest.fn().mockResolvedValue(true);
+ const eventPublisherService = {
+ publish: jest.fn(async ({ event }: { event: { type: string } }) => {
+ if (event.type === 'run-finished') {
+ throw new Error('Redis unavailable');
+ }
+ }),
+ resetStreamState: jest.fn().mockResolvedValue(undefined),
+ };
+
+ await expect(
+ streamPartsWithoutClaim({
+ service: await buildService({ finish, eventPublisherService }),
+ streamChannelId: 'run-channel-id',
+ }),
+ ).resolves.toMatchObject({ finish: { outcome: { kind: 'completed' } } });
+
+ expect(finish).toHaveBeenCalledTimes(1);
+ expect(finish).toHaveBeenCalledWith(
+ expect.objectContaining({
+ turnId: 'turn-id',
+ status: AgentTurnStatus.COMPLETED,
+ }),
+ );
+ });
+
+ it('ends the run channel with the error of a failed run', async () => {
+ const eventPublisherService = buildPublisher();
+ const finish = jest.fn().mockResolvedValue(true);
+ const turnError = new Error('Provider unavailable');
+
+ await expect(
+ streamTurnWithoutClaim({
+ service: await buildService({ finish, eventPublisherService }),
+ turnError,
+ streamChannelId: 'run-channel-id',
+ }),
+ ).rejects.toBe(turnError);
+
+ expectFailureRecordedOnce(finish);
+ expect(eventPublisherService.publish).toHaveBeenCalledTimes(1);
+ expect(eventPublisherService.publish).toHaveBeenCalledWith({
+ threadId: 'run-channel-id',
+ workspaceId: 'workspace-id',
+ event: {
+ type: 'stream-error',
+ code: 'STREAM_EXECUTION_FAILED',
+ message: 'Provider unavailable',
+ },
+ shouldKeepCatchup: false,
+ });
+ });
+});
+
+describe('AgentTurnStreamService streamTurn usage', () => {
+ it('counts the usage a model reports with an error finish reason', async () => {
+ const { streamed } = await streamPartsWithoutClaim({
+ service: await buildService({
+ finish: jest.fn().mockResolvedValue(true),
+ }),
+ parts: [
+ { type: 'start' },
+ { type: 'start-step' },
+ {
+ type: 'finish-step',
+ finishReason: 'error',
+ usage: { inputTokens: 120, outputTokens: 8 },
+ },
+ { type: 'start-step' },
+ {
+ type: 'finish-step',
+ finishReason: 'error',
+ usage: { inputTokens: undefined, outputTokens: undefined },
+ },
+ { type: 'finish', finishReason: 'error', totalUsage: {} },
+ ],
+ });
+
+ expect(streamed.usage).toMatchObject({
+ inputTokens: 120,
+ outputTokens: 8,
+ conversationSize: 120,
+ });
+ });
+});
+
+describe('AgentTurnStreamService streamTurn of a claimed turn', () => {
+ it('keeps a finished turn completed when its end event cannot be sent', async () => {
+ const finish = jest.fn().mockResolvedValue(true);
+ const publish = jest.fn(async ({ event }: { event: { type: string } }) => {
+ if (event.type === 'message-persisted') {
+ throw new Error('Redis unavailable');
+ }
+ });
+
+ const service = await buildService({
+ finish,
+ eventPublisherService: { publish },
+ });
+
+ await expect(
+ service.streamTurn({
+ workspaceId: 'workspace-id',
+ claim: {
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ streamId: 'stream-id',
+ },
+ turnId: 'turn-id',
+ startTurn: async () => ({
+ source: {
+ modelConfig: { contextWindowTokens: 1000 } as never,
+ parts: new ReadableStream({
+ start(controller) {
+ [
+ { type: 'start' },
+ { type: 'finish', finishReason: 'stop', totalUsage: {} },
+ ].forEach((part) => controller.enqueue(part as never));
+ controller.close();
+ },
+ }),
+ },
+ }),
+ completeTurn: async () => ({ modelId: 'model-id', stopReason: null }),
+ isBackgroundRun: true,
+ }),
+ ).resolves.toMatchObject({ finish: { outcome: { kind: 'completed' } } });
+
+ expect(finish).toHaveBeenCalledTimes(1);
+ expect(finish).toHaveBeenCalledWith(
+ expect.objectContaining({
+ turnId: 'turn-id',
+ status: AgentTurnStatus.COMPLETED,
+ }),
+ );
+ });
+});
+
+describe('AgentTurnStreamService streamTurn of a run without a conversation', () => {
+ it('records a run stopped after its stream ended as cancelled', async () => {
+ const finish = jest.fn().mockResolvedValue(true);
+ const service = await buildService({ finish });
+
+ await service.streamTurn({
+ workspaceId: 'workspace-id',
+ claim: null,
+ turnId: 'turn-id',
+ startTurn: async () => ({
+ source: {
+ modelConfig: { contextWindowTokens: 1000 } as never,
+ parts: new ReadableStream({
+ start(controller) {
+ [
+ { type: 'start' },
+ { type: 'finish', finishReason: 'stop', totalUsage: {} },
+ ].forEach((part) => controller.enqueue(part as never));
+ controller.close();
+ },
+ }),
+ },
+ }),
+ completeTurn: async () => ({
+ modelId: 'model-id',
+ stopReason: null,
+ isAborted: true,
+ }),
+ isBackgroundRun: true,
+ });
+
+ expect(finish).toHaveBeenCalledTimes(1);
+ expect(finish).toHaveBeenCalledWith(
+ expect.objectContaining({ status: AgentTurnStatus.CANCELLED }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service.ts
new file mode 100644
index 00000000000..a76c268de2b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-conversation-access.service.ts
@@ -0,0 +1,174 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined, isNonEmptyString } from 'twenty-shared/utils';
+
+import { type ApplicationCallerOperation } from 'src/engine/core-modules/application/types/application-caller-operation.type';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';
+import { buildAgentRunStreamChannelId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-stream-channel-id.util';
+import { type AgentChatConversationInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-conversation.input';
+import { type AgentChatEventInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-event.input';
+import { type AgentChatChannel } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-channel.type';
+import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
+import { createAgentChatLiveEventFilter } from 'src/engine/metadata-modules/ai/ai-chat/utils/create-agent-chat-live-event-filter.util';
+import { isAgentTurnOpenedByOtherMember } from 'src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util';
+import { throwAgentChatThreadNotFound } from 'src/engine/metadata-modules/ai/ai-chat/utils/throw-agent-chat-thread-not-found.util';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { type AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
+import { maskStreamChunkOfTurnActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+type ConversationReader = {
+ workspace: Pick<FlatWorkspace, 'id' | 'workspaceCustomApplicationId'>;
+ callerApplication: ApplicationCallerOperation['callingApplication'];
+ workspaceMemberId: string | undefined;
+};
+
+type ConversationViewer = {
+ workspaceId: string;
+ threadId: string;
+ workspaceMemberId: string | undefined;
+ applicationId?: string;
+};
+
+@Injectable()
+export class AgentChatConversationAccessService {
+ constructor(
+ private readonly sharingService: AgentChatSharingService,
+ private readonly agentRunService: AgentRunService,
+ @InjectAgentHistoryRepository('agentTurn')
+ private readonly turnRepository: AgentHistoryRepository<AgentTurnWorkspaceEntity>,
+ ) {}
+
+ async resolveReadableChannelOrThrow({
+ source: { runId, ...conversation },
+ ...reader
+ }: ConversationReader & {
+ source: Pick<
+ AgentChatEventInput,
+ 'threadId' | 'agentUniversalIdentifier' | 'threadKey' | 'runId'
+ >;
+ }): Promise<AgentChatChannel> {
+ if (!isDefined(runId)) {
+ return {
+ kind: 'thread',
+ channelId: await this.resolveReadableThreadIdOrThrow({
+ ...reader,
+ conversation,
+ }),
+ };
+ }
+
+ if (
+ !isDefined(reader.callerApplication) ||
+ Object.values(conversation).some(isDefined)
+ ) {
+ throw new AiException(
+ 'Pass runId alone, with an application access token',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ return {
+ kind: 'run',
+ channelId: buildAgentRunStreamChannelId({
+ applicationId: reader.callerApplication.id,
+ callerWorkspaceMemberId: reader.workspaceMemberId ?? null,
+ runId,
+ }),
+ };
+ }
+
+ async resolveReadableThreadIdOrThrow({
+ workspace,
+ callerApplication,
+ workspaceMemberId,
+ conversation: { threadId, agentUniversalIdentifier, threadKey },
+ }: ConversationReader & {
+ conversation: Pick<
+ AgentChatConversationInput,
+ 'threadId' | 'agentUniversalIdentifier' | 'threadKey'
+ >;
+ }): Promise<string> {
+ const isNamedByKey =
+ isDefined(agentUniversalIdentifier) || isDefined(threadKey);
+
+ if (isDefined(threadId) && !isNamedByKey) {
+ if (!isDefined(workspaceMemberId)) {
+ return throwAgentChatThreadNotFound();
+ }
+
+ await this.sharingService.getReadableThread({
+ workspaceId: workspace.id,
+ threadId,
+ workspaceMemberId,
+ });
+
+ return threadId;
+ }
+
+ if (
+ isDefined(threadId) ||
+ !isDefined(callerApplication) ||
+ !isNonEmptyString(agentUniversalIdentifier) ||
+ !isNonEmptyString(threadKey?.trim())
+ ) {
+ throw new AiException(
+ 'Pass either threadId, or agentUniversalIdentifier and threadKey with an application access token',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ return this.agentRunService.resolveConversationThreadIdOrThrow({
+ workspace,
+ callerApplication,
+ agentUniversalIdentifier,
+ threadKey,
+ });
+ }
+
+ async getVisibleCatchupChunks({
+ chunks,
+ ...viewer
+ }: ConversationViewer & {
+ chunks: Record<string, unknown>[];
+ }): Promise<Record<string, unknown>[]> {
+ if (!(await this.isLatestTurnOpenedByOtherMember(viewer))) {
+ return chunks;
+ }
+
+ return chunks.map(maskStreamChunkOfTurnActedByOthers);
+ }
+
+ createLiveEventFilter(viewer: ConversationViewer) {
+ return createAgentChatLiveEventFilter({
+ isStreamingTurnHidden: () => this.isLatestTurnOpenedByOtherMember(viewer),
+ });
+ }
+
+ // the latest turn is the one streaming
+ private async isLatestTurnOpenedByOtherMember({
+ workspaceId,
+ threadId,
+ workspaceMemberId,
+ applicationId,
+ }: ConversationViewer): Promise<boolean> {
+ const latestTurn = await this.turnRepository.findOne(workspaceId, {
+ where: { threadId },
+ order: { createdAt: 'DESC', id: 'DESC' },
+ });
+
+ return (
+ isDefined(latestTurn?.createdBy) &&
+ isAgentTurnOpenedByOtherMember({
+ createdBy: latestTurn.createdBy,
+ workspaceMemberId,
+ applicationId,
+ })
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service.ts
index 14e6514fc53..becfcb1fea1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service.ts
@@ -31,18 +31,41 @@ export class AgentChatEventPublisherService {
threadId,
workspaceId,
event,
+ shouldKeepCatchup = true,
}: {
threadId: string;
workspaceId: string;
event: AgentChatSubscriptionEvent;
+ // a run channel is followed from before its run starts, so nothing reads catch-up chunks for it
+ shouldKeepCatchup?: boolean;
}): Promise<void> {
- let publishedEvent = event;
+ const publishedEvent = shouldKeepCatchup
+ ? await this.keepCatchup({ threadId, event })
+ : event;
- if (event.type === 'stream-chunk') {
- const redis = this.redisClientService.getClient();
- const key = this.getStreamChunksKey(threadId);
+ await this.subscriptionService.publishToAgentChat({
+ workspaceId,
+ threadId,
+ payload: {
+ onAgentChatEvent: {
+ threadId,
+ event: publishedEvent,
+ },
+ },
+ });
+ }
+
+ private async keepCatchup({
+ threadId,
+ event,
+ }: {
+ threadId: string;
+ event: AgentChatSubscriptionEvent;
+ }): Promise<AgentChatSubscriptionEvent> {
+ const redis = this.redisClientService.getClient();
+ const key = this.getStreamChunksKey(threadId);
- // RPUSH returns the new list length — use it as a 1-based sequence number.
+ if (event.type === 'stream-chunk') {
// Sent together on one connection, Redis still runs them in order.
const [seq] = await Promise.all([
redis.rpush(key, JSON.stringify(event.chunk)),
@@ -53,25 +76,17 @@ export class AgentChatEventPublisherService {
),
]);
- publishedEvent = { ...event, seq };
- } else if (
+ return { ...event, seq };
+ }
+
+ if (
event.type === 'message-persisted' ||
event.type === 'credits-exhausted'
) {
- const redis = this.redisClientService.getClient();
- await redis.del(this.getStreamChunksKey(threadId));
+ await redis.del(key);
}
- await this.subscriptionService.publishToAgentChat({
- workspaceId,
- threadId,
- payload: {
- onAgentChatEvent: {
- threadId,
- event: publishedEvent,
- },
- },
- });
+ return event;
}
async resetStreamState(threadId: string): Promise<void> {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service.ts
index b75790ec96b..d68357e72ba 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service.ts
@@ -10,6 +10,7 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import { AGENT_TURN_INTERRUPTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant';
import { AgentMessageStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-status.enum';
import { AGENT_CHAT_WAITING_RUN_OWNER_TYPE } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-waiting-run-owner-type.constant';
import { FLUSH_QUEUED_AGENT_CHAT_MESSAGES_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/flush-queued-agent-chat-messages-job-name.constant';
@@ -21,7 +22,6 @@ import { type StreamErrorPayload } from 'src/engine/metadata-modules/ai/ai-histo
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
@@ -140,16 +140,11 @@ export class AgentChatStreamRecoveryService {
return null;
}
- const interruptedError: StreamErrorPayload = {
- code: AiExceptionCode.STREAM_INTERRUPTED,
- message: 'The response was interrupted before it could finish.',
- };
-
const hasReaped = await this.release({
threadId: thread.id,
workspaceId,
streamId: thread.activeStreamId,
- turnError: interruptedError,
+ turnError: AGENT_TURN_INTERRUPTED_ERROR,
shouldFlush: true,
});
@@ -162,7 +157,7 @@ export class AgentChatStreamRecoveryService {
amount: 1,
attributes: {
failure_phase: 'interrupted',
- error_code: interruptedError.code,
+ error_code: AGENT_TURN_INTERRUPTED_ERROR.code,
},
});
@@ -170,7 +165,7 @@ export class AgentChatStreamRecoveryService {
`[AI_CHAT_TURN_FAILED] failurePhase=interrupted, threadId=${thread.id}, workspaceId=${workspaceId}: stream ${thread.activeStreamId} stopped sending heartbeats`,
);
- return interruptedError;
+ return AGENT_TURN_INTERRUPTED_ERROR;
}
// the oldest queued message is the queue's place in line, so it and the runs go in the order they came
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
index 1603402663b..949146eaa89 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
@@ -28,6 +28,7 @@ import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/s
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { AgentTitleGenerationService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service';
import { type AgentHistoryTransactionScope } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type';
+import { isAgentTurnOpenedByOtherMember } from 'src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util';
type AddMessageArgs = {
threadId: string;
@@ -273,6 +274,24 @@ export class AgentChatService {
workspaceId,
});
+ return this.getMessagesVisibleTo({
+ threadId,
+ workspaceMemberId,
+ workspaceId,
+ });
+ }
+
+ async getMessagesVisibleTo({
+ threadId,
+ workspaceMemberId,
+ applicationId,
+ workspaceId,
+ }: {
+ threadId: string;
+ workspaceMemberId: string | undefined;
+ applicationId?: string;
+ workspaceId: string;
+ }) {
// contexts are given to the model, never shown
const [messages, turns] = await Promise.all([
this.messageRepository.find(workspaceId, {
@@ -288,10 +307,12 @@ export class AgentChatService {
// the opener is stamped on the turn, so a run resumed in a new turn after a pause is still theirs
const turnIdsOpenedByOtherMembers = new Set(
turns
- .filter(
- ({ createdBy }) =>
- isDefined(createdBy.workspaceMemberId) &&
- createdBy.workspaceMemberId !== workspaceMemberId,
+ .filter(({ createdBy }) =>
+ isAgentTurnOpenedByOtherMember({
+ createdBy,
+ workspaceMemberId,
+ applicationId,
+ }),
)
.map(({ id }) => id),
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service.ts
index 5cbe7b59504..fe9020181e2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-turn-stream.service.ts
@@ -49,6 +49,7 @@ import { mapAgentChatTurnOutcomeToTurnStatus } from 'src/engine/metadata-modules
import { updateAgentChatThreadUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { AgentTurnRecorderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
@@ -85,9 +86,39 @@ export type AgentTurnCompletion = {
modelId: string;
stopReason: StepDebitResult['stopReason'];
isWaiting?: boolean;
+ // a stop the caller saw land after the stream ended, so the turn is recorded as stopped too
+ isAborted?: boolean;
usage?: AgentTurnStreamUsage;
};
+export type AgentTurnStreamInput<
+ TStarted extends { source: AgentTurnStreamSource },
+ TCompletion extends AgentTurnCompletion,
+> = {
+ workspaceId: string;
+ claim: AgentChatStreamClaim | null;
+ // where a turn without a claim streams, when its caller follows it; a claimed turn streams to its thread
+ streamChannelId?: string;
+ turnId: string;
+ abortSignal?: AbortSignal;
+ startTurn: (
+ writer: UIMessageStreamWriter<ExtendedUIMessage>,
+ ) => Promise<TStarted>;
+ completeTurn: (
+ streamed: AgentTurnStreamResult & { started: TStarted },
+ ) => Promise<TCompletion>;
+ isBackgroundRun?: boolean;
+};
+
+export type AgentTurnStreamOutput<
+ TStarted extends { source: AgentTurnStreamSource },
+ TCompletion extends AgentTurnCompletion,
+> = {
+ streamed: AgentTurnStreamResult & { started: TStarted };
+ completion: TCompletion;
+ finish: AgentTurnFinish | null;
+};
+
export type AgentTurnFinish = {
outcome: AgentChatTurnOutcome;
isAwaitingAnswer: boolean;
@@ -202,31 +233,74 @@ export class AgentTurnStreamService {
async streamTurn<
TStarted extends { source: AgentTurnStreamSource },
TCompletion extends AgentTurnCompletion,
+ >(
+ input: AgentTurnStreamInput<TStarted, TCompletion>,
+ ): Promise<AgentTurnStreamOutput<TStarted, TCompletion>> {
+ const { workspaceId, claim, streamChannelId, turnId } = input;
+
+ return this.streamAndFinishTurn(input).catch(async (error: unknown) => {
+ // a claimed turn's failure is recorded and published when its claim is released
+ if (!isDefined(claim)) {
+ const turnError = mapErrorToStreamError(error);
+
+ // a failure to record it must not hide why the turn failed
+ await this.turnRecorderService
+ .finish({
+ workspaceId,
+ turnId,
+ status: AgentTurnStatus.FAILED,
+ error: turnError,
+ })
+ .catch((finishError: unknown) =>
+ this.logger.warn(
+ `Could not record the failure of turn ${turnId} in workspace ${workspaceId}: ${formatErrorWithCause(finishError)}`,
+ ),
+ );
+
+ if (isDefined(streamChannelId)) {
+ await this.eventPublisherService
+ .publish({
+ threadId: streamChannelId,
+ workspaceId,
+ event: { type: 'stream-error', ...turnError },
+ shouldKeepCatchup: false,
+ })
+ .catch((publishError: unknown) =>
+ this.logger.warn(
+ `Could not publish the failure of channel ${streamChannelId} in workspace ${workspaceId}: ${formatErrorWithCause(publishError)}`,
+ ),
+ );
+ }
+ }
+
+ throw error;
+ });
+ }
+
+ private async streamAndFinishTurn<
+ TStarted extends { source: AgentTurnStreamSource },
+ TCompletion extends AgentTurnCompletion,
>({
+ workspaceId,
claim,
+ streamChannelId,
turnId,
abortSignal,
startTurn,
completeTurn,
isBackgroundRun = false,
- }: {
- claim: AgentChatStreamClaim;
- turnId: string;
- abortSignal: AbortSignal;
- startTurn: (
- writer: UIMessageStreamWriter<ExtendedUIMessage>,
- ) => Promise<TStarted>;
- completeTurn: (
- streamed: AgentTurnStreamResult & { started: TStarted },
- ) => Promise<TCompletion>;
- isBackgroundRun?: boolean;
- }): Promise<{
- streamed: AgentTurnStreamResult & { started: TStarted };
- completion: TCompletion;
- finish: AgentTurnFinish | null;
- }> {
- const { workspaceId, threadId } = claim;
- const streamed = await this.stream({ claim, turnId, startTurn });
+ }: AgentTurnStreamInput<TStarted, TCompletion>): Promise<
+ AgentTurnStreamOutput<TStarted, TCompletion>
+ > {
+ const threadId = claim?.threadId ?? null;
+ const channelId = threadId ?? streamChannelId;
+ const streamed = await this.stream({
+ workspaceId,
+ claim,
+ channelId,
+ turnId,
+ startTurn,
+ });
const completion = await completeTurn(streamed).catch(
async (error: unknown) => {
await this.turnRecorderService.recordUsage({
@@ -241,9 +315,14 @@ export class AgentTurnStreamService {
);
const finish = await this.finishTurn({
+ workspaceId,
claim,
turnId,
- result: { ...streamed, usage: completion.usage ?? streamed.usage },
+ result: {
+ ...streamed,
+ isAborted: streamed.isAborted || completion.isAborted === true,
+ usage: completion.usage ?? streamed.usage,
+ },
modelId: completion.modelId,
stopReason: completion.stopReason,
isWaiting: completion.isWaiting,
@@ -251,7 +330,7 @@ export class AgentTurnStreamService {
});
// a worker shutting down interrupted the turn, which fails rather than ends as stopped
- if (abortSignal.reason instanceof AiException) {
+ if (abortSignal?.reason instanceof AiException) {
throw abortSignal.reason;
}
@@ -259,35 +338,55 @@ export class AgentTurnStreamService {
throw streamed.streamError;
}
- // the end event follows every chunk, so a subscriber that sees it has the whole reply
- await this.eventPublisherService.publish({
- threadId,
- workspaceId,
- event:
- completion.stopReason === 'workspaceAllowance'
- ? { type: 'credits-exhausted' }
- : {
- type: 'message-persisted',
- messageId: streamed.assistantMessageId,
- },
- });
+ if (!isDefined(channelId)) {
+ return { streamed, completion, finish };
+ }
+
+ // the end event follows every chunk, so a subscriber that sees it has the whole reply. The turn is
+ // already finished, so a failed send keeps its outcome: live subscribers see the connection as lost,
+ // and the saved reply shows once the thread reloads
+ await this.eventPublisherService
+ .publish({
+ threadId: channelId,
+ workspaceId,
+ event:
+ completion.stopReason === 'workspaceAllowance'
+ ? { type: 'credits-exhausted', turnId }
+ : isDefined(threadId)
+ ? {
+ type: 'message-persisted',
+ messageId: streamed.assistantMessageId,
+ turnId,
+ }
+ : { type: 'run-finished', turnId },
+ shouldKeepCatchup: isDefined(threadId),
+ })
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not publish the end of turn ${turnId} on channel ${channelId}: ${formatErrorWithCause(error)}`,
+ ),
+ );
return { streamed, completion, finish };
}
private async stream<TStarted extends { source: AgentTurnStreamSource }>({
+ workspaceId,
claim,
+ channelId,
turnId,
startTurn,
- }: {
- claim: AgentChatStreamClaim;
- turnId: string;
- startTurn: (
- writer: UIMessageStreamWriter<ExtendedUIMessage>,
- ) => Promise<TStarted>;
+ }: Pick<
+ AgentTurnStreamInput<TStarted, AgentTurnCompletion>,
+ 'workspaceId' | 'claim' | 'turnId' | 'startTurn'
+ > & {
+ channelId: string | undefined;
}): Promise<AgentTurnStreamResult & { started: TStarted }> {
- const { workspaceId, threadId, streamId } = claim;
- const assistantMessageId = uuidv5(streamId, ASSISTANT_MESSAGE_ID_NAMESPACE);
+ // a turn without a claim keeps no reply, so its id only has to be its own
+ const assistantMessageId = uuidv5(
+ claim?.streamId ?? turnId,
+ ASSISTANT_MESSAGE_ID_NAMESPACE,
+ );
const usage: AgentTurnStreamUsage = {
inputTokens: 0,
outputTokens: 0,
@@ -361,64 +460,69 @@ export class AgentTurnStreamService {
},
});
- const [publishStream, checkpointStream] = uiStream.tee();
-
- void (async () => {
- try {
- for await (const message of readUIMessageStream<ExtendedUIMessage>({
- stream: checkpointStream,
- terminateOnError: false,
- })) {
- const now = Date.now();
-
- if (
- isFinalizing ||
- message.parts.length === 0 ||
- now - lastCheckpointAt < AGENT_CHAT_CHECKPOINT_INTERVAL_MS
- ) {
- continue;
- }
-
- lastCheckpointAt = now;
- const parts = message.parts;
-
- checkpoints = checkpoints
- .then(async () => {
- if (isFinalizing) {
- return;
- }
-
- await this.conversationWriterService.upsertAssistantMessage({
- workspaceId,
- id: assistantMessageId,
- threadId,
- turnId,
- parts,
+ const [publishStream, checkpointStream] = isDefined(claim)
+ ? uiStream.tee()
+ : [uiStream, null];
+
+ if (isDefined(claim) && isDefined(checkpointStream)) {
+ void (async () => {
+ try {
+ for await (const message of readUIMessageStream<ExtendedUIMessage>({
+ stream: checkpointStream,
+ terminateOnError: false,
+ })) {
+ const now = Date.now();
+
+ if (
+ isFinalizing ||
+ message.parts.length === 0 ||
+ now - lastCheckpointAt < AGENT_CHAT_CHECKPOINT_INTERVAL_MS
+ ) {
+ continue;
+ }
+
+ lastCheckpointAt = now;
+ const parts = message.parts;
+
+ checkpoints = checkpoints
+ .then(async () => {
+ if (isFinalizing) {
+ return;
+ }
+
+ await this.conversationWriterService.upsertAssistantMessage({
+ workspaceId,
+ id: assistantMessageId,
+ threadId: claim.threadId,
+ turnId,
+ parts,
+ });
+ })
+ .catch((error) => {
+ this.logger.warn(
+ `Failed to checkpoint assistant message for stream ${claim.streamId}: ${formatErrorWithCause(error)}`,
+ );
});
- })
- .catch((error) => {
- this.logger.warn(
- `Failed to checkpoint assistant message for stream ${streamId}: ${formatErrorWithCause(error)}`,
- );
- });
+ }
+ } catch {
+ // best-effort; the reply is saved whole once the turn ends
}
- } catch {
- // best-effort; the reply is saved whole once the turn ends
- }
- })();
+ })();
+ }
for await (const chunk of publishStream) {
- if ((chunk as { type?: string }).type === 'error') {
+ if (!isDefined(channelId) || chunk.type === 'error') {
continue;
}
await this.eventPublisherService.publish({
- threadId,
+ threadId: channelId,
workspaceId,
event: {
type: 'stream-chunk',
chunk: chunk as Record<string, unknown>,
},
+ shouldKeepCatchup: isDefined(claim),
});
}
@@ -434,8 +538,9 @@ export class AgentTurnStreamService {
// Saves the reply and ends the turn, unless another stream took the thread over meanwhile. A turn that
// waits on a person or an event is recorded as waiting rather than done. A turn whose stream failed
- // only records its usage: its failure is recorded with the stream's claim
+ // only records its usage: its failure is recorded with the stream's claim, or by streamTurn without one
private async finishTurn({
+ workspaceId,
claim,
turnId,
result,
@@ -443,9 +548,13 @@ export class AgentTurnStreamService {
stopReason,
isWaiting = false,
isBackgroundRun = false,
- }: {
- claim: AgentChatStreamClaim;
- turnId: string;
+ }: Pick<
+ AgentTurnStreamInput<
+ { source: AgentTurnStreamSource },
+ AgentTurnCompletion
+ >,
+ 'workspaceId' | 'claim' | 'turnId'
+ > & {
result: AgentTurnStreamResult;
modelId: string;
stopReason: StepDebitResult['stopReason'];
@@ -454,7 +563,7 @@ export class AgentTurnStreamService {
// stands in for a written reply
isBackgroundRun?: boolean;
}): Promise<AgentTurnFinish | null> {
- const { workspaceId, threadId, streamId } = claim;
+ const threadId = claim?.threadId ?? null;
const { replyParts, assistantMessageId } = result;
// a turn that only waits on the member still needs a preview in chat lists
const replyText =
@@ -475,7 +584,7 @@ export class AgentTurnStreamService {
isTextReplyRequired: !isBackgroundRun,
});
- if (!isBackgroundRun) {
+ if (!isBackgroundRun && isDefined(claim)) {
this.logTurnWithoutText({
claim,
result,
@@ -487,13 +596,14 @@ export class AgentTurnStreamService {
});
}
+ const turnStatus = mapAgentChatTurnOutcomeToTurnStatus(outcome);
const finishTurn = () =>
this.turnRecorderService.finish({
workspaceId,
turnId,
- ...mapAgentChatTurnOutcomeToTurnStatus(outcome),
+ ...turnStatus,
modelId,
- streamClaim: { threadId, streamId },
+ streamClaim: claim ?? undefined,
});
await this.turnRecorderService.recordUsage({
@@ -507,14 +617,14 @@ export class AgentTurnStreamService {
return null;
}
- if (replyParts.length === 0) {
+ if (replyParts.length === 0 || !isDefined(claim)) {
await finishTurn();
return { outcome, isAwaitingAnswer, threadBefore: null };
}
const threadBefore = await this.threadRepository.findOne(workspaceId, {
- where: { id: threadId },
+ where: { id: claim.threadId },
});
if (!isDefined(threadBefore) || isDefined(threadBefore.deletedAt)) {
@@ -528,7 +638,7 @@ export class AgentTurnStreamService {
await this.conversationWriterService.upsertAssistantMessage({
workspaceId,
id: assistantMessageId,
- threadId,
+ threadId: claim.threadId,
turnId,
parts: replyParts,
});
@@ -536,8 +646,8 @@ export class AgentTurnStreamService {
const totalsUpdate = await updateAgentChatThreadUsage({
repository: this.threadRepository,
workspaceId,
- threadId,
- streamId,
+ threadId: claim.threadId,
+ streamId: claim.streamId,
lastMessageText: replyText,
shouldRecordActivity: !isSilent && (!isBackgroundRun || isAwaitingAnswer),
usage: {
@@ -552,10 +662,14 @@ export class AgentTurnStreamService {
// best-effort so it never turns the saved reply into an error
if (!isSilent && !isBackgroundRun) {
await this.threadService
- .recordThreadActivity({ workspaceId, threadId, text: replyText })
+ .recordThreadActivity({
+ workspaceId,
+ threadId: claim.threadId,
+ text: replyText,
+ })
.catch((error: unknown) =>
this.logger.warn(
- `Could not record reply activity on thread ${threadId}: ${formatErrorWithCause(error)}`,
+ `Could not record reply activity on thread ${claim.threadId}: ${formatErrorWithCause(error)}`,
),
);
}
@@ -648,9 +762,16 @@ export class AgentTurnStreamService {
modelConfig: AiModelConfig;
usage: AgentTurnStreamUsage;
}) {
- if (part.type === 'finish-step') {
+ // a step that failed before the model answered still ends with a finish-step, one without token counts;
+ // one whose model answered with an error finish reason reports real usage and is billed
+ if (
+ part.type === 'finish-step' &&
+ (isDefined(part.usage?.inputTokens) ||
+ isDefined(part.usage?.outputTokens))
+ ) {
Object.assign(usage, addStepToAgentTurnUsage(modelConfig, usage, part));
- usage.conversationSize = part.usage?.inputTokens ?? 0;
+ usage.conversationSize =
+ part.usage?.inputTokens ?? usage.conversationSize;
}
if (part.type === 'start') {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-channel.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-channel.type.ts
new file mode 100644
index 00000000000..5bf890d7387
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-channel.type.ts
@@ -0,0 +1,5 @@
+// a run's channel carries only that run's turn, so it has no thread to check, filter or reap
+export type AgentChatChannel = {
+ kind: 'thread' | 'run';
+ channelId: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-agent-chat-live-event-filter.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-agent-chat-live-event-filter.util.spec.ts
new file mode 100644
index 00000000000..1dff741036f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-agent-chat-live-event-filter.util.spec.ts
@@ -0,0 +1,61 @@
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+
+import { createAgentChatLiveEventFilter } from 'src/engine/metadata-modules/ai/ai-chat/utils/create-agent-chat-live-event-filter.util';
+
+const EMPTY_CHUNK = { type: 'message-metadata', messageMetadata: {} };
+
+const toChunkEvent = (
+ chunk: Record<string, unknown>,
+): AgentChatSubscriptionEvent => ({ type: 'stream-chunk', chunk, seq: 1 });
+
+describe('createAgentChatLiveEventFilter', () => {
+ it('shows only the text of a reply streamed for another member', async () => {
+ const filterVisibleEvent = createAgentChatLiveEventFilter({
+ isStreamingTurnHidden: async () => true,
+ });
+ const textChunk = toChunkEvent({
+ type: 'text-delta',
+ id: 'text-1',
+ delta: 'Acme renews in May',
+ });
+
+ expect(
+ await filterVisibleEvent(
+ toChunkEvent({
+ type: 'tool-output-available',
+ toolCallId: 'call-1',
+ output: { email: '[email protected]' },
+ }),
+ ),
+ ).toEqual(toChunkEvent(EMPTY_CHUNK));
+ expect(await filterVisibleEvent(textChunk)).toEqual(textChunk);
+ expect(await filterVisibleEvent({ type: 'queue-updated' })).toEqual({
+ type: 'queue-updated',
+ });
+ });
+
+ it('checks again who opened the turn when a new reply starts', async () => {
+ const isStreamingTurnHidden = jest
+ .fn<Promise<boolean>, []>()
+ .mockResolvedValue(false);
+ const filterVisibleEvent = createAgentChatLiveEventFilter({
+ isStreamingTurnHidden,
+ });
+ const reasoningChunk = toChunkEvent({
+ type: 'reasoning-delta',
+ id: 'reasoning-1',
+ delta: 'Their notes',
+ });
+
+ expect(isStreamingTurnHidden).not.toHaveBeenCalled();
+ expect(await filterVisibleEvent(reasoningChunk)).toEqual(reasoningChunk);
+
+ isStreamingTurnHidden.mockResolvedValue(true);
+ await filterVisibleEvent(toChunkEvent({ type: 'start' }));
+
+ expect(await filterVisibleEvent(reasoningChunk)).toEqual(
+ toChunkEvent(EMPTY_CHUNK),
+ );
+ expect(isStreamingTurnHidden).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-agent-chat-live-event-filter.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-agent-chat-live-event-filter.util.ts
new file mode 100644
index 00000000000..6681882f096
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-agent-chat-live-event-filter.util.ts
@@ -0,0 +1,32 @@
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { maskStreamChunkOfTurnActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util';
+
+export const createAgentChatLiveEventFilter = ({
+ isStreamingTurnHidden,
+}: {
+ isStreamingTurnHidden: () => Promise<boolean>;
+}): ((
+ event: AgentChatSubscriptionEvent,
+) => Promise<AgentChatSubscriptionEvent>) => {
+ let isHidden: Promise<boolean> | undefined;
+
+ return async (event) => {
+ if (event.type !== 'stream-chunk') {
+ return event;
+ }
+
+ // read once a chunk arrives, so the channel is already subscribed and a turn starting before it is seen;
+ // every reply opens with a start chunk, so the turn it streams is known by then
+ if (!isDefined(isHidden) || event.chunk.type === 'start') {
+ isHidden = isStreamingTurnHidden();
+ }
+
+ if (!(await isHidden)) {
+ return event;
+ }
+
+ return { ...event, chunk: maskStreamChunkOfTurnActedByOthers(event.chunk) };
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-message-part-types-shown-to-others.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-message-part-types-shown-to-others.constant.ts
new file mode 100644
index 00000000000..00720ff50d5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-message-part-types-shown-to-others.constant.ts
@@ -0,0 +1 @@
+export const AGENT_MESSAGE_PART_TYPES_SHOWN_TO_OTHERS = new Set(['text']);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant.ts
new file mode 100644
index 00000000000..d92e5fefaf5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant.ts
@@ -0,0 +1,7 @@
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { type StreamErrorPayload } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
+
+export const AGENT_TURN_INTERRUPTED_ERROR: StreamErrorPayload = {
+ code: AiExceptionCode.STREAM_INTERRUPTED,
+ message: 'The response was interrupted before it could finish.',
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts
index 93239f97471..ca77bb4ac76 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-conversation-reader.service.spec.ts
@@ -46,13 +46,23 @@ const buildTurn = ({
},
];
-const buildService = (messages: unknown[], failedTurnIds: string[] = []) => {
- const messageRepository = { find: jest.fn().mockResolvedValue(messages) };
- const turnRepository = {
- find: jest
- .fn()
- .mockResolvedValue(failedTurnIds.map((turnId) => ({ id: turnId }))),
+type TurnRow = {
+ id: string;
+ status?: string;
+ createdBy: {
+ workspaceMemberId?: string;
+ context?: { applicationId?: string };
};
+};
+
+const openedBy = (id: string, workspaceMemberId?: string): TurnRow => ({
+ id,
+ createdBy: { workspaceMemberId },
+});
+
+const buildService = (messages: unknown[], turns: TurnRow[] = []) => {
+ const messageRepository = { find: jest.fn().mockResolvedValue(messages) };
+ const turnRepository = { find: jest.fn().mockResolvedValue(turns) };
const fileUrlService = {
signFileByIdUrl: jest
.fn()
@@ -114,7 +124,7 @@ describe('AgentConversationReaderService', () => {
parts: [{ type: 'text', textContent: 'And the second one?' }],
},
],
- ['turn-2'],
+ [{ ...openedBy('turn-2', MEMBER_A), status: 'failed' }],
);
const messages = await service.loadMessages({
@@ -158,7 +168,7 @@ describe('AgentConversationReaderService', () => {
]);
});
- it('keeps every part when no actor is given', async () => {
+ it('keeps every part when no viewer is given', async () => {
const { service } = buildService([
...buildTurn({
turnId: 'turn-1',
@@ -177,25 +187,28 @@ describe('AgentConversationReaderService', () => {
});
it('reduces turns sent by someone else to their text', async () => {
- const { service } = buildService([
- ...buildTurn({
- turnId: 'turn-1',
- senderWorkspaceMemberId: MEMBER_A,
- question: 'Who is our biggest customer?',
- answer: 'Private Co',
- }),
- ...buildTurn({
- turnId: 'turn-2',
- senderWorkspaceMemberId: MEMBER_B,
- question: 'And the second one?',
- answer: 'Other Co',
- }),
- ]);
+ const { service } = buildService(
+ [
+ ...buildTurn({
+ turnId: 'turn-1',
+ senderWorkspaceMemberId: MEMBER_A,
+ question: 'Who is our biggest customer?',
+ answer: 'Private Co',
+ }),
+ ...buildTurn({
+ turnId: 'turn-2',
+ senderWorkspaceMemberId: MEMBER_B,
+ question: 'And the second one?',
+ answer: 'Other Co',
+ }),
+ ],
+ [openedBy('turn-1', MEMBER_A), openedBy('turn-2', MEMBER_B)],
+ );
const messages = await service.loadMessages({
workspaceId: WORKSPACE_ID,
threadId: THREAD_ID,
- actor: { type: 'user', workspaceMemberId: MEMBER_B },
+ viewer: { workspaceMemberId: MEMBER_B },
});
expect(messages.map(getPartTypes)).toEqual([
@@ -206,26 +219,35 @@ describe('AgentConversationReaderService', () => {
]);
});
- it('treats a member and the application acting alone as different actors', async () => {
- const { service } = buildService([
- ...buildTurn({
- turnId: 'turn-1',
- senderWorkspaceMemberId: MEMBER_A,
- question: 'Who is our biggest customer?',
- answer: 'Private Co',
- }),
- ...buildTurn({
- turnId: 'turn-2',
- senderWorkspaceMemberId: null,
- question: 'Summarize this thread',
- answer: 'Done',
- }),
- ]);
+ it('hides from an application the turns a member opened elsewhere, not its own', async () => {
+ const { service } = buildService(
+ [
+ ...buildTurn({
+ turnId: 'turn-1',
+ senderWorkspaceMemberId: MEMBER_A,
+ question: 'Who is our biggest customer?',
+ answer: 'Private Co',
+ }),
+ ...buildTurn({
+ turnId: 'turn-2',
+ senderWorkspaceMemberId: null,
+ question: 'Summarize this thread',
+ answer: 'Done',
+ }),
+ ],
+ [
+ openedBy('turn-1', MEMBER_A),
+ {
+ id: 'turn-2',
+ createdBy: { context: { applicationId: APPLICATION_ID } },
+ },
+ ],
+ );
const messages = await service.loadMessages({
workspaceId: WORKSPACE_ID,
threadId: THREAD_ID,
- actor: { type: 'application', applicationId: APPLICATION_ID },
+ viewer: { workspaceMemberId: undefined, applicationId: APPLICATION_ID },
});
expect(messages.map(getPartTypes)).toEqual([
@@ -236,15 +258,71 @@ describe('AgentConversationReaderService', () => {
]);
});
- it('loads files with their type and signs them for the actor', async () => {
- const { service, messageRepository, fileUrlService } = buildService([
- buildFileMessage({ turnId: 'turn-1', senderWorkspaceMemberId: MEMBER_A }),
+ it('reads back the turns an application ran as a member', async () => {
+ const [, assistantMessage] = buildTurn({
+ turnId: 'turn-2',
+ senderWorkspaceMemberId: null,
+ question: '',
+ answer: 'Done',
+ });
+ const { service } = buildService(
+ [
+ ...buildTurn({
+ turnId: 'turn-1',
+ senderWorkspaceMemberId: MEMBER_A,
+ question: 'Who is our biggest customer?',
+ answer: 'Private Co',
+ }),
+ assistantMessage,
+ ],
+ [
+ {
+ id: 'turn-1',
+ createdBy: {
+ workspaceMemberId: MEMBER_A,
+ context: { applicationId: APPLICATION_ID },
+ },
+ },
+ openedBy('turn-2', MEMBER_A),
+ ],
+ );
+
+ const appMessages = await service.loadMessages({
+ workspaceId: WORKSPACE_ID,
+ threadId: THREAD_ID,
+ viewer: { workspaceMemberId: undefined, applicationId: APPLICATION_ID },
+ });
+ const memberMessages = await service.loadMessages({
+ workspaceId: WORKSPACE_ID,
+ threadId: THREAD_ID,
+ viewer: { workspaceMemberId: MEMBER_A },
+ });
+
+ expect(appMessages.map(getPartTypes)[1]).toEqual([
+ 'tool-find_companies',
+ 'text',
+ ]);
+ expect(memberMessages.map(getPartTypes)[1]).toEqual([
+ 'tool-find_companies',
+ 'text',
]);
+ });
+
+ it('loads files with their type and signs them for the viewer', async () => {
+ const { service, messageRepository, fileUrlService } = buildService(
+ [
+ buildFileMessage({
+ turnId: 'turn-1',
+ senderWorkspaceMemberId: MEMBER_A,
+ }),
+ ],
+ [openedBy('turn-1', MEMBER_A)],
+ );
const messages = await service.loadMessages({
workspaceId: WORKSPACE_ID,
threadId: THREAD_ID,
- actor: { type: 'user', workspaceMemberId: MEMBER_A },
+ viewer: { workspaceMemberId: MEMBER_A },
});
expect(messageRepository.find).toHaveBeenCalledWith(
@@ -266,14 +344,20 @@ describe('AgentConversationReaderService', () => {
});
it('drops the files of turns sent by someone else without signing them', async () => {
- const { service, fileUrlService } = buildService([
- buildFileMessage({ turnId: 'turn-1', senderWorkspaceMemberId: MEMBER_A }),
- ]);
+ const { service, fileUrlService } = buildService(
+ [
+ buildFileMessage({
+ turnId: 'turn-1',
+ senderWorkspaceMemberId: MEMBER_A,
+ }),
+ ],
+ [openedBy('turn-1', MEMBER_A)],
+ );
const messages = await service.loadMessages({
workspaceId: WORKSPACE_ID,
threadId: THREAD_ID,
- actor: { type: 'user', workspaceMemberId: MEMBER_B },
+ viewer: { workspaceMemberId: MEMBER_B },
});
expect(getPartTypes(messages[0])).toEqual(['text']);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts
index 1522e675deb..2a3ce704437 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service.ts
@@ -19,9 +19,9 @@ import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { type AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
-import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
+import { type AgentConversationViewer } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-viewer.type';
import { filterPartsOfTurnActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util';
-import { findTurnIdsActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util';
+import { isAgentTurnOpenedByOtherMember } from 'src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util';
@Injectable()
export class AgentConversationReaderService {
@@ -73,13 +73,14 @@ export class AgentConversationReaderService {
async loadMessages({
workspaceId,
threadId,
- actor,
+ viewer,
}: {
workspaceId: string;
threadId: string;
- actor?: AgentConversationActor;
+ // the history's rule, so a run reads the conversation as its caller reads it
+ viewer?: AgentConversationViewer;
}): Promise<ExtendedUIMessage[]> {
- const [threadMessages, failedTurns] = await Promise.all([
+ const [threadMessages, turns] = await Promise.all([
this.messageRepository.find(workspaceId, {
where: { threadId },
order: {
@@ -88,24 +89,31 @@ export class AgentConversationReaderService {
},
relations: ['parts', 'parts.file'],
}),
- this.turnRepository.find(workspaceId, {
- where: { threadId, status: AgentTurnStatus.FAILED },
- select: ['id'],
- }),
+ this.turnRepository.find(workspaceId, { where: { threadId } }),
]);
// a failed run is kept on record but leaves the conversation as it was, and a chat message
// queued behind a stream is not sent yet
- const failedTurnIds = new Set(failedTurns.map(({ id }) => id));
+ const failedTurnIds = new Set(
+ turns
+ .filter(({ status }) => status === AgentTurnStatus.FAILED)
+ .map(({ id }) => id),
+ );
const messages = threadMessages.filter(
({ turnId, status }) =>
status !== AgentMessageStatus.QUEUED &&
(!isDefined(turnId) || !failedTurnIds.has(turnId)),
);
- const turnIdsActedByOthers = isDefined(actor)
- ? findTurnIdsActedByOthers({ messages, actor })
- : new Set<string>();
+ const turnIdsActedByOthers = new Set(
+ isDefined(viewer)
+ ? turns
+ .filter(({ createdBy }) =>
+ isAgentTurnOpenedByOtherMember({ createdBy, ...viewer }),
+ )
+ .map(({ id }) => id)
+ : [],
+ );
return Promise.all(
messages.map(async (message) => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
index 5778ac4b8b7..d21af229802 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
@@ -84,7 +84,7 @@ export class AgentConversationWriterService {
scope,
}: {
workspaceId: string;
- threadId: string;
+ threadId: string | null;
agentId: string | null;
status: AgentTurnStatus;
createdBy?: ActorMetadata;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service.ts
index cd2bba2101f..2dbc3cd25f0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-turn-recorder.service.ts
@@ -1,5 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
+import { type AiRunUsage } from 'twenty-shared/application';
import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
@@ -10,6 +11,10 @@ import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { type AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
import { type AgentTurnUsage } from 'src/engine/metadata-modules/ai/ai-billing/types/agent-turn-usage.type';
import { buildEndWaitingAgentTurnQuery } from 'src/engine/metadata-modules/ai/ai-history/utils/build-end-waiting-agent-turn-query.util';
import { buildReleaseStreamClaimQuery } from 'src/engine/metadata-modules/ai/ai-history/utils/build-release-stream-claim-query.util';
@@ -150,7 +155,8 @@ export class AgentTurnRecorderService {
}: {
workspaceId: string;
turnId: string;
- threadId: string;
+ // null for a turn without a conversation, which has no thread totals to add to
+ threadId: string | null;
usage: AgentTurnUsage;
}): Promise<void> {
await this.turnRepository
@@ -247,6 +253,44 @@ export class AgentTurnRecorderService {
);
}
+ async findUsageOrThrow({
+ workspaceId,
+ turnId,
+ }: {
+ workspaceId: string;
+ turnId: string;
+ }): Promise<AiRunUsage> {
+ const turn = await this.turnRepository.findOne(workspaceId, {
+ where: { id: turnId },
+ select: ['inputTokens', 'outputTokens'],
+ });
+
+ if (!isDefined(turn)) {
+ throw new AiException(
+ `Turn ${turnId} not found`,
+ AiExceptionCode.AGENT_EXECUTION_FAILED,
+ );
+ }
+
+ return {
+ inputTokens: turn.inputTokens ?? 0,
+ outputTokens: turn.outputTokens ?? 0,
+ };
+ }
+
+ async findTurn({
+ workspaceId,
+ turnId,
+ }: {
+ workspaceId: string;
+ turnId: string;
+ }): Promise<Pick<AgentTurnWorkspaceEntity, 'id' | 'status'> | null> {
+ return this.turnRepository.findOne(workspaceId, {
+ where: { id: turnId },
+ select: ['id', 'status'],
+ });
+ }
+
async findLatestTurn({
workspaceId,
threadId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity.ts
index c7d0b79ce2f..de6229cbded 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity.ts
@@ -8,10 +8,10 @@ import { type StreamErrorPayload } from 'src/engine/metadata-modules/ai/ai-histo
import { BaseWorkspaceEntity } from 'src/engine/twenty-orm/base.workspace-entity';
export class AgentTurnWorkspaceEntity extends BaseWorkspaceEntity {
- thread: EntityRelation<AgentChatThreadWorkspaceEntity>;
+ thread: EntityRelation<AgentChatThreadWorkspaceEntity> | null;
messages: EntityRelation<AgentMessageWorkspaceEntity[]>;
- threadId: string;
+ threadId: string | null;
agentId: string | null;
status: AgentTurnStatus;
error: StreamErrorPayload | null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.ts
deleted file mode 100644
index 657ebae9f1e..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type AgentConversationActor =
- | { type: 'user'; workspaceMemberId: string }
- | { type: 'application'; applicationId: string };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-viewer.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-viewer.type.ts
new file mode 100644
index 00000000000..374d25767d5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-conversation-viewer.type.ts
@@ -0,0 +1,5 @@
+// who a conversation is read for: turns other members opened ran under their permissions
+export type AgentConversationViewer = {
+ workspaceMemberId: string | undefined;
+ applicationId?: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.ts
deleted file mode 100644
index a2311804ed1..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/find-turn-ids-acted-by-others.util.spec.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
-import { findTurnIdsActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util';
-
-const APPLICATION_ID = 'application-id';
-
-const userMessage = (
- turnId: string | null,
- senderWorkspaceMemberId: string | null,
-) => ({
- turnId,
- role: AgentMessageRole.USER,
- senderWorkspaceMemberId,
- senderApplicationId: APPLICATION_ID,
-});
-
-const assistantMessage = (turnId: string | null) => ({
- turnId,
- role: AgentMessageRole.ASSISTANT,
- senderWorkspaceMemberId: null,
- senderApplicationId: null,
-});
-
-describe('findTurnIdsActedByOthers', () => {
- it('should keep the turns a member sent and flag the others', () => {
- expect(
- findTurnIdsActedByOthers({
- messages: [
- userMessage('turn-1', 'member-a'),
- assistantMessage('turn-1'),
- userMessage('turn-2', 'member-b'),
- assistantMessage('turn-2'),
- userMessage('turn-3', null),
- assistantMessage('turn-3'),
- ],
- actor: { type: 'user', workspaceMemberId: 'member-a' },
- }),
- ).toEqual(new Set(['turn-2', 'turn-3']));
- });
-
- it('should keep the turns the application sent on its own', () => {
- expect(
- findTurnIdsActedByOthers({
- messages: [
- userMessage('turn-1', 'member-a'),
- userMessage('turn-2', null),
- ],
- actor: { type: 'application', applicationId: APPLICATION_ID },
- }),
- ).toEqual(new Set(['turn-1']));
- });
-
- it('should flag turns with no request or a request from someone else', () => {
- expect(
- findTurnIdsActedByOthers({
- messages: [
- assistantMessage('turn-1'),
- userMessage('turn-2', 'member-a'),
- userMessage('turn-2', 'member-b'),
- ],
- actor: { type: 'user', workspaceMemberId: 'member-a' },
- }),
- ).toEqual(new Set(['turn-1', 'turn-2']));
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/is-agent-turn-opened-by-other-member.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/is-agent-turn-opened-by-other-member.util.spec.ts
new file mode 100644
index 00000000000..e5eb25a64b0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/is-agent-turn-opened-by-other-member.util.spec.ts
@@ -0,0 +1,51 @@
+import { FieldActorSource } from 'twenty-shared/types';
+
+import { isAgentTurnOpenedByOtherMember } from 'src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util';
+
+const RUN_AS_JONY_BY_APPLICATION = {
+ source: FieldActorSource.AGENT,
+ workspaceMemberId: 'jony-member-id',
+ name: 'Jony Ive',
+ context: { applicationId: 'application-id' },
+};
+
+describe('isAgentTurnOpenedByOtherMember', () => {
+ it('lets the application read on its own a turn it ran as a member', () => {
+ expect(
+ isAgentTurnOpenedByOtherMember({
+ createdBy: RUN_AS_JONY_BY_APPLICATION,
+ workspaceMemberId: undefined,
+ applicationId: 'application-id',
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps that turn from another application', () => {
+ expect(
+ isAgentTurnOpenedByOtherMember({
+ createdBy: RUN_AS_JONY_BY_APPLICATION,
+ workspaceMemberId: undefined,
+ applicationId: 'other-application-id',
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps that turn from another member, even through the same application', () => {
+ expect(
+ isAgentTurnOpenedByOtherMember({
+ createdBy: RUN_AS_JONY_BY_APPLICATION,
+ workspaceMemberId: 'jane-member-id',
+ applicationId: 'application-id',
+ }),
+ ).toBe(true);
+ });
+
+ it('lets the member the turn ran as read it', () => {
+ expect(
+ isAgentTurnOpenedByOtherMember({
+ createdBy: RUN_AS_JONY_BY_APPLICATION,
+ workspaceMemberId: 'jony-member-id',
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/mask-stream-chunk-of-turn-acted-by-others.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/mask-stream-chunk-of-turn-acted-by-others.util.spec.ts
new file mode 100644
index 00000000000..228b11d8cbd
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/__tests__/mask-stream-chunk-of-turn-acted-by-others.util.spec.ts
@@ -0,0 +1,73 @@
+import { maskStreamChunkOfTurnActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util';
+
+const EMPTY_CHUNK = { type: 'message-metadata', messageMetadata: {} };
+
+describe('maskStreamChunkOfTurnActedByOthers', () => {
+ it('keeps the text of the reply', () => {
+ const chunks = [
+ { type: 'start', messageId: 'message-id' },
+ { type: 'text-start', id: 'text-1' },
+ { type: 'text-delta', id: 'text-1', delta: 'Acme renews in May' },
+ { type: 'text-end', id: 'text-1' },
+ { type: 'finish' },
+ ];
+
+ expect(chunks.map(maskStreamChunkOfTurnActedByOthers)).toEqual(chunks);
+ });
+
+ it('empties every other chunk', () => {
+ expect(
+ [
+ { type: 'start-step' },
+ { type: 'reasoning-delta', id: 'reasoning-1', delta: 'Their notes' },
+ {
+ type: 'tool-input-available',
+ toolCallId: 'call-1',
+ toolName: 'find_people',
+ input: { email: '[email protected]' },
+ },
+ { type: 'tool-output-available', toolCallId: 'call-1', output: [] },
+ { type: 'source-url', sourceId: 'source-1', url: 'https://acme.com' },
+ { type: 'data-record', data: { id: 'record-id' } },
+ ].map(maskStreamChunkOfTurnActedByOthers),
+ ).toEqual([
+ EMPTY_CHUNK,
+ EMPTY_CHUNK,
+ EMPTY_CHUNK,
+ EMPTY_CHUNK,
+ EMPTY_CHUNK,
+ EMPTY_CHUNK,
+ ]);
+ });
+
+ it('drops the usage the reply carries as metadata', () => {
+ expect(
+ [
+ {
+ type: 'start',
+ messageId: 'message-id',
+ messageMetadata: { startedAt: '2026-11-01T00:00:00.000Z' },
+ },
+ {
+ type: 'message-metadata',
+ messageMetadata: { usage: { inputCredits: 12 } },
+ },
+ {
+ type: 'finish',
+ finishReason: 'stop',
+ messageMetadata: {
+ usage: {
+ inputTokens: 120,
+ inputCredits: 12,
+ conversationSize: 120,
+ },
+ },
+ },
+ ].map(maskStreamChunkOfTurnActedByOthers),
+ ).toEqual([
+ { type: 'start', messageId: 'message-id' },
+ EMPTY_CHUNK,
+ { type: 'finish', finishReason: 'stop' },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util.ts
index 5aedc408009..593c20f2094 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util.ts
@@ -1,3 +1,8 @@
+import { AGENT_MESSAGE_PART_TYPES_SHOWN_TO_OTHERS } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-message-part-types-shown-to-others.constant';
+
export const filterPartsOfTurnActedByOthers = <TPart extends { type: string }>(
parts: TPart[],
-): TPart[] => parts.filter(({ type }) => type === 'text');
+): TPart[] =>
+ parts.filter(({ type }) =>
+ AGENT_MESSAGE_PART_TYPES_SHOWN_TO_OTHERS.has(type),
+ );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.ts
deleted file mode 100644
index 213682879f9..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/find-turn-ids-acted-by-others.util.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
-import { type AgentConversationActor } from 'src/engine/metadata-modules/ai/ai-history/types/agent-conversation-actor.type';
-import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
-
-type AgentMessageSender = Pick<
- AgentMessageWorkspaceEntity,
- 'turnId' | 'role' | 'senderWorkspaceMemberId' | 'senderApplicationId'
->;
-
-const isSentByActor = (
- message: AgentMessageSender,
- actor: AgentConversationActor,
-): boolean =>
- actor.type === 'user'
- ? message.senderWorkspaceMemberId === actor.workspaceMemberId
- : message.senderApplicationId === actor.applicationId &&
- !isDefined(message.senderWorkspaceMemberId);
-
-export const findTurnIdsActedByOthers = ({
- messages,
- actor,
-}: {
- messages: AgentMessageSender[];
- actor: AgentConversationActor;
-}): Set<string> => {
- const turnIds = new Set<string>();
- const turnIdsActedByActor = new Set<string>();
- const turnIdsActedByOthers = new Set<string>();
-
- for (const message of messages) {
- if (!isDefined(message.turnId)) {
- continue;
- }
-
- turnIds.add(message.turnId);
-
- if (message.role !== AgentMessageRole.USER) {
- continue;
- }
-
- if (isSentByActor(message, actor)) {
- turnIdsActedByActor.add(message.turnId);
- } else {
- turnIdsActedByOthers.add(message.turnId);
- }
- }
-
- return new Set(
- [...turnIds].filter(
- (turnId) =>
- turnIdsActedByOthers.has(turnId) || !turnIdsActedByActor.has(turnId),
- ),
- );
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util.ts
new file mode 100644
index 00000000000..ad7e22f3182
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/is-agent-turn-opened-by-other-member.util.ts
@@ -0,0 +1,27 @@
+import { type ActorMetadata } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+// An application reading on its own sees the turns it ran as a member: they ran within its role
+export const isAgentTurnOpenedByOtherMember = ({
+ createdBy,
+ workspaceMemberId,
+ applicationId,
+}: {
+ createdBy: Pick<ActorMetadata, 'workspaceMemberId' | 'context'>;
+ workspaceMemberId: string | undefined;
+ applicationId?: string;
+}): boolean => {
+ if (!isDefined(createdBy.workspaceMemberId)) {
+ return false;
+ }
+
+ const isOpenedByReadingApplication =
+ !isDefined(workspaceMemberId) &&
+ isDefined(applicationId) &&
+ createdBy.context?.applicationId === applicationId;
+
+ return (
+ !isOpenedByReadingApplication &&
+ createdBy.workspaceMemberId !== workspaceMemberId
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util.ts
index d63bd4f8f89..a40a2386124 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util.ts
@@ -1,86 +1,20 @@
-import { isDefined } from 'twenty-shared/utils';
import {
- type ExtendedFileUIPart,
type ExtendedUIMessagePart,
+ mapAgentMessagePartToUIMessagePart,
} from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-// keep in sync with packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
-
+// the model is handed files by id, so a stored part needs no url here
export const mapDBPartToUIMessagePart = (
part: AgentMessagePartWorkspaceEntity,
-): ExtendedUIMessagePart | null => {
- switch (part.type) {
- case 'text':
- return {
- type: 'text',
- text: part.textContent ?? '',
- };
- case 'reasoning':
- return {
- type: 'reasoning',
- text: part.reasoningContent ?? '',
- state: (part.state as 'streaming' | 'done') ?? 'done',
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'file':
- return {
- type: 'file',
- mediaType: part.file?.mimeType ?? 'application/octet-stream',
- filename: part.fileFilename ?? '',
- url: '',
- fileId: part.fileId ?? '',
- } as ExtendedFileUIPart;
- case 'source-url':
- return {
- type: 'source-url',
- sourceId: part.sourceUrlSourceId ?? '',
- url: part.sourceUrlUrl ?? '',
- title: part.sourceUrlTitle ?? '',
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'source-document':
- return {
- type: 'source-document',
- sourceId: part.sourceDocumentSourceId ?? '',
- mediaType: part.sourceDocumentMediaType ?? '',
- title: part.sourceDocumentTitle ?? '',
- filename: part.sourceDocumentFilename ?? '',
- providerMetadata: part.providerMetadata ?? undefined,
- };
- case 'step-start':
- return {
- type: 'step-start',
- };
- default: {
- const isStaticToolPart =
- part.type.startsWith('tool-') && part.toolCallId !== null;
- const isDynamicToolPart =
- part.type === 'dynamic-tool' && part.toolCallId !== null;
-
- if (isStaticToolPart || isDynamicToolPart) {
- return {
- type: part.type,
- ...(isDynamicToolPart && { toolName: part.toolName ?? '' }),
- toolCallId: part.toolCallId,
- input: part.toolInput ?? {},
- output: part.toolOutput,
- errorText: part.errorMessage ?? '',
- state: part.state,
- ...(part.providerExecuted != null && {
- providerExecuted: part.providerExecuted,
- }),
- ...(part.providerMetadata != null && {
- callProviderMetadata: part.providerMetadata,
- }),
- } as ExtendedUIMessagePart;
- }
-
- return null;
- }
- }
-};
+): ExtendedUIMessagePart | null =>
+ mapAgentMessagePartToUIMessagePart({
+ ...part,
+ fileMediaType: part.file?.mimeType,
+ fileUrl: null,
+ });
export const mapDBPartsToUIMessageParts = (
parts: AgentMessagePartWorkspaceEntity[],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util.ts
new file mode 100644
index 00000000000..6f7a55483a1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/mask-stream-chunk-of-turn-acted-by-others.util.ts
@@ -0,0 +1,27 @@
+import { isString } from '@sniptt/guards';
+
+import { AGENT_MESSAGE_PART_TYPES_SHOWN_TO_OTHERS } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-message-part-types-shown-to-others.constant';
+
+const MESSAGE_FRAME_CHUNK_TYPES = new Set(['start', 'finish', 'abort']);
+
+// a part streams as `<part type>`, or as its `-start`, `-delta` and `-end` chunks
+const toStreamedPartType = (chunkType: string) =>
+ chunkType.replace(/-(start|delta|end)$/, '');
+
+const isChunkTypeShownToOthers = (chunkType: string) =>
+ MESSAGE_FRAME_CHUNK_TYPES.has(chunkType) ||
+ AGENT_MESSAGE_PART_TYPES_SHOWN_TO_OTHERS.has(toStreamedPartType(chunkType));
+
+// replaced rather than dropped, so seq stays gapless for replay
+export const maskStreamChunkOfTurnActedByOthers = (
+ chunk: Record<string, unknown>,
+): Record<string, unknown> => {
+ if (!isString(chunk.type) || !isChunkTypeShownToOthers(chunk.type)) {
+ return { type: 'message-metadata', messageMetadata: {} };
+ }
+
+ // the turn's usage and credits ride on its metadata, which history keeps from other members too
+ return Object.fromEntries(
+ Object.entries(chunk).filter(([key]) => key !== 'messageMetadata'),
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts b/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
index b8e3b0004bf..7e42cbbdf8d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
@@ -3,36 +3,24 @@ import { Injectable } from '@nestjs/common';
import { IsNull } from 'typeorm';
import {
- PermissionFlagType,
+ type PermissionFlagType,
SystemPermissionFlag,
} from 'twenty-shared/constants';
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import {
FieldMetadataType,
- type ObjectsPermissions,
type ObjectsPermissionsByRoleId,
- type RestrictedFieldsPermissions,
} from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
import { buildResolveMorphRelationPermissionFieldIds } from 'src/engine/metadata-modules/role/utils/build-resolve-morph-relation-permission-field-ids.util';
-import { mergeRestrictedFieldPermissions } from 'src/engine/metadata-modules/role/utils/merge-restricted-field-permissions.util';
-import { hasRoleWideAccessToPermissionFlag } from 'src/engine/permissions/role/utils/has-role-wide-access-to-permission-flag.util';
-import { type RolePermissionFlagEntity } from 'src/engine/metadata-modules/role-permission-flag/role-permission-flag.entity';
+import { computeObjectsPermissionsForRoleDefinition } from 'src/engine/permissions/role/utils/compute-objects-permissions-for-role-definition.util';
+import { buildIsPermissionFlagGranted } from 'src/engine/permissions/role/utils/build-is-permission-flag-granted.util';
+import { type PermissionFlagEntity } from 'src/engine/metadata-modules/permission-flag/permission-flag.entity';
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
import { type WorkspaceCacheProviderContext } from 'src/engine/workspace-cache/types/workspace-cache-provider-context.type';
import { type WorkspaceCacheRowsRequirement } from 'src/engine/workspace-cache/types/workspace-cache-rows-requirement.type';
-const WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS = [
- STANDARD_OBJECTS.workflow.universalIdentifier,
- STANDARD_OBJECTS.workflowRun.universalIdentifier,
- STANDARD_OBJECTS.workflowVersion.universalIdentifier,
-] as const;
-const WORKSPACE_MEMBER_OBJECT_UNIVERSAL_IDENTIFIER =
- STANDARD_OBJECTS.workspaceMember.universalIdentifier;
-
const ROLES_PERMISSIONS_ROWS_REQUIREMENT = {
role: true,
objectPermission: { columns: true, groupBy: ['roleId'] },
@@ -96,182 +84,54 @@ export class WorkspaceRolesPermissionsCacheService extends WorkspaceCacheProvide
const permissionsByRoleId: ObjectsPermissionsByRoleId = {};
for (const role of roles) {
- const roleObjectPermissions =
- objectPermissions.byRoleId.get(role.id) ?? [];
- const assignedPermissionFlagUniversalIdentifiers = new Set(
- (rolePermissionFlags.byRoleId.get(role.id) ?? []).map(
- (rolePermissionFlagRow) =>
- this.getRolePermissionFlagUniversalIdentifier({
- ...rolePermissionFlagRow,
- permissionFlag: permissionFlagById.get(
- rolePermissionFlagRow.permissionFlagId,
- ),
- } as RolePermissionFlagEntity),
+ const isPermissionFlagGranted = buildIsPermissionFlagGranted({
+ role,
+ permissionFlagUniversalIdentifiers: (
+ rolePermissionFlags.byRoleId.get(role.id) ?? []
+ ).map((rolePermissionFlagRow) =>
+ this.getRolePermissionFlagUniversalIdentifier({
+ flag: rolePermissionFlagRow.flag,
+ permissionFlag: permissionFlagById.get(
+ rolePermissionFlagRow.permissionFlagId,
+ ),
+ }),
),
+ });
+
+ permissionsByRoleId[role.id] = computeObjectsPermissionsForRoleDefinition(
+ {
+ roleDefinition: {
+ canReadAllObjectRecords: role.canReadAllObjectRecords,
+ canUpdateAllObjectRecords: role.canUpdateAllObjectRecords,
+ canSoftDeleteAllObjectRecords: role.canSoftDeleteAllObjectRecords,
+ canDestroyAllObjectRecords: role.canDestroyAllObjectRecords,
+ isPermissionFlagGranted,
+ objectPermissions: objectPermissions.byRoleId.get(role.id) ?? [],
+ fieldPermissions: fieldPermissions.byRoleId.get(role.id) ?? [],
+ rowLevelPermissionPredicates:
+ rowLevelPermissionPredicates.byRoleId.get(role.id) ?? [],
+ rowLevelPermissionPredicateGroups:
+ rowLevelPermissionPredicateGroups.byRoleId.get(role.id) ?? [],
+ },
+ objectMetadataCollection: workspaceObjectMetadataCollection,
+ resolveMorphRelationPermissionFieldIds,
+ },
);
- const isRolePermissionFlagGranted = (
- permissionFlag: PermissionFlagType,
- ): boolean =>
- hasRoleWideAccessToPermissionFlag({ role, permissionFlag }) ||
- assignedPermissionFlagUniversalIdentifiers.has(
- SystemPermissionFlag[permissionFlag],
- );
- const roleFieldPermissions = fieldPermissions.byRoleId.get(role.id) ?? [];
-
- const roleRowLevelPermissionPredicates =
- rowLevelPermissionPredicates.byRoleId.get(role.id) ?? [];
- const roleRowLevelPermissionPredicateGroups =
- rowLevelPermissionPredicateGroups.byRoleId.get(role.id) ?? [];
-
- const objectRecordsPermissions: ObjectsPermissions = {};
-
- for (const objectMetadata of workspaceObjectMetadataCollection) {
- const {
- id: objectMetadataId,
- isSystem,
- universalIdentifier,
- } = objectMetadata;
-
- let canRead = role.canReadAllObjectRecords;
- let canUpdate = role.canUpdateAllObjectRecords;
- let canSoftDelete = role.canSoftDeleteAllObjectRecords;
- let canDestroy = role.canDestroyAllObjectRecords;
- const restrictedFields: RestrictedFieldsPermissions = {};
-
- const isWorkspaceMemberObject =
- universalIdentifier === WORKSPACE_MEMBER_OBJECT_UNIVERSAL_IDENTIFIER;
- const isWorkflowRelatedObject =
- WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.includes(
- universalIdentifier as (typeof WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS)[number],
- );
-
- if (isWorkflowRelatedObject) {
- const hasWorkflowsPermissions = isRolePermissionFlagGranted(
- PermissionFlagType.WORKFLOWS,
- );
-
- canRead = hasWorkflowsPermissions;
- canUpdate = hasWorkflowsPermissions;
- canSoftDelete = hasWorkflowsPermissions;
- canDestroy = hasWorkflowsPermissions;
- } else {
- if (isWorkspaceMemberObject) {
- const hasWorkspaceMembersPermissions = isRolePermissionFlagGranted(
- PermissionFlagType.WORKSPACE_MEMBERS,
- );
-
- canRead = true;
- canUpdate = hasWorkspaceMembersPermissions;
- canSoftDelete = hasWorkspaceMembersPermissions;
- canDestroy = hasWorkspaceMembersPermissions;
- } else {
- const objectRecordPermissionsOverride = roleObjectPermissions.find(
- (objectPermission) =>
- objectPermission.objectMetadataId === objectMetadataId,
- );
-
- const getPermissionValue = (
- overrideValue: boolean | null | undefined,
- defaultValue: boolean,
- ) => overrideValue ?? (isSystem ? true : defaultValue);
-
- canRead = getPermissionValue(
- objectRecordPermissionsOverride?.canReadObjectRecords,
- canRead,
- );
- canUpdate = getPermissionValue(
- objectRecordPermissionsOverride?.canUpdateObjectRecords,
- canUpdate,
- );
- canSoftDelete = getPermissionValue(
- objectRecordPermissionsOverride?.canSoftDeleteObjectRecords,
- canSoftDelete,
- );
- canDestroy = getPermissionValue(
- objectRecordPermissionsOverride?.canDestroyObjectRecords,
- canDestroy,
- );
- }
-
- const fieldPermissionsForObject = roleFieldPermissions.filter(
- (fieldPermission) =>
- fieldPermission.objectMetadataId === objectMetadataId,
- );
-
- for (const fieldPermission of fieldPermissionsForObject) {
- const isFieldLabelIdentifier =
- fieldPermission.fieldMetadataId ===
- objectMetadata.labelIdentifierFieldMetadataId;
-
- if (
- isDefined(fieldPermission.canReadFieldValue) ||
- isDefined(fieldPermission.canUpdateFieldValue)
- ) {
- const fieldRestriction = {
- canRead: isFieldLabelIdentifier
- ? true
- : fieldPermission.canReadFieldValue,
- canUpdate: fieldPermission.canUpdateFieldValue,
- };
-
- for (const restrictedFieldId of resolveMorphRelationPermissionFieldIds(
- fieldPermission.fieldMetadataId,
- )) {
- restrictedFields[restrictedFieldId] =
- mergeRestrictedFieldPermissions({
- existing: restrictedFields[restrictedFieldId],
- incoming: fieldRestriction,
- });
- }
- }
- }
- }
-
- if (
- universalIdentifier ===
- STANDARD_OBJECTS.agentChatThread.universalIdentifier
- ) {
- const hasAiPermission = isRolePermissionFlagGranted(
- PermissionFlagType.AI,
- );
- canRead = canRead && hasAiPermission;
- canUpdate = canUpdate && hasAiPermission;
- canSoftDelete = canSoftDelete && hasAiPermission;
- canDestroy = canDestroy && hasAiPermission;
- }
-
- objectRecordsPermissions[objectMetadataId] = {
- canReadObjectRecords: canRead,
- canUpdateObjectRecords: canUpdate,
- canSoftDeleteObjectRecords: canSoftDelete,
- canDestroyObjectRecords: canDestroy,
- restrictedFields,
- rowLevelPermissionPredicates: roleRowLevelPermissionPredicates.filter(
- (rowLevelPermissionPredicate) =>
- rowLevelPermissionPredicate.objectMetadataId === objectMetadataId,
- ),
- rowLevelPermissionPredicateGroups:
- roleRowLevelPermissionPredicateGroups.filter(
- (rowLevelPermissionPredicateGroup) =>
- rowLevelPermissionPredicateGroup.objectMetadataId ===
- objectMetadataId,
- ),
- };
- }
-
- permissionsByRoleId[role.id] = objectRecordsPermissions;
}
return permissionsByRoleId;
}
- private getRolePermissionFlagUniversalIdentifier(
- rolePermissionFlag: RolePermissionFlagEntity,
- ): string {
+ private getRolePermissionFlagUniversalIdentifier({
+ flag,
+ permissionFlag,
+ }: {
+ flag: PermissionFlagType;
+ permissionFlag:
+ | Pick<PermissionFlagEntity, 'universalIdentifier'>
+ | undefined;
+ }): string {
// The permissionFlag relation is stripped until the 2.6.0 upgrade cursor, so fall back to the legacy flag column
- return (
- rolePermissionFlag.permissionFlag?.universalIdentifier ??
- SystemPermissionFlag[rolePermissionFlag.flag as PermissionFlagType]
- );
+ return permissionFlag?.universalIdentifier ?? SystemPermissionFlag[flag];
}
}
diff --git a/packages/twenty-server/src/engine/permissions/combine/utils/__tests__/resolve-permissions-row-access-outcome.util.spec.ts b/packages/twenty-server/src/engine/permissions/combine/utils/__tests__/resolve-permissions-row-access-outcome.util.spec.ts
index 4d5def23d8d..cf9ab7cb00c 100644
--- a/packages/twenty-server/src/engine/permissions/combine/utils/__tests__/resolve-permissions-row-access-outcome.util.spec.ts
+++ b/packages/twenty-server/src/engine/permissions/combine/utils/__tests__/resolve-permissions-row-access-outcome.util.spec.ts
@@ -153,4 +153,52 @@ describe('resolvePermissionsRowAccessOutcome', () => {
}),
).toBe(true);
});
+
+ describe('for a principal narrowed by a scope', () => {
+ const scopedPrincipal = ({
+ canReadObjectRecords,
+ }: {
+ canReadObjectRecords: boolean;
+ }): PermissionsPrincipalsWithRolesContext => ({
+ ...readOnlyPrincipal,
+ scope: {
+ objectsPermissions: {
+ [flatObjectMetadata.id]: {
+ ...readOnlyPermissions,
+ canReadObjectRecords,
+ },
+ },
+ },
+ });
+
+ it('denies what the scope denies, though the role permits it', () => {
+ expect(
+ resolveOutcome({
+ principal: scopedPrincipal({ canReadObjectRecords: false }),
+ }),
+ ).toBe(false);
+ expect(
+ resolveOutcome({
+ principal: scopedPrincipal({ canReadObjectRecords: true }),
+ }),
+ ).toBeUndefined();
+ });
+
+ it('never lets a share carry it beyond its roles', () => {
+ const principal = scopedPrincipal({ canReadObjectRecords: true });
+ const featureFlagKeys = [FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED];
+
+ expect(
+ resolveOutcome({ principal, operationType: 'update', featureFlagKeys }),
+ ).toBe(false);
+ expect(
+ resolveOutcome({
+ principal,
+ operationType: 'update',
+ featureFlagKeys,
+ hypotheticalRecordShareAccessLevel: RecordShareAccessLevel.READ_WRITE,
+ }),
+ ).toBe(false);
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/permissions/combine/utils/are-record-grants-held-to-row-level-permissions.util.ts b/packages/twenty-server/src/engine/permissions/combine/utils/are-record-grants-held-to-row-level-permissions.util.ts
index dfa17563090..4dd69cab4fb 100644
--- a/packages/twenty-server/src/engine/permissions/combine/utils/are-record-grants-held-to-row-level-permissions.util.ts
+++ b/packages/twenty-server/src/engine/permissions/combine/utils/are-record-grants-held-to-row-level-permissions.util.ts
@@ -1,15 +1,8 @@
/* @license Enterprise */
import { type PermissionsRowAccessRequest } from 'src/engine/permissions/combine/types/row-access-policy.type';
-import { isOperationGrantedBeyondRole } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role.util';
+import { isOperationGrantedBeyondRoleToPrincipal } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util';
-export const areRecordGrantsHeldToRowLevelPermissions = ({
- metadataMaps,
- flatObjectMetadata,
- operationType,
-}: PermissionsRowAccessRequest): boolean =>
- !isOperationGrantedBeyondRole({
- flatObjectMetadata,
- featureFlagsMap: metadataMaps.featureFlagsMap,
- operationType,
- });
+export const areRecordGrantsHeldToRowLevelPermissions = (
+ request: PermissionsRowAccessRequest,
+): boolean => !isOperationGrantedBeyondRoleToPrincipal(request);
diff --git a/packages/twenty-server/src/engine/permissions/combine/utils/resolve-permissions-row-access-outcome.util.ts b/packages/twenty-server/src/engine/permissions/combine/utils/resolve-permissions-row-access-outcome.util.ts
index 285d2c96691..2ba5d94e280 100644
--- a/packages/twenty-server/src/engine/permissions/combine/utils/resolve-permissions-row-access-outcome.util.ts
+++ b/packages/twenty-server/src/engine/permissions/combine/utils/resolve-permissions-row-access-outcome.util.ts
@@ -2,15 +2,13 @@
import { type PermissionsRowAccessRequest } from 'src/engine/permissions/combine/types/row-access-policy.type';
import { hasHypotheticalRecordShare } from 'src/engine/permissions/record-share/utils/has-hypothetical-record-share.util';
-import { isOperationGrantedBeyondRole } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role.util';
+import { isOperationGrantedBeyondRoleToPrincipal } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util';
import { isObjectOperationDeniedToPrincipal } from 'src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util';
import { isObjectOperationDisabledToPrincipal } from 'src/engine/permissions/role/utils/is-object-operation-disabled-to-principal.util';
export const resolvePermissionsRowAccessOutcome = (
request: PermissionsRowAccessRequest,
): boolean | undefined => {
- const { metadataMaps, flatObjectMetadata, operationType } = request;
-
if (
isObjectOperationDisabledToPrincipal(request) ||
isObjectOperationDeniedToPrincipal(request)
@@ -19,11 +17,7 @@ export const resolvePermissionsRowAccessOutcome = (
}
if (
- isOperationGrantedBeyondRole({
- flatObjectMetadata,
- featureFlagsMap: metadataMaps.featureFlagsMap,
- operationType,
- }) &&
+ isOperationGrantedBeyondRoleToPrincipal(request) &&
hasHypotheticalRecordShare(request)
) {
return true;
diff --git a/packages/twenty-server/src/engine/permissions/permissions.service.ts b/packages/twenty-server/src/engine/permissions/permissions.service.ts
index c306a096bfc..faa14b04438 100644
--- a/packages/twenty-server/src/engine/permissions/permissions.service.ts
+++ b/packages/twenty-server/src/engine/permissions/permissions.service.ts
@@ -176,12 +176,17 @@ export class PermissionsService {
'flatRolePermissionFlagMaps',
]);
- return this.isPermissionFlagGrantedToRoles({
- roleIdsBySource: rolePermissionConfig.intersectionOf,
- setting,
- flatRoleMaps,
- flatRolePermissionFlagMaps,
- });
+ const { scope } = rolePermissionConfig;
+
+ return (
+ (!isDefined(scope) || (scope.permissionFlags[setting] ?? false)) &&
+ this.isPermissionFlagGrantedToRoles({
+ roleIdsBySource: rolePermissionConfig.intersectionOf,
+ setting,
+ flatRoleMaps,
+ flatRolePermissionFlagMaps,
+ })
+ );
}
// Like the ORM, a role missing from the cache grants nothing
diff --git a/packages/twenty-server/src/engine/permissions/principal/types/permission-scope.type.ts b/packages/twenty-server/src/engine/permissions/principal/types/permission-scope.type.ts
new file mode 100644
index 00000000000..21b2ab6dd3f
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/principal/types/permission-scope.type.ts
@@ -0,0 +1,11 @@
+import { type PermissionFlagType } from 'twenty-shared/constants';
+
+import { type UserWorkspacePermissions } from 'src/engine/permissions/types/user-workspace-permissions.type';
+
+// A restriction written inline on an AI run rather than stored as a role, resolved like a member's permissions
+export type PermissionScope = Pick<
+ UserWorkspacePermissions,
+ 'objectsPermissions'
+> & {
+ permissionFlags: Partial<Record<PermissionFlagType, boolean>>;
+};
diff --git a/packages/twenty-server/src/engine/permissions/principal/types/permissions-principals-with-roles-context.type.ts b/packages/twenty-server/src/engine/permissions/principal/types/permissions-principals-with-roles-context.type.ts
index 191e9fa5d82..9e9383aeb99 100644
--- a/packages/twenty-server/src/engine/permissions/principal/types/permissions-principals-with-roles-context.type.ts
+++ b/packages/twenty-server/src/engine/permissions/principal/types/permissions-principals-with-roles-context.type.ts
@@ -1,5 +1,6 @@
/* @license Enterprise */
+import { type PermissionScope } from 'src/engine/permissions/principal/types/permission-scope.type';
import {
type PermissionsAgentPrincipal,
type PermissionsApiKeyPrincipal,
@@ -34,4 +35,6 @@ export type PermissionsPrincipalsWithRolesContext = {
mainPrincipal: PermissionsMainPrincipalWithRole;
limitingPrincipal?: PermissionsLimitingPrincipalWithRole;
applicationPrincipal: PermissionsApplicationPrincipalWithRole;
+ // narrows what the roles allow, and leaves no reach beyond them
+ scope?: Pick<PermissionScope, 'objectsPermissions'>;
};
diff --git a/packages/twenty-server/src/engine/permissions/principal/types/role-permission-config.type.ts b/packages/twenty-server/src/engine/permissions/principal/types/role-permission-config.type.ts
index 3f78e6421f6..8885a55cec4 100644
--- a/packages/twenty-server/src/engine/permissions/principal/types/role-permission-config.type.ts
+++ b/packages/twenty-server/src/engine/permissions/principal/types/role-permission-config.type.ts
@@ -1,3 +1,5 @@
+import { type PermissionScope } from 'src/engine/permissions/principal/types/permission-scope.type';
+
// null: this actor takes part but has no role, so nothing is allowed
export type RoleIdsBySource = {
userWorkspaceRoleId?: string | null;
@@ -9,4 +11,7 @@ export type RoleIdsBySource = {
export type RolePermissionConfig =
| { shouldBypassPermissionChecks: true }
- | { intersectionOf: RoleIdsBySource };
+ | {
+ intersectionOf: RoleIdsBySource;
+ scope?: PermissionScope;
+ };
diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/build-permissions-principals-with-roles-from-config.util.ts b/packages/twenty-server/src/engine/permissions/principal/utils/build-permissions-principals-with-roles-from-config.util.ts
index 3fd753ffbc1..1337449193e 100644
--- a/packages/twenty-server/src/engine/permissions/principal/utils/build-permissions-principals-with-roles-from-config.util.ts
+++ b/packages/twenty-server/src/engine/permissions/principal/utils/build-permissions-principals-with-roles-from-config.util.ts
@@ -21,8 +21,9 @@ export const buildPermissionsPrincipalsWithRolesFromConfig = ({
return undefined;
}
+ const { intersectionOf, scope } = rolePermissionConfig;
const principalRoles = buildPermissionsPrincipalRoles({
- roleIdsBySource: rolePermissionConfig.intersectionOf,
+ roleIdsBySource: intersectionOf,
principalsContext,
});
@@ -30,5 +31,9 @@ export const buildPermissionsPrincipalsWithRolesFromConfig = ({
return undefined;
}
- return { workspaceId, ...principalRoles };
+ return {
+ workspaceId,
+ ...principalRoles,
+ ...(isDefined(scope) ? { scope } : {}),
+ };
};
diff --git a/packages/twenty-server/src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util.ts b/packages/twenty-server/src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util.ts
new file mode 100644
index 00000000000..130b5b22c89
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util.ts
@@ -0,0 +1,23 @@
+/* @license Enterprise */
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type PermissionsObjectAccessRequest } from 'src/engine/permissions/combine/types/row-access-policy.type';
+import { isOperationGrantedBeyondRole } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role.util';
+
+// a scope bounds everything a run reaches, so shares never carry a scoped principal past its roles
+export const isOperationGrantedBeyondRoleToPrincipal = ({
+ principal,
+ flatObjectMetadata,
+ metadataMaps,
+ operationType,
+}: Pick<
+ PermissionsObjectAccessRequest,
+ 'principal' | 'flatObjectMetadata' | 'metadataMaps' | 'operationType'
+>): boolean =>
+ !isDefined(principal.scope) &&
+ isOperationGrantedBeyondRole({
+ flatObjectMetadata,
+ featureFlagsMap: metadataMaps.featureFlagsMap,
+ operationType,
+ });
diff --git a/packages/twenty-server/src/engine/permissions/record-share/utils/resolve-permissions-share-grant.util.ts b/packages/twenty-server/src/engine/permissions/record-share/utils/resolve-permissions-share-grant.util.ts
index f0d70402dfe..d09e4a91df2 100644
--- a/packages/twenty-server/src/engine/permissions/record-share/utils/resolve-permissions-share-grant.util.ts
+++ b/packages/twenty-server/src/engine/permissions/record-share/utils/resolve-permissions-share-grant.util.ts
@@ -7,7 +7,7 @@ import { type PermissionsRowAccessRequest } from 'src/engine/permissions/combine
import { getPermissionsPrincipalShareKeys } from 'src/engine/permissions/principal/utils/get-permissions-principal-share-keys.util';
import { isShareOnlyWhilePrivateRecordFlagDisabled } from 'src/engine/permissions/private-record/utils/is-share-only-while-private-record-flag-disabled.util';
import { isRecordPrivacyApplicable } from 'src/engine/permissions/private-record/utils/is-record-privacy-applicable.util';
-import { isOperationGrantedBeyondRole } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role.util';
+import { isOperationGrantedBeyondRoleToPrincipal } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util';
import { resolveRequiredRecordShareAccessLevels } from 'src/engine/permissions/record-share/utils/resolve-required-record-share-access-levels.util';
export const resolvePermissionsShareGrant = (
@@ -23,11 +23,7 @@ export const resolvePermissionsShareGrant = (
const accessLevels = resolveRequiredRecordShareAccessLevels(
request.operationType,
);
- const isGrantedBeyondRole = isOperationGrantedBeyondRole({
- flatObjectMetadata: request.flatObjectMetadata,
- featureFlagsMap: request.metadataMaps.featureFlagsMap,
- operationType: request.operationType,
- });
+ const isGrantedBeyondRole = isOperationGrantedBeyondRoleToPrincipal(request);
// TODO(@charlesBochet): remove with isShareOnlyWhilePrivateRecordFlagDisabled after 2.55
const isShareOnly = isShareOnlyWhilePrivateRecordFlagDisabled(request);
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/__tests__/get-objects-permissions-from-role-permission-config.util.spec.ts b/packages/twenty-server/src/engine/permissions/role/utils/__tests__/get-objects-permissions-from-role-permission-config.util.spec.ts
index d6fec3af43e..97364bc198b 100644
--- a/packages/twenty-server/src/engine/permissions/role/utils/__tests__/get-objects-permissions-from-role-permission-config.util.spec.ts
+++ b/packages/twenty-server/src/engine/permissions/role/utils/__tests__/get-objects-permissions-from-role-permission-config.util.spec.ts
@@ -2,13 +2,17 @@ import {
FieldMetadataType,
type ObjectPermissions,
type ObjectsPermissionsByRoleId,
+ type RowLevelPermissionPredicate,
+ RowLevelPermissionPredicateOperand,
} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { getObjectsPermissionsFromRolePermissionConfig } from 'src/engine/permissions/role/utils/get-objects-permissions-from-role-permission-config.util';
+import { validateOperationIsPermittedOrThrow } from 'src/engine/permissions/role/utils/validate-operation-is-permitted-or-throw.util';
import { type ApplicationDefaultRoleMaps } from 'src/engine/permissions/principal/types/application-default-role-maps.type';
import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
@@ -230,6 +234,8 @@ flatObjectMetadataMaps.byUniversalIdentifier.invoice =
getFlatObjectMetadataMock({
id: INVOICE_ID,
universalIdentifier: 'invoice',
+ nameSingular: 'invoice',
+ fieldIds: [AMOUNT_FIELD_ID],
applicationId: 'owning-application-id',
disabledObjectPermissionActions: ['canDestroyObjectRecords'],
});
@@ -241,6 +247,7 @@ const flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata> =
flatFieldMetadataMaps.byUniversalIdentifier.amount = getFlatFieldMetadataMock({
id: AMOUNT_FIELD_ID,
universalIdentifier: 'amount',
+ name: 'amount',
objectMetadataId: INVOICE_ID,
type: FieldMetadataType.NUMBER,
applicationId: 'owning-application-id',
@@ -507,3 +514,178 @@ describe('getObjectsPermissionsFromRolePermissionConfig disabled actions', () =>
).toBe(false);
});
});
+
+describe('getObjectsPermissionsFromRolePermissionConfig with a scope', () => {
+ const USER_PREDICATE: RowLevelPermissionPredicate = {
+ id: 'predicate-id',
+ fieldMetadataId: AMOUNT_FIELD_ID,
+ objectMetadataId: INVOICE_ID,
+ operand: RowLevelPermissionPredicateOperand.IS,
+ value: 'mine',
+ subFieldName: null,
+ rowLevelPermissionPredicateGroupId: null,
+ workspaceMemberFieldMetadataId: null,
+ workspaceMemberSubFieldName: null,
+ roleId: 'user-role-id',
+ };
+
+ const rolesPermissionsWithPredicate = {
+ ...disabledActionRolesPermissions,
+ 'user-role-id': {
+ [INVOICE_ID]: {
+ ...FULL_ACCESS,
+ rowLevelPermissionPredicates: [USER_PREDICATE],
+ },
+ },
+ };
+
+ const compute = ({
+ intersectionOf,
+ scopeObjectPermissions,
+ }: {
+ intersectionOf: RoleIdsBySource;
+ scopeObjectPermissions?: ObjectPermissions;
+ }) =>
+ getObjectsPermissionsFromRolePermissionConfig({
+ principals: undefined,
+ rolePermissionConfig: {
+ intersectionOf,
+ scope: {
+ objectsPermissions: isDefined(scopeObjectPermissions)
+ ? { [INVOICE_ID]: scopeObjectPermissions }
+ : {},
+ permissionFlags: {},
+ },
+ },
+ rolesPermissions: rolesPermissionsWithPredicate,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ flatApplicationMaps,
+ })[INVOICE_ID];
+
+ it('narrows the roles to what the scope allows', () => {
+ const invoicePermissions = compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: {
+ ...FULL_ACCESS,
+ canUpdateObjectRecords: false,
+ },
+ });
+
+ expect(invoicePermissions?.canReadObjectRecords).toBe(true);
+ expect(invoicePermissions?.canUpdateObjectRecords).toBe(false);
+ });
+
+ it('never grants what the roles deny', () => {
+ const invoicePermissions = compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: FULL_ACCESS,
+ });
+
+ expect(invoicePermissions?.canDestroyObjectRecords).toBe(false);
+ });
+
+ it('denies an object the scope leaves out', () => {
+ const invoicePermissions = compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ });
+
+ expect(invoicePermissions?.canReadObjectRecords).toBe(false);
+ expect(invoicePermissions?.canUpdateObjectRecords).toBe(false);
+ });
+
+ it("keeps the roles' row-level predicates", () => {
+ const invoicePermissions = compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: FULL_ACCESS,
+ });
+
+ expect(invoicePermissions?.rowLevelPermissionPredicates).toEqual([
+ USER_PREDICATE,
+ ]);
+ });
+
+ it('adds the field restrictions of the scope', () => {
+ const invoicePermissions = compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: {
+ ...FULL_ACCESS,
+ restrictedFields: {
+ [AMOUNT_FIELD_ID]: { canRead: false, canUpdate: false },
+ },
+ },
+ });
+
+ expect(invoicePermissions?.restrictedFields[AMOUNT_FIELD_ID]).toEqual({
+ canRead: false,
+ canUpdate: false,
+ });
+ });
+
+ describe('inserting a record that sets the predicate field', () => {
+ // the user role cannot update amount (a disabled action), which its own predicate exempts on insert
+ const insertAmount = (invoicePermissions: ObjectPermissions | undefined) =>
+ validateOperationIsPermittedOrThrow({
+ entityName: 'invoice',
+ operationType: 'insert',
+ objectsPermissions: isDefined(invoicePermissions)
+ ? { [INVOICE_ID]: invoicePermissions }
+ : {},
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ objectIdByNameSingular: { invoice: INVOICE_ID },
+ selectedColumns: [],
+ updatedColumns: ['amount'],
+ });
+
+ it('is allowed without a scope', () => {
+ expect(() =>
+ insertAmount(
+ getObjectsPermissionsFromRolePermissionConfig({
+ principals: undefined,
+ rolePermissionConfig: {
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ },
+ rolesPermissions: rolesPermissionsWithPredicate,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ flatApplicationMaps,
+ })[INVOICE_ID],
+ ),
+ ).not.toThrow();
+ });
+
+ it('is allowed when the scope does not restrict the field', () => {
+ expect(() =>
+ insertAmount(
+ compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: FULL_ACCESS,
+ }),
+ ),
+ ).not.toThrow();
+ });
+
+ it('is refused when the scope denies writing the field', () => {
+ expect(() =>
+ insertAmount(
+ compute({
+ intersectionOf: { userWorkspaceRoleId: 'user-role-id' },
+ scopeObjectPermissions: {
+ ...FULL_ACCESS,
+ restrictedFields: {
+ [AMOUNT_FIELD_ID]: { canRead: null, canUpdate: false },
+ },
+ },
+ }),
+ ),
+ ).toThrow('no permission to write field "amount" on "invoice"');
+ });
+ });
+
+ it('grants nothing without a role', () => {
+ expect(
+ compute({ intersectionOf: {}, scopeObjectPermissions: FULL_ACCESS }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/__tests__/resolve-ai-run-permission-scope.util.spec.ts b/packages/twenty-server/src/engine/permissions/role/utils/__tests__/resolve-ai-run-permission-scope.util.spec.ts
new file mode 100644
index 00000000000..45c77f680d5
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/role/utils/__tests__/resolve-ai-run-permission-scope.util.spec.ts
@@ -0,0 +1,343 @@
+import {
+ PermissionFlagType,
+ SystemPermissionFlag,
+} from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { FieldMetadataType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { resolveAiRunPermissionScope } from 'src/engine/permissions/role/utils/resolve-ai-run-permission-scope.util';
+import { isObjectOperationDeniedToPrincipal } from 'src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util';
+import { type PermissionsPrincipalsWithRolesContext } from 'src/engine/permissions/principal/types/permissions-principals-with-roles-context.type';
+import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+const PERSON_ID = 'person-id';
+const COMPANY_ID = 'company-id';
+const WORKFLOW_ID = 'workflow-id';
+const CAMPAIGN_ID = 'campaign-id';
+const WORKFLOW_UNIVERSAL_IDENTIFIER =
+ STANDARD_OBJECTS.workflow.universalIdentifier;
+const EMAIL_FIELD_ID = 'email-field-id';
+
+const flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata> =
+ createEmptyFlatEntityMaps();
+
+for (const [id, universalIdentifier, isSystem] of [
+ [PERSON_ID, 'person', false],
+ [COMPANY_ID, 'company', false],
+ [WORKFLOW_ID, WORKFLOW_UNIVERSAL_IDENTIFIER, false],
+ [CAMPAIGN_ID, 'campaign', true],
+] as const) {
+ flatObjectMetadataMaps.byUniversalIdentifier[universalIdentifier] =
+ getFlatObjectMetadataMock({
+ id,
+ universalIdentifier,
+ nameSingular: universalIdentifier,
+ isSystem,
+ });
+ flatObjectMetadataMaps.universalIdentifierById[id] = universalIdentifier;
+}
+
+const flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata> =
+ createEmptyFlatEntityMaps();
+
+flatFieldMetadataMaps.byUniversalIdentifier.email = getFlatFieldMetadataMock({
+ id: EMAIL_FIELD_ID,
+ universalIdentifier: 'email',
+ objectMetadataId: PERSON_ID,
+ type: FieldMetadataType.TEXT,
+});
+flatFieldMetadataMaps.universalIdentifierById[EMAIL_FIELD_ID] = 'email';
+
+const resolve = (
+ scope: Parameters<typeof resolveAiRunPermissionScope>[0]['scope'],
+) => {
+ const { objectsPermissions, permissionFlags } = resolveAiRunPermissionScope({
+ scope,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ });
+
+ return {
+ objectsPermissions,
+ grantedPermissionFlags: Object.values(PermissionFlagType).filter(
+ (permissionFlag) => permissionFlags[permissionFlag],
+ ),
+ };
+};
+
+describe('resolveAiRunPermissionScope', () => {
+ it('denies everything an empty scope leaves out', () => {
+ const { objectsPermissions, grantedPermissionFlags } = resolve({});
+
+ expect(objectsPermissions[PERSON_ID]?.canReadObjectRecords).toBe(false);
+ expect(objectsPermissions[COMPANY_ID]?.canUpdateObjectRecords).toBe(false);
+ expect(grantedPermissionFlags).toEqual([]);
+ });
+
+ it('allows only the actions it names on the objects it names', () => {
+ const { objectsPermissions } = resolve({
+ objectPermissions: [
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: true },
+ ],
+ });
+
+ expect(objectsPermissions[PERSON_ID]).toMatchObject({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ });
+ expect(objectsPermissions[COMPANY_ID]?.canReadObjectRecords).toBe(false);
+ });
+
+ it('lets an object entry narrow an action granted on all objects', () => {
+ const { objectsPermissions } = resolve({
+ canReadAllObjectRecords: true,
+ objectPermissions: [
+ { objectUniversalIdentifier: 'company', canReadObjectRecords: false },
+ ],
+ });
+
+ expect(objectsPermissions[PERSON_ID]?.canReadObjectRecords).toBe(true);
+ expect(objectsPermissions[COMPANY_ID]?.canReadObjectRecords).toBe(false);
+ });
+
+ it('restricts the fields it names', () => {
+ const { objectsPermissions } = resolve({
+ canReadAllObjectRecords: true,
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ ],
+ });
+
+ expect(
+ objectsPermissions[PERSON_ID]?.restrictedFields[EMAIL_FIELD_ID],
+ ).toMatchObject({ canRead: false });
+ });
+
+ it.each([
+ {
+ unknown: 'an object',
+ scope: {
+ objectPermissions: [
+ { objectUniversalIdentifier: 'unknown', canReadObjectRecords: false },
+ ],
+ },
+ message: 'Object unknown in an AI run scope does not exist',
+ },
+ {
+ unknown: 'the object of a field',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'unknown',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ message: 'Object unknown in an AI run scope does not exist',
+ },
+ {
+ unknown: 'a field',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'unknown',
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ message: 'Field unknown in an AI run scope does not exist',
+ },
+ ])(
+ 'refuses a scope naming $unknown the workspace does not have',
+ ({ scope, message }) => {
+ expect(() => resolve(scope)).toThrow(message);
+ },
+ );
+
+ describe('on the workflow objects, which the workflows flag grants', () => {
+ const WORKFLOWS_FLAG = SystemPermissionFlag[PermissionFlagType.WORKFLOWS];
+
+ it('grants every action with the flag', () => {
+ expect(
+ resolve({ permissionFlagUniversalIdentifiers: [WORKFLOWS_FLAG] })
+ .objectsPermissions[WORKFLOW_ID],
+ ).toMatchObject({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canDestroyObjectRecords: true,
+ });
+ });
+
+ it('lets an explicit deny narrow what the flag grants', () => {
+ expect(
+ resolve({
+ permissionFlagUniversalIdentifiers: [WORKFLOWS_FLAG],
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: WORKFLOW_UNIVERSAL_IDENTIFIER,
+ canUpdateObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ }).objectsPermissions[WORKFLOW_ID],
+ ).toMatchObject({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ canDestroyObjectRecords: false,
+ });
+ });
+
+ it('never lets an explicit grant stand in for the flag', () => {
+ expect(
+ resolve({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: WORKFLOW_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ }).objectsPermissions[WORKFLOW_ID]?.canReadObjectRecords,
+ ).toBe(false);
+ });
+ });
+
+ it('refuses a scope that lists an object twice', () => {
+ expect(() =>
+ resolve({
+ objectPermissions: [
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: true },
+ {
+ objectUniversalIdentifier: 'person',
+ canUpdateObjectRecords: false,
+ },
+ ],
+ }),
+ ).toThrow('An AI run scope lists an object or field more than once');
+ });
+
+ it('refuses a field named under an object it does not belong to', () => {
+ expect(() =>
+ resolve({
+ canReadAllObjectRecords: true,
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'company',
+ fieldUniversalIdentifier: 'email',
+ canReadFieldValue: false,
+ },
+ ],
+ }),
+ ).toThrow('Field email does not belong to object company');
+ });
+
+ describe('on a system object', () => {
+ it('leaves it readable but not writable when the scope grants nothing', () => {
+ expect(resolve({}).objectsPermissions[CAMPAIGN_ID]).toMatchObject({
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ });
+ });
+
+ it('lets a scope grant writing it, on all objects or on that one', () => {
+ expect(
+ resolve({ canUpdateAllObjectRecords: true }).objectsPermissions[
+ CAMPAIGN_ID
+ ]?.canUpdateObjectRecords,
+ ).toBe(true);
+ expect(
+ resolve({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: 'campaign',
+ canUpdateObjectRecords: true,
+ },
+ ],
+ }).objectsPermissions[CAMPAIGN_ID]?.canUpdateObjectRecords,
+ ).toBe(true);
+ });
+
+ it('refuses an insert by a member who can write it, under a scope that grants nothing', () => {
+ const isInsertDenied = (
+ scope?: PermissionsPrincipalsWithRolesContext['scope'],
+ ) =>
+ isObjectOperationDeniedToPrincipal({
+ principal: {
+ workspaceId: 'workspace-id',
+ mainPrincipal: {
+ type: 'workspaceMember',
+ roleId: 'member-role-id',
+ workspaceMemberId: 'workspace-member-id',
+ },
+ applicationPrincipal: { type: 'customApplication' },
+ ...(isDefined(scope) ? { scope } : {}),
+ },
+ metadataMaps: {
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ rolesPermissions: {
+ 'member-role-id': {
+ [CAMPAIGN_ID]: {
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: true,
+ canDestroyObjectRecords: true,
+ restrictedFields: {},
+ rowLevelPermissionPredicates: [],
+ rowLevelPermissionPredicateGroups: [],
+ },
+ },
+ },
+ flatApplicationMaps: { byId: {} },
+ flatRowLevelPermissionPredicateMaps: createEmptyFlatEntityMaps(),
+ flatRowLevelPermissionPredicateGroupMaps:
+ createEmptyFlatEntityMaps(),
+ featureFlagsMap: {},
+ },
+ flatObjectMetadata: flatObjectMetadataMaps.byUniversalIdentifier
+ .campaign as FlatObjectMetadata,
+ operationType: 'insert',
+ });
+
+ expect(isInsertDenied()).toBe(false);
+ expect(
+ isInsertDenied(
+ resolveAiRunPermissionScope({
+ scope: {},
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ }),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ it('grants the flags it names, and tool flags with all tools', () => {
+ expect(
+ resolve({
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag[PermissionFlagType.SEND_EMAIL_TOOL],
+ ],
+ }).grantedPermissionFlags,
+ ).toEqual([PermissionFlagType.SEND_EMAIL_TOOL]);
+ expect(
+ resolve({ canAccessAllTools: true }).grantedPermissionFlags,
+ ).toContain(PermissionFlagType.HTTP_REQUEST_TOOL);
+ expect(
+ resolve({ canAccessAllTools: true }).grantedPermissionFlags,
+ ).not.toContain(PermissionFlagType.WORKFLOWS);
+ });
+});
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/build-is-permission-flag-granted.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/build-is-permission-flag-granted.util.ts
new file mode 100644
index 00000000000..df9b1f4faf5
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/role/utils/build-is-permission-flag-granted.util.ts
@@ -0,0 +1,25 @@
+import {
+ type PermissionFlagType,
+ SystemPermissionFlag,
+} from 'twenty-shared/constants';
+
+import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
+import { hasRoleWideAccessToPermissionFlag } from 'src/engine/permissions/role/utils/has-role-wide-access-to-permission-flag.util';
+
+export const buildIsPermissionFlagGranted = ({
+ role,
+ permissionFlagUniversalIdentifiers,
+}: {
+ role: Pick<FlatRole, 'canUpdateAllSettings' | 'canAccessAllTools'>;
+ permissionFlagUniversalIdentifiers: Iterable<string>;
+}): ((permissionFlag: PermissionFlagType) => boolean) => {
+ const grantedPermissionFlagUniversalIdentifiers = new Set(
+ permissionFlagUniversalIdentifiers,
+ );
+
+ return (permissionFlag) =>
+ hasRoleWideAccessToPermissionFlag({ role, permissionFlag }) ||
+ grantedPermissionFlagUniversalIdentifiers.has(
+ SystemPermissionFlag[permissionFlag],
+ );
+};
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-role-definition.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-role-definition.util.ts
new file mode 100644
index 00000000000..02e5067449b
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-role-definition.util.ts
@@ -0,0 +1,244 @@
+import { resolveObjectPermissionValue } from 'twenty-shared/application';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import {
+ type ObjectsPermissions,
+ type RestrictedFieldsPermissions,
+ type RowLevelPermissionPredicate,
+ type RowLevelPermissionPredicateGroup,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FieldPermissionEntity } from 'src/engine/metadata-modules/object-permission/field-permission/field-permission.entity';
+import { type ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { type ObjectPermissionEntity } from 'src/engine/metadata-modules/object-permission/object-permission.entity';
+import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
+import { mergeRestrictedFieldPermissions } from 'src/engine/metadata-modules/role/utils/merge-restricted-field-permissions.util';
+
+const WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS: string[] = [
+ STANDARD_OBJECTS.workflow.universalIdentifier,
+ STANDARD_OBJECTS.workflowRun.universalIdentifier,
+ STANDARD_OBJECTS.workflowVersion.universalIdentifier,
+];
+
+type RoleDefinitionForObjectsPermissions = Pick<
+ FlatRole,
+ | 'canReadAllObjectRecords'
+ | 'canUpdateAllObjectRecords'
+ | 'canSoftDeleteAllObjectRecords'
+ | 'canDestroyAllObjectRecords'
+> & {
+ isPermissionFlagGranted: (permissionFlag: PermissionFlagType) => boolean;
+ // an AI run scope leaves system objects readable but not writable unless it grants them
+ areSystemObjectsReadOnlyByDefault?: boolean;
+ objectPermissions: Pick<
+ ObjectPermissionEntity,
+ | 'objectMetadataId'
+ | 'canReadObjectRecords'
+ | 'canUpdateObjectRecords'
+ | 'canSoftDeleteObjectRecords'
+ | 'canDestroyObjectRecords'
+ >[];
+ fieldPermissions: Pick<
+ FieldPermissionEntity,
+ | 'objectMetadataId'
+ | 'fieldMetadataId'
+ | 'canReadFieldValue'
+ | 'canUpdateFieldValue'
+ >[];
+ rowLevelPermissionPredicates: RowLevelPermissionPredicate[];
+ rowLevelPermissionPredicateGroups: RowLevelPermissionPredicateGroup[];
+};
+
+type ObjectRecordsAccess = {
+ canRead: boolean;
+ canUpdate: boolean;
+ canSoftDelete: boolean;
+ canDestroy: boolean;
+};
+
+const grantAllObjectRecordsAccess = (
+ isGranted: boolean,
+): ObjectRecordsAccess => ({
+ canRead: isGranted,
+ canUpdate: isGranted,
+ canSoftDelete: isGranted,
+ canDestroy: isGranted,
+});
+
+const resolveObjectRecordsAccess = ({
+ objectMetadata: { id: objectMetadataId, isSystem, universalIdentifier },
+ roleDefinition,
+}: {
+ objectMetadata: Pick<
+ ObjectMetadataEntity,
+ 'id' | 'isSystem' | 'universalIdentifier'
+ >;
+ roleDefinition: RoleDefinitionForObjectsPermissions;
+}): ObjectRecordsAccess => {
+ const { isPermissionFlagGranted, objectPermissions } = roleDefinition;
+
+ if (
+ WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.includes(universalIdentifier)
+ ) {
+ return grantAllObjectRecordsAccess(
+ isPermissionFlagGranted(PermissionFlagType.WORKFLOWS),
+ );
+ }
+
+ if (
+ universalIdentifier === STANDARD_OBJECTS.workspaceMember.universalIdentifier
+ ) {
+ return {
+ ...grantAllObjectRecordsAccess(
+ isPermissionFlagGranted(PermissionFlagType.WORKSPACE_MEMBERS),
+ ),
+ canRead: true,
+ };
+ }
+
+ const isSystemObjectWritableByDefault =
+ isSystem && !roleDefinition.areSystemObjectsReadOnlyByDefault;
+ const objectPermissionOverride = objectPermissions.find(
+ (objectPermission) =>
+ objectPermission.objectMetadataId === objectMetadataId,
+ );
+
+ return {
+ canRead: resolveObjectPermissionValue({
+ objectValue: objectPermissionOverride?.canReadObjectRecords,
+ hasAllObjectsPermission: roleDefinition.canReadAllObjectRecords,
+ isSystemObject: isSystem,
+ }),
+ canUpdate: resolveObjectPermissionValue({
+ objectValue: objectPermissionOverride?.canUpdateObjectRecords,
+ hasAllObjectsPermission: roleDefinition.canUpdateAllObjectRecords,
+ isSystemObject: isSystemObjectWritableByDefault,
+ }),
+ canSoftDelete: resolveObjectPermissionValue({
+ objectValue: objectPermissionOverride?.canSoftDeleteObjectRecords,
+ hasAllObjectsPermission: roleDefinition.canSoftDeleteAllObjectRecords,
+ isSystemObject: isSystemObjectWritableByDefault,
+ }),
+ canDestroy: resolveObjectPermissionValue({
+ objectValue: objectPermissionOverride?.canDestroyObjectRecords,
+ hasAllObjectsPermission: roleDefinition.canDestroyAllObjectRecords,
+ isSystemObject: isSystemObjectWritableByDefault,
+ }),
+ };
+};
+
+const buildRestrictedFields = ({
+ objectMetadata,
+ fieldPermissions,
+ resolveMorphRelationPermissionFieldIds,
+}: {
+ objectMetadata: Pick<
+ ObjectMetadataEntity,
+ 'id' | 'labelIdentifierFieldMetadataId'
+ >;
+ fieldPermissions: RoleDefinitionForObjectsPermissions['fieldPermissions'];
+ resolveMorphRelationPermissionFieldIds: (fieldMetadataId: string) => string[];
+}): RestrictedFieldsPermissions => {
+ const restrictedFields: RestrictedFieldsPermissions = {};
+
+ for (const fieldPermission of fieldPermissions) {
+ if (fieldPermission.objectMetadataId !== objectMetadata.id) {
+ continue;
+ }
+
+ if (
+ !isDefined(fieldPermission.canReadFieldValue) &&
+ !isDefined(fieldPermission.canUpdateFieldValue)
+ ) {
+ continue;
+ }
+
+ const isFieldLabelIdentifier =
+ fieldPermission.fieldMetadataId ===
+ objectMetadata.labelIdentifierFieldMetadataId;
+ const fieldRestriction = {
+ canRead: isFieldLabelIdentifier
+ ? true
+ : fieldPermission.canReadFieldValue,
+ canUpdate: fieldPermission.canUpdateFieldValue,
+ };
+
+ for (const restrictedFieldId of resolveMorphRelationPermissionFieldIds(
+ fieldPermission.fieldMetadataId,
+ )) {
+ restrictedFields[restrictedFieldId] = mergeRestrictedFieldPermissions({
+ existing: restrictedFields[restrictedFieldId],
+ incoming: fieldRestriction,
+ });
+ }
+ }
+
+ return restrictedFields;
+};
+
+export const computeObjectsPermissionsForRoleDefinition = ({
+ roleDefinition,
+ objectMetadataCollection,
+ resolveMorphRelationPermissionFieldIds,
+}: {
+ roleDefinition: RoleDefinitionForObjectsPermissions;
+ objectMetadataCollection: Pick<
+ ObjectMetadataEntity,
+ 'id' | 'isSystem' | 'universalIdentifier' | 'labelIdentifierFieldMetadataId'
+ >[];
+ resolveMorphRelationPermissionFieldIds: (fieldMetadataId: string) => string[];
+}): ObjectsPermissions => {
+ const {
+ isPermissionFlagGranted,
+ fieldPermissions,
+ rowLevelPermissionPredicates,
+ rowLevelPermissionPredicateGroups,
+ } = roleDefinition;
+ const objectsPermissions: ObjectsPermissions = {};
+
+ for (const objectMetadata of objectMetadataCollection) {
+ const { id: objectMetadataId, universalIdentifier } = objectMetadata;
+
+ const isWorkflowObject =
+ WORKFLOW_STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.includes(
+ universalIdentifier,
+ );
+ const objectRecordsAccess = resolveObjectRecordsAccess({
+ objectMetadata,
+ roleDefinition,
+ });
+ const restrictedFields = isWorkflowObject
+ ? {}
+ : buildRestrictedFields({
+ objectMetadata,
+ fieldPermissions,
+ resolveMorphRelationPermissionFieldIds,
+ });
+ const hasAiAccess =
+ universalIdentifier !==
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier ||
+ isPermissionFlagGranted(PermissionFlagType.AI);
+
+ objectsPermissions[objectMetadataId] = {
+ canReadObjectRecords: objectRecordsAccess.canRead && hasAiAccess,
+ canUpdateObjectRecords: objectRecordsAccess.canUpdate && hasAiAccess,
+ canSoftDeleteObjectRecords:
+ objectRecordsAccess.canSoftDelete && hasAiAccess,
+ canDestroyObjectRecords: objectRecordsAccess.canDestroy && hasAiAccess,
+ restrictedFields,
+ rowLevelPermissionPredicates: rowLevelPermissionPredicates.filter(
+ (rowLevelPermissionPredicate) =>
+ rowLevelPermissionPredicate.objectMetadataId === objectMetadataId,
+ ),
+ rowLevelPermissionPredicateGroups:
+ rowLevelPermissionPredicateGroups.filter(
+ (rowLevelPermissionPredicateGroup) =>
+ rowLevelPermissionPredicateGroup.objectMetadataId ===
+ objectMetadataId,
+ ),
+ };
+ }
+
+ return objectsPermissions;
+};
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-roles.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-roles.util.ts
index 993e73a782d..508602d757f 100644
--- a/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-roles.util.ts
+++ b/packages/twenty-server/src/engine/permissions/role/utils/compute-objects-permissions-for-roles.util.ts
@@ -15,6 +15,7 @@ import { getPermissionsPrincipalActingApplicationId } from 'src/engine/permissio
import { getPermissionsPrincipalRoleIds } from 'src/engine/permissions/principal/utils/get-permissions-principal-role-ids.util';
import { computePermissionIntersection } from 'src/engine/permissions/role/utils/compute-permission-intersection.util';
import { restrictObjectsPermissionsToDisabledActions } from 'src/engine/permissions/role/utils/restrict-objects-permissions-to-disabled-actions.util';
+import { restrictObjectsPermissionsToScope } from 'src/engine/permissions/role/utils/restrict-objects-permissions-to-scope.util';
export const computeObjectsPermissionsForRoles = ({
principal,
@@ -25,7 +26,7 @@ export const computeObjectsPermissionsForRoles = ({
}: {
principal: Pick<
PermissionsPrincipalsWithRolesContext,
- 'mainPrincipal' | 'limitingPrincipal' | 'applicationPrincipal'
+ 'mainPrincipal' | 'limitingPrincipal' | 'applicationPrincipal' | 'scope'
>;
rolesPermissions: ObjectsPermissionsByRoleId;
flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
@@ -67,5 +68,12 @@ export const computeObjectsPermissionsForRoles = ({
return {};
}
- return computePermissionIntersection(permissionsPerRole);
+ const objectsPermissions = computePermissionIntersection(permissionsPerRole);
+
+ return isDefined(principal.scope)
+ ? restrictObjectsPermissionsToScope({
+ objectsPermissions,
+ scope: principal.scope,
+ })
+ : objectsPermissions;
};
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/get-objects-permissions-from-role-permission-config.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/get-objects-permissions-from-role-permission-config.util.ts
index 96e1a2f9ca4..5c337002386 100644
--- a/packages/twenty-server/src/engine/permissions/role/utils/get-objects-permissions-from-role-permission-config.util.ts
+++ b/packages/twenty-server/src/engine/permissions/role/utils/get-objects-permissions-from-role-permission-config.util.ts
@@ -32,8 +32,9 @@ export const getObjectsPermissionsFromRolePermissionConfig = ({
return {};
}
+ const { intersectionOf, scope } = rolePermissionConfig;
const principalRoles = buildPermissionsPrincipalRoles({
- roleIdsBySource: rolePermissionConfig.intersectionOf,
+ roleIdsBySource: intersectionOf,
principalsContext: principals,
});
@@ -42,7 +43,7 @@ export const getObjectsPermissionsFromRolePermissionConfig = ({
}
return computeObjectsPermissionsForRoles({
- principal: principalRoles,
+ principal: { ...principalRoles, scope },
rolesPermissions,
flatObjectMetadataMaps,
flatFieldMetadataMaps,
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util.ts
index 26476ccea19..e5baa94e75c 100644
--- a/packages/twenty-server/src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util.ts
+++ b/packages/twenty-server/src/engine/permissions/role/utils/is-object-operation-denied-to-principal.util.ts
@@ -1,15 +1,11 @@
/* @license Enterprise */
import { type PermissionsObjectAccessRequest } from 'src/engine/permissions/combine/types/row-access-policy.type';
-import { isOperationGrantedBeyondRole } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role.util';
+import { isOperationGrantedBeyondRoleToPrincipal } from 'src/engine/permissions/record-share/utils/is-operation-granted-beyond-role-to-principal.util';
import { isRolePermittingOperation } from 'src/engine/permissions/role/utils/is-role-permitting-operation.util';
export const isObjectOperationDeniedToPrincipal = (
request: PermissionsObjectAccessRequest,
): boolean =>
!isRolePermittingOperation(request) &&
- !isOperationGrantedBeyondRole({
- flatObjectMetadata: request.flatObjectMetadata,
- featureFlagsMap: request.metadataMaps.featureFlagsMap,
- operationType: request.operationType,
- });
+ !isOperationGrantedBeyondRoleToPrincipal(request);
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/resolve-ai-run-permission-scope.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/resolve-ai-run-permission-scope.util.ts
new file mode 100644
index 00000000000..2a2a4c39e63
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/role/utils/resolve-ai-run-permission-scope.util.ts
@@ -0,0 +1,199 @@
+import { PermissionFlagType } from 'twenty-shared/constants';
+import {
+ type AiRunScope,
+ type AiRunScopeObjectPermission,
+ hasAiRunScopeRepeatedEntries,
+} from 'twenty-shared/ai';
+import { OBJECT_PERMISSION_ACTIONS } from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ type ObjectsPermissions,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { buildIsPermissionFlagGranted } from 'src/engine/permissions/role/utils/build-is-permission-flag-granted.util';
+import { buildResolveMorphRelationPermissionFieldIds } from 'src/engine/metadata-modules/role/utils/build-resolve-morph-relation-permission-field-ids.util';
+import { computeObjectsPermissionsForRoleDefinition } from 'src/engine/permissions/role/utils/compute-objects-permissions-for-role-definition.util';
+import {
+ PermissionsException,
+ PermissionsExceptionCode,
+} from 'src/engine/permissions/permissions.exception';
+import { type PermissionScope } from 'src/engine/permissions/principal/types/permission-scope.type';
+
+// a flag decides objects such as workflows regardless of their object permission, so a scope's explicit deny is applied after
+const narrowObjectsPermissionsToExplicitDenies = ({
+ objectsPermissions,
+ objectPermissions,
+}: {
+ objectsPermissions: ObjectsPermissions;
+ objectPermissions: (Omit<
+ AiRunScopeObjectPermission,
+ 'objectUniversalIdentifier'
+ > & {
+ objectMetadataId: string;
+ })[];
+}): ObjectsPermissions =>
+ objectPermissions.reduce(
+ (narrowedObjectsPermissions, { objectMetadataId, ...objectPermission }) => {
+ const grantedObjectPermissions =
+ narrowedObjectsPermissions[objectMetadataId];
+
+ if (!isDefined(grantedObjectPermissions)) {
+ return narrowedObjectsPermissions;
+ }
+
+ return {
+ ...narrowedObjectsPermissions,
+ [objectMetadataId]: {
+ ...grantedObjectPermissions,
+ ...Object.fromEntries(
+ OBJECT_PERMISSION_ACTIONS.map((action) => [
+ action,
+ grantedObjectPermissions[action] &&
+ objectPermission[action] !== false,
+ ]),
+ ),
+ },
+ };
+ },
+ objectsPermissions,
+ );
+
+export const resolveAiRunPermissionScope = ({
+ scope,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+}: {
+ scope: AiRunScope;
+ flatObjectMetadataMaps: Pick<
+ FlatEntityMaps<FlatObjectMetadata>,
+ 'byUniversalIdentifier'
+ >;
+ flatFieldMetadataMaps: Pick<
+ FlatEntityMaps<FlatFieldMetadata>,
+ 'byUniversalIdentifier'
+ >;
+}): PermissionScope => {
+ if (hasAiRunScopeRepeatedEntries(scope)) {
+ throw new PermissionsException(
+ 'An AI run scope lists an object or field more than once',
+ PermissionsExceptionCode.INVALID_ARG,
+ );
+ }
+
+ // a dropped entry could be a deny, so one naming metadata the workspace lacks fails the run
+ const findObjectMetadataIdOrThrow = (objectUniversalIdentifier: string) => {
+ const objectMetadataId =
+ flatObjectMetadataMaps.byUniversalIdentifier[objectUniversalIdentifier]
+ ?.id;
+
+ if (!isDefined(objectMetadataId)) {
+ throw new PermissionsException(
+ `Object ${objectUniversalIdentifier} in an AI run scope does not exist`,
+ PermissionsExceptionCode.INVALID_ARG,
+ );
+ }
+
+ return objectMetadataId;
+ };
+
+ const isPermissionFlagGranted = buildIsPermissionFlagGranted({
+ role: {
+ canUpdateAllSettings: scope.canUpdateAllSettings ?? false,
+ canAccessAllTools: scope.canAccessAllTools ?? false,
+ },
+ permissionFlagUniversalIdentifiers:
+ scope.permissionFlagUniversalIdentifiers ?? [],
+ });
+
+ const objectPermissions = (scope.objectPermissions ?? []).map(
+ ({ objectUniversalIdentifier, ...objectPermission }) => ({
+ ...objectPermission,
+ objectMetadataId: findObjectMetadataIdOrThrow(objectUniversalIdentifier),
+ }),
+ );
+
+ const flatFieldMetadatas = Object.values(
+ flatFieldMetadataMaps.byUniversalIdentifier,
+ ).filter(isDefined);
+
+ const flagGrantedObjectsPermissions =
+ computeObjectsPermissionsForRoleDefinition({
+ roleDefinition: {
+ canReadAllObjectRecords: scope.canReadAllObjectRecords ?? false,
+ canUpdateAllObjectRecords: scope.canUpdateAllObjectRecords ?? false,
+ canSoftDeleteAllObjectRecords:
+ scope.canSoftDeleteAllObjectRecords ?? false,
+ canDestroyAllObjectRecords: scope.canDestroyAllObjectRecords ?? false,
+ isPermissionFlagGranted,
+ areSystemObjectsReadOnlyByDefault: true,
+ objectPermissions,
+ fieldPermissions: (scope.fieldPermissions ?? []).flatMap(
+ ({
+ objectUniversalIdentifier,
+ fieldUniversalIdentifier,
+ ...fieldPermission
+ }) => {
+ const objectMetadataId = findObjectMetadataIdOrThrow(
+ objectUniversalIdentifier,
+ );
+ const flatFieldMetadata =
+ flatFieldMetadataMaps.byUniversalIdentifier[
+ fieldUniversalIdentifier
+ ];
+
+ if (!isDefined(flatFieldMetadata)) {
+ throw new PermissionsException(
+ `Field ${fieldUniversalIdentifier} in an AI run scope does not exist`,
+ PermissionsExceptionCode.INVALID_ARG,
+ );
+ }
+
+ // attached to the named object, the restriction would miss the field's own
+ if (flatFieldMetadata.objectMetadataId !== objectMetadataId) {
+ throw new PermissionsException(
+ `Field ${fieldUniversalIdentifier} does not belong to object ${objectUniversalIdentifier} in an AI run scope`,
+ PermissionsExceptionCode.INVALID_ARG,
+ );
+ }
+
+ return [
+ {
+ ...fieldPermission,
+ objectMetadataId,
+ fieldMetadataId: flatFieldMetadata.id,
+ },
+ ];
+ },
+ ),
+ rowLevelPermissionPredicates: [],
+ rowLevelPermissionPredicateGroups: [],
+ },
+ objectMetadataCollection: Object.values(
+ flatObjectMetadataMaps.byUniversalIdentifier,
+ ).filter(isDefined),
+ resolveMorphRelationPermissionFieldIds:
+ buildResolveMorphRelationPermissionFieldIds(
+ flatFieldMetadatas.filter(
+ (flatFieldMetadata) =>
+ flatFieldMetadata.type === FieldMetadataType.MORPH_RELATION,
+ ),
+ ),
+ });
+
+ return {
+ objectsPermissions: narrowObjectsPermissionsToExplicitDenies({
+ objectsPermissions: flagGrantedObjectsPermissions,
+ objectPermissions,
+ }),
+ permissionFlags: Object.fromEntries(
+ Object.values(PermissionFlagType).map((permissionFlag) => [
+ permissionFlag,
+ isPermissionFlagGranted(permissionFlag),
+ ]),
+ ),
+ };
+};
diff --git a/packages/twenty-server/src/engine/permissions/role/utils/restrict-objects-permissions-to-scope.util.ts b/packages/twenty-server/src/engine/permissions/role/utils/restrict-objects-permissions-to-scope.util.ts
new file mode 100644
index 00000000000..6b23e6b43fe
--- /dev/null
+++ b/packages/twenty-server/src/engine/permissions/role/utils/restrict-objects-permissions-to-scope.util.ts
@@ -0,0 +1,41 @@
+import { type ObjectsPermissions } from 'twenty-shared/types';
+
+import { type PermissionScope } from 'src/engine/permissions/principal/types/permission-scope.type';
+import { computePermissionIntersection } from 'src/engine/permissions/role/utils/compute-permission-intersection.util';
+
+// the roles' predicates keep their insert-guard field exemption, except on fields the scope denies writing
+export const restrictObjectsPermissionsToScope = ({
+ objectsPermissions,
+ scope,
+}: {
+ objectsPermissions: ObjectsPermissions;
+ scope: Pick<PermissionScope, 'objectsPermissions'>;
+}): ObjectsPermissions => {
+ const intersectedObjectsPermissions = computePermissionIntersection([
+ objectsPermissions,
+ scope.objectsPermissions,
+ ]);
+
+ return Object.fromEntries(
+ Object.entries(objectsPermissions).map(
+ ([objectMetadataId, objectPermissions]) => {
+ const scopeRestrictedFields =
+ scope.objectsPermissions[objectMetadataId]?.restrictedFields ?? {};
+
+ return [
+ objectMetadataId,
+ {
+ ...intersectedObjectsPermissions[objectMetadataId],
+ rowLevelPermissionPredicates:
+ objectPermissions.rowLevelPermissionPredicates.filter(
+ ({ fieldMetadataId }) =>
+ scopeRestrictedFields[fieldMetadataId]?.canUpdate !== false,
+ ),
+ rowLevelPermissionPredicateGroups:
+ objectPermissions.rowLevelPermissionPredicateGroups,
+ },
+ ];
+ },
+ ),
+ );
+};
diff --git a/packages/twenty-server/src/engine/subscriptions/subscription.service.ts b/packages/twenty-server/src/engine/subscriptions/subscription.service.ts
index abeeef62cb9..b0b07e7e166 100644
--- a/packages/twenty-server/src/engine/subscriptions/subscription.service.ts
+++ b/packages/twenty-server/src/engine/subscriptions/subscription.service.ts
@@ -5,6 +5,7 @@ import { isDefined } from 'twenty-shared/utils';
import { RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';
import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
import { filterMapAsyncIterator } from 'src/engine/subscriptions/utils/filter-map-async-iterator';
+import { subscribeToChannel } from 'src/engine/subscriptions/utils/subscribe-to-channel';
@Injectable()
export class SubscriptionService {
@@ -108,18 +109,17 @@ export class SubscriptionService {
return `${SubscriptionChannel.AGENT_CHAT_CHANNEL}:${workspaceId}:${threadId}`;
}
- async subscribeToAgentChat({
+ async subscribeToAgentChat<TPayload>({
workspaceId,
threadId,
}: {
workspaceId: string;
threadId: string;
}) {
- const client = this.redisClient.getPubSubClient();
-
- return client.asyncIterator(
- this.getAgentChatChannel({ workspaceId, threadId }),
- );
+ return subscribeToChannel<TPayload>({
+ pubSub: this.redisClient.getPubSubClient(),
+ channel: this.getAgentChatChannel({ workspaceId, threadId }),
+ });
}
async publishToAgentChat<T>({
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/__tests__/filter-map-async-iterator.spec.ts b/packages/twenty-server/src/engine/subscriptions/utils/__tests__/filter-map-async-iterator.spec.ts
index 2ae9a32763e..5b6358c81ee 100644
--- a/packages/twenty-server/src/engine/subscriptions/utils/__tests__/filter-map-async-iterator.spec.ts
+++ b/packages/twenty-server/src/engine/subscriptions/utils/__tests__/filter-map-async-iterator.spec.ts
@@ -19,6 +19,36 @@ describe('filterMapAsyncIterator', () => {
expect(values).toEqual([10, 30]);
});
+ it('awaits an async mapper, skipping values it resolves to undefined', async () => {
+ const stream = filterMapAsyncIterator<number>(
+ (async function* () {
+ yield 1;
+ yield 2;
+ yield 3;
+ })(),
+ async (value) => (value === 2 ? undefined : value * 10),
+ );
+ const values = [];
+
+ for await (const value of stream) {
+ values.push(value);
+ }
+
+ expect(values).toEqual([10, 30]);
+ });
+
+ it('rejects the read when an async mapper rejects', async () => {
+ const mapperError = new Error('Thread not readable');
+ const stream = filterMapAsyncIterator<number>(
+ (async function* () {
+ yield 1;
+ })(),
+ () => Promise.reject(mapperError),
+ );
+
+ await expect(stream.next()).rejects.toBe(mapperError);
+ });
+
it('closes the source while a read is pending', async () => {
const sourceReturn = jest
.fn()
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/__tests__/subscribe-to-channel.spec.ts b/packages/twenty-server/src/engine/subscriptions/utils/__tests__/subscribe-to-channel.spec.ts
new file mode 100644
index 00000000000..8ba2544bf7d
--- /dev/null
+++ b/packages/twenty-server/src/engine/subscriptions/utils/__tests__/subscribe-to-channel.spec.ts
@@ -0,0 +1,109 @@
+import { subscribeToChannel } from 'src/engine/subscriptions/utils/subscribe-to-channel';
+
+const buildPubSub = () => {
+ let deliver: (payload: string) => void = () => {};
+ let resolveSubscribed: (subscriptionId: number) => void = () => {};
+ const pubSub = {
+ subscribe: jest.fn(
+ (_channel: string, onMessage: (payload: string) => void) => {
+ deliver = onMessage;
+
+ return new Promise<number>((resolve) => {
+ resolveSubscribed = resolve;
+ });
+ },
+ ),
+ unsubscribe: jest.fn(),
+ };
+
+ return {
+ pubSub,
+ deliver: (payload: string) => deliver(payload),
+ acknowledgeSubscription: () => resolveSubscribed(7),
+ };
+};
+
+describe('subscribeToChannel', () => {
+ it('resolves only once the channel is subscribed', async () => {
+ const { pubSub, acknowledgeSubscription } = buildPubSub();
+ let isResolved = false;
+
+ const subscription = subscribeToChannel<string>({
+ pubSub: pubSub as never,
+ channel: 'channel',
+ }).then((iterator) => {
+ isResolved = true;
+
+ return iterator;
+ });
+
+ await Promise.resolve();
+ expect(pubSub.subscribe).toHaveBeenCalledWith(
+ 'channel',
+ expect.any(Function),
+ );
+ expect(isResolved).toBe(false);
+
+ acknowledgeSubscription();
+ await subscription;
+ expect(isResolved).toBe(true);
+ });
+
+ it('keeps what is published before it is read, in order', async () => {
+ const { pubSub, deliver, acknowledgeSubscription } = buildPubSub();
+ const subscription = subscribeToChannel<string>({
+ pubSub: pubSub as never,
+ channel: 'channel',
+ });
+
+ acknowledgeSubscription();
+
+ const iterator = await subscription;
+
+ deliver('first');
+ deliver('second');
+
+ await expect(iterator.next()).resolves.toEqual({
+ done: false,
+ value: 'first',
+ });
+ await expect(iterator.next()).resolves.toEqual({
+ done: false,
+ value: 'second',
+ });
+
+ const pendingRead = iterator.next();
+
+ deliver('third');
+ await expect(pendingRead).resolves.toEqual({
+ done: false,
+ value: 'third',
+ });
+ });
+
+ it('unsubscribes and ends a pending read on return', async () => {
+ const { pubSub, acknowledgeSubscription } = buildPubSub();
+ const subscription = subscribeToChannel<string>({
+ pubSub: pubSub as never,
+ channel: 'channel',
+ });
+
+ acknowledgeSubscription();
+
+ const iterator = await subscription;
+ const pendingRead = iterator.next();
+
+ await iterator.return?.();
+
+ await expect(pendingRead).resolves.toEqual({
+ done: true,
+ value: undefined,
+ });
+ await expect(iterator.next()).resolves.toEqual({
+ done: true,
+ value: undefined,
+ });
+ expect(pubSub.unsubscribe).toHaveBeenCalledTimes(1);
+ expect(pubSub.unsubscribe).toHaveBeenCalledWith(7);
+ });
+});
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/filter-map-async-iterator.ts b/packages/twenty-server/src/engine/subscriptions/utils/filter-map-async-iterator.ts
index c479e2de751..d98b24fb051 100644
--- a/packages/twenty-server/src/engine/subscriptions/utils/filter-map-async-iterator.ts
+++ b/packages/twenty-server/src/engine/subscriptions/utils/filter-map-async-iterator.ts
@@ -4,7 +4,7 @@ import { isDefined } from 'twenty-shared/utils';
// closed subscription would keep its pub/sub listener until the next message.
export const filterMapAsyncIterator = <TValue>(
iterator: AsyncIterator<TValue>,
- mapValue: (value: TValue) => TValue | undefined,
+ mapValue: (value: TValue) => TValue | undefined | Promise<TValue | undefined>,
): AsyncIterableIterator<TValue> => ({
next: async () => {
while (true) {
@@ -14,7 +14,7 @@ export const filterMapAsyncIterator = <TValue>(
return result;
}
- const mappedValue = mapValue(result.value);
+ const mappedValue = await mapValue(result.value);
if (isDefined(mappedValue)) {
return { done: false, value: mappedValue };
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/subscribe-to-channel.ts b/packages/twenty-server/src/engine/subscriptions/utils/subscribe-to-channel.ts
new file mode 100644
index 00000000000..47d62a98db5
--- /dev/null
+++ b/packages/twenty-server/src/engine/subscriptions/utils/subscribe-to-channel.ts
@@ -0,0 +1,70 @@
+import { type RedisPubSub } from 'graphql-redis-subscriptions';
+import { isDefined } from 'twenty-shared/utils';
+
+// subscribed once it resolves, unlike RedisPubSub's asyncIterator, which subscribes on its first read
+export const subscribeToChannel = async <TPayload>({
+ pubSub,
+ channel,
+}: {
+ pubSub: Pick<RedisPubSub, 'subscribe' | 'unsubscribe'>;
+ channel: string;
+}): Promise<AsyncIterableIterator<TPayload>> => {
+ const receivedResults: IteratorResult<TPayload>[] = [];
+ const pendingReads: ((result: IteratorResult<TPayload>) => void)[] = [];
+ let isClosed = false;
+
+ const subscriptionId = await pubSub.subscribe<TPayload>(
+ channel,
+ (payload) => {
+ const pendingRead = pendingReads.shift();
+
+ if (isDefined(pendingRead)) {
+ pendingRead({ done: false, value: payload });
+
+ return;
+ }
+
+ receivedResults.push({ done: false, value: payload });
+ },
+ );
+
+ const close = async (): Promise<IteratorResult<TPayload>> => {
+ if (!isClosed) {
+ isClosed = true;
+ pubSub.unsubscribe(subscriptionId);
+ receivedResults.length = 0;
+ pendingReads
+ .splice(0)
+ .forEach((pendingRead) =>
+ pendingRead({ done: true, value: undefined }),
+ );
+ }
+
+ return { done: true, value: undefined };
+ };
+
+ return {
+ next: () => {
+ if (isClosed) {
+ return close();
+ }
+
+ const receivedResult = receivedResults.shift();
+
+ if (isDefined(receivedResult)) {
+ return Promise.resolve(receivedResult);
+ }
+
+ return new Promise((resolve) => pendingReads.push(resolve));
+ },
+ return: close,
+ throw: async (error: unknown) => {
+ await close();
+
+ throw error;
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index f687b665a73..25b7773cc55 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -305,7 +305,10 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
workflowRunId,
stepId: step.id,
}),
- runSpec: buildWorkflowAgentRunSpec({ step }),
+ runSpec: buildWorkflowAgentRunSpec({
+ step,
+ applicationId,
+ }),
summary: null,
continuationCount: 0,
},
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-turn-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-turn-standard-flat-field-metadata.util.ts
index 14e6d6844c2..f2cb09ec959 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-turn-standard-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-turn-standard-flat-field-metadata.util.ts
@@ -440,7 +440,8 @@ export const buildAgentTurnStandardFlatFieldMetadatas = (
),
icon: 'IconRelationOneToMany',
isUIEditable: false,
- isNullable: false,
+ // a one-shot AI call records its turn without a conversation
+ isNullable: true,
targetObjectName: 'agentChatThread',
targetFieldName: 'turns',
morphId: null,
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-draft.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-draft.service.ts
index cc16e17150d..a9b0de71bb5 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-draft.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-draft.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, type Type } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import { MessageCampaignStatus } from 'twenty-shared/types';
import {
@@ -8,24 +8,22 @@ import {
isDefined,
parseEmailDocument,
} from 'twenty-shared/utils';
-import { type ObjectLiteral } from 'typeorm';
import { v4 } from 'uuid';
import {
EmailingDomainException,
EmailingDomainExceptionCode,
} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
-import { UserRoleService } from 'src/engine/permissions/role-assignment/user-role.service';
+import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
import { collectCampaignVariableNamesOrThrow } from 'src/modules/emailing/utils/collect-campaign-variable-names-or-throw.util';
import { collectCampaignVariableNamesFromStringOrThrow } from 'src/modules/emailing/utils/collect-campaign-variable-names-from-string-or-throw.util';
-import { buildEmailingRolePermissionConfig } from 'src/modules/emailing/utils/build-emailing-role-permission-config.util';
export type SaveDraftCampaignArgs = {
workspaceId: string;
- userWorkspaceId: string;
+ rolePermissionConfig: RolePermissionConfig;
campaignId?: string;
name?: string;
subject?: string;
@@ -45,24 +43,13 @@ const DEFAULT_CAMPAIGN_NAME = 'Untitled campaign';
@Injectable()
export class MessageCampaignDraftService {
constructor(
- private readonly userRoleService: UserRoleService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly campaignVariableService: CampaignVariableService,
) {}
- private getRoleScopedRepository<T extends ObjectLiteral>(
- entity: Type<T>,
- roleId: string,
- ) {
- return this.workspaceOrmManager.getRepository(
- entity,
- buildEmailingRolePermissionConfig(roleId),
- );
- }
-
async saveDraft({
workspaceId,
- userWorkspaceId,
+ rolePermissionConfig,
campaignId,
name,
subject,
@@ -90,15 +77,10 @@ export class MessageCampaignDraftService {
);
}
- const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
- workspaceId,
- userWorkspaceId,
- });
-
return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const campaignRepository = await this.getRoleScopedRepository(
+ const campaignRepository = this.workspaceOrmManager.getRepository(
MessageCampaignWorkspaceEntity,
- roleId,
+ rolePermissionConfig,
);
if (!isDefined(campaignId)) {
diff --git a/packages/twenty-server/src/modules/emailing/tools/__tests__/save-campaign-tool.spec.ts b/packages/twenty-server/src/modules/emailing/tools/__tests__/save-campaign-tool.spec.ts
index b1fcac517da..c4b8c9c280d 100644
--- a/packages/twenty-server/src/modules/emailing/tools/__tests__/save-campaign-tool.spec.ts
+++ b/packages/twenty-server/src/modules/emailing/tools/__tests__/save-campaign-tool.spec.ts
@@ -5,6 +5,7 @@ import {
EmailingDomainExceptionCode,
} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
import { toToolJsonSchema } from 'src/engine/core-modules/record-crud/utils/to-tool-json-schema.util';
+import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
import { MessageCampaignDraftService } from 'src/modules/emailing/services/message-campaign-draft.service';
import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool';
import { SaveCampaignToolInputZodSchema } from 'src/modules/emailing/tools/save-campaign-tool.schema';
@@ -14,6 +15,15 @@ describe('SaveCampaignTool', () => {
let saveDraft: jest.Mock;
const campaignId = '20202020-0000-4000-8000-000000000001';
+ const scopedRolePermissionConfig: RolePermissionConfig = {
+ intersectionOf: { userWorkspaceRoleId: 'member-role-id' },
+ scope: { objectsPermissions: {}, permissionFlags: {} },
+ };
+ const memberContext = {
+ workspaceId: 'workspace-1',
+ userWorkspaceId: 'user-workspace-1',
+ rolePermissionConfig: scopedRolePermissionConfig,
+ };
beforeEach(async () => {
saveDraft = jest.fn().mockResolvedValue({
@@ -44,7 +54,7 @@ describe('SaveCampaignTool', () => {
it('should edit a campaign and reference the record', async () => {
const output = await tool.execute(
{ campaignId, body: { type: 'doc', content: [] } },
- { workspaceId: 'workspace-1', userWorkspaceId: 'user-workspace-1' },
+ memberContext,
);
expect(output.success).toBe(true);
@@ -58,7 +68,7 @@ describe('SaveCampaignTool', () => {
]);
expect(saveDraft).toHaveBeenCalledWith({
workspaceId: 'workspace-1',
- userWorkspaceId: 'user-workspace-1',
+ rolePermissionConfig: scopedRolePermissionConfig,
campaignId,
name: undefined,
subject: undefined,
@@ -76,7 +86,7 @@ describe('SaveCampaignTool', () => {
const output = await tool.execute(
{ name: 'Launch announcement' },
- { workspaceId: 'workspace-1', userWorkspaceId: 'user-workspace-1' },
+ memberContext,
);
expect(output.success).toBe(true);
@@ -93,6 +103,16 @@ describe('SaveCampaignTool', () => {
expect(saveDraft).not.toHaveBeenCalled();
});
+ it('should refuse to run without the permissions it was given', async () => {
+ const output = await tool.execute(
+ { name: 'Launch announcement' },
+ { workspaceId: 'workspace-1', userWorkspaceId: 'user-workspace-1' },
+ );
+
+ expect(output.success).toBe(false);
+ expect(saveDraft).not.toHaveBeenCalled();
+ });
+
it('should expose an input schema convertible to JSON schema for the LLM', () => {
const jsonSchema = toToolJsonSchema(SaveCampaignToolInputZodSchema) as {
properties?: Record<string, unknown>;
@@ -117,7 +137,7 @@ describe('SaveCampaignTool', () => {
const output = await tool.execute(
{ campaignId, subject: 'New subject' },
- { workspaceId: 'workspace-1', userWorkspaceId: 'user-workspace-1' },
+ memberContext,
);
expect(output).toEqual({
diff --git a/packages/twenty-server/src/modules/emailing/tools/save-campaign-tool.ts b/packages/twenty-server/src/modules/emailing/tools/save-campaign-tool.ts
index 25c2f8d9b24..6dfe2496d1b 100644
--- a/packages/twenty-server/src/modules/emailing/tools/save-campaign-tool.ts
+++ b/packages/twenty-server/src/modules/emailing/tools/save-campaign-tool.ts
@@ -31,7 +31,10 @@ export class SaveCampaignTool implements Tool {
parameters: SaveCampaignToolInput,
context: ToolExecutionContext,
): Promise<ToolOutput> {
- if (!isDefined(context.userWorkspaceId)) {
+ if (
+ !isDefined(context.userWorkspaceId) ||
+ !isDefined(context.rolePermissionConfig)
+ ) {
return {
success: false,
message: 'Failed to save campaign',
@@ -42,7 +45,7 @@ export class SaveCampaignTool implements Tool {
try {
const result = await this.messageCampaignDraftService.saveDraft({
workspaceId: context.workspaceId,
- userWorkspaceId: context.userWorkspaceId,
+ rolePermissionConfig: context.rolePermissionConfig,
campaignId: parameters.campaignId,
name: parameters.name,
subject: parameters.subject,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-ai-agent-step.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-ai-agent-step.util.spec.ts
new file mode 100644
index 00000000000..6177b418640
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-ai-agent-step.util.spec.ts
@@ -0,0 +1,100 @@
+import { validateWorkflowAiAgentStep } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util';
+import { type WorkflowAiAgentActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type';
+
+const errorCodesFor = ({ input }: { input: WorkflowAiAgentActionInput }) =>
+ validateWorkflowAiAgentStep({
+ step: {
+ id: 'step-1',
+ name: 'Qualify',
+ settings: { outputSchema: {}, input },
+ },
+ })
+ .filter(({ severity }) => severity === 'error')
+ .map(({ code }) => code);
+
+describe('validateWorkflowAiAgentStep', () => {
+ it('accepts a step running an agent', () => {
+ expect(errorCodesFor({ input: { agentId: 'agent-id' } })).toEqual([]);
+ });
+
+ it('accepts a step with its own instructions and a prompt', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ instructions: 'Qualify the lead.',
+ prompt: 'Qualify {{trigger.name}}',
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('refuses a step without an agent or a prompt', () => {
+ expect(
+ errorCodesFor({
+ input: { instructions: 'Qualify the lead.', prompt: ' ' },
+ }),
+ ).toEqual(['AI_AGENT_MISSING_PROMPT']);
+ });
+
+ it('refuses a step running an agent with its own config', () => {
+ expect(
+ errorCodesFor({ input: { agentId: 'agent-id', modelId: 'model-id' } }),
+ ).toEqual(['AI_AGENT_CONFLICTING_CONFIG']);
+ });
+
+ it('refuses a step without an agent that asks humans for input', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ prompt: 'Qualify {{trigger.name}}',
+ humanInputInstructions: 'Ask before choosing a plan.',
+ },
+ }),
+ ).toEqual(['AI_AGENT_CONFLICTING_CONFIG']);
+ });
+
+ it('refuses a step without an agent that keeps a conversation', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ prompt: 'Qualify {{trigger.name}}',
+ conversation: { scope: 'RUN' },
+ },
+ }),
+ ).toEqual(['AI_AGENT_CONFLICTING_CONFIG']);
+ });
+
+ it('ignores blank human input instructions on a step without an agent', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ prompt: 'Qualify {{trigger.name}}',
+ humanInputInstructions: ' ',
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('accepts human input instructions and a conversation on a step running an agent', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ agentId: 'agent-id',
+ humanInputInstructions: 'Ask before choosing a plan.',
+ conversation: { scope: 'KEY', key: 'lead' },
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('accepts a response format on a step running an agent', () => {
+ expect(
+ errorCodesFor({
+ input: {
+ agentId: 'agent-id',
+ responseFormat: { type: 'text' },
+ },
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util.ts
index 812aec76315..8ded073028e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util.ts
@@ -1,19 +1,43 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-import { type WorkflowValidationIssue } from 'twenty-shared/workflow';
+import {
+ getWorkflowAiAgentStepConfigIssues,
+ isWorkflowAiAgentGenerateStep,
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES,
+ type WorkflowValidationIssue,
+} from 'twenty-shared/workflow';
import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-export const validateWorkflowAiAgentStep = (
- step: WorkflowAiAgentAction,
-): WorkflowValidationIssue[] => {
+export const validateWorkflowAiAgentStep = ({
+ step,
+}: {
+ step: Pick<WorkflowAiAgentAction, 'id' | 'name'> & {
+ settings: Pick<WorkflowAiAgentAction['settings'], 'input' | 'outputSchema'>;
+ };
+}): WorkflowValidationIssue[] => {
const issues: WorkflowValidationIssue[] = [];
- if (!isNonEmptyString(step.settings?.input?.agentId)) {
+ const input = step.settings?.input ?? {};
+ const stepLabel = step.name ?? step.id;
+
+ for (const issueCode of getWorkflowAiAgentStepConfigIssues(input)) {
+ issues.push({
+ severity: 'error',
+ code: 'AI_AGENT_CONFLICTING_CONFIG',
+ message: `AI step "${stepLabel}": ${WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES[issueCode]}`,
+ stepId: step.id,
+ });
+ }
+
+ if (
+ isWorkflowAiAgentGenerateStep(input) &&
+ !isNonEmptyString(input.prompt?.trim())
+ ) {
issues.push({
severity: 'error',
- code: 'AI_AGENT_MISSING_AGENT',
- message: `Agent step "${step.name ?? step.id}" has no agent selected.`,
+ code: 'AI_AGENT_MISSING_PROMPT',
+ message: `AI step "${stepLabel}" has no prompt.`,
stepId: step.id,
});
}
@@ -26,7 +50,7 @@ export const validateWorkflowAiAgentStep = (
issues.push({
severity: 'warning',
code: 'AI_AGENT_MISSING_OUTPUT_VARIABLE',
- message: `Agent step "${step.name ?? step.id}" has no output variable defined. Downstream steps won't be able to reference its result.`,
+ message: `AI step "${stepLabel}" has no output variable defined. Downstream steps won't be able to reference its result.`,
stepId: step.id,
});
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
index 55dc367c9de..6da4edda135 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
@@ -74,7 +74,7 @@ export class WorkflowVersionValidationWorkspaceService {
const stepTypeIssues = steps.flatMap((step) => {
if (step.type === WorkflowActionType.AI_AGENT) {
return [
- ...validateWorkflowAiAgentStep(step),
+ ...validateWorkflowAiAgentStep({ step }),
...validateWorkflowConversationStep(step),
];
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service.ts
new file mode 100644
index 00000000000..3599a9d6c45
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service.ts
@@ -0,0 +1,61 @@
+import { Injectable } from '@nestjs/common';
+
+import { msg } from '@lingui/core/macro';
+import { isAgentRunnableAsWorkflowStep } from 'twenty-shared/workflow';
+
+import { AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent.service';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { type FlatAgentWithRoleId } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';
+import {
+ WorkflowVersionStepException,
+ WorkflowVersionStepExceptionCode,
+} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';
+
+@Injectable()
+export class WorkflowAiAgentStepAgentService {
+ constructor(private readonly agentService: AgentService) {}
+
+ async findAgentRunnableByNewStepOrThrow({
+ agentId,
+ workspaceId,
+ }: {
+ agentId: string;
+ workspaceId: string;
+ }): Promise<FlatAgentWithRoleId> {
+ const agent = await this.agentService
+ .findOneAgentById({ id: agentId, workspaceId })
+ .catch((error) => {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.AGENT_NOT_FOUND
+ ) {
+ throw new WorkflowVersionStepException(
+ `Agent "${agentId}" not found. Run an existing agent, or give the step its own instructions.`,
+ WorkflowVersionStepExceptionCode.NOT_FOUND,
+ {
+ userFriendlyMessage: msg`The agent this step should run was not found.`,
+ },
+ );
+ }
+
+ throw error;
+ });
+
+ if (!isAgentRunnableAsWorkflowStep(agent)) {
+ const { label } = agent;
+
+ throw new WorkflowVersionStepException(
+ `Agent "${label}" is archived or belongs to another workflow step, so a new step cannot run it. Run an active agent, or give the step its own instructions.`,
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ {
+ userFriendlyMessage: msg`Agent "${label}" is archived or belongs to another workflow step, so a new step cannot run it.`,
+ },
+ );
+ }
+
+ return agent;
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/utils/is-workflow-ai-agent-step-kind-changed.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/utils/is-workflow-ai-agent-step-kind-changed.util.ts
new file mode 100644
index 00000000000..28c82187214
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/utils/is-workflow-ai-agent-step-kind-changed.util.ts
@@ -0,0 +1,22 @@
+import {
+ isWorkflowAiAgentGenerateStep,
+ WorkflowActionType,
+} from 'twenty-shared/workflow';
+
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const getAiAgentStepAgentId = (step: WorkflowAction): string | undefined =>
+ step.type === WorkflowActionType.AI_AGENT &&
+ !isWorkflowAiAgentGenerateStep(step.settings.input)
+ ? step.settings.input.agentId
+ : undefined;
+
+export const isWorkflowAiAgentStepKindChanged = ({
+ existingStep,
+ updatedStep,
+}: {
+ existingStep: WorkflowAction;
+ updatedStep: WorkflowAction;
+}): boolean =>
+ existingStep.type === updatedStep.type &&
+ getAiAgentStepAgentId(existingStep) !== getAiAgentStepAgentId(updatedStep);
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
index 01e6fa44466..5b04625a170 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
@@ -1,17 +1,18 @@
import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
-import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
+import { isNonEmptyString } from '@sniptt/guards';
import { inputSchemaToOutputSchema } from 'twenty-shared/logic-function';
import {
FieldMetadataType,
StepLogicalOperator,
ViewFilterOperand,
} from 'twenty-shared/types';
-import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import { isDefined, isPlainObject, isValidUuid } from 'twenty-shared/utils';
import {
IF_ELSE_BRANCH_POSITION_OFFSETS,
WORKFLOW_ACTION_FEATURE_FLAGS,
+ WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME,
WorkflowActionType,
getFunctionInputFromInputSchema,
type StepIfElseBranch,
@@ -23,8 +24,6 @@ import { FindRecordsService } from 'src/engine/core-modules/record-crud/services
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { type WorkflowStepPositionInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-step-position.input';
import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
-import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';
-import { AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent.service';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import {
LogicFunctionException,
@@ -33,7 +32,6 @@ import {
import { LogicFunctionFromSourceService } from 'src/engine/metadata-modules/logic-function/services/logic-function-from-source.service';
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -46,6 +44,7 @@ import {
import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';
import { type OutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/types/output-schema.type';
import { CodeStepBuildService } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/services/code-step-build.service';
+import { WorkflowAiAgentStepAgentService } from 'src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service';
import { type WorkflowExecutionContext } from 'src/modules/workflow/workflow-executor/types/workflow-execution-context.type';
import { type BaseWorkflowActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type';
import {
@@ -78,18 +77,15 @@ export class WorkflowVersionStepOperationsWorkspaceService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly logicFunctionFromSourceService: LogicFunctionFromSourceService,
private readonly codeStepBuildService: CodeStepBuildService,
- private readonly agentService: AgentService,
- @InjectWorkspaceScopedRepository(RoleTargetEntity)
- private readonly roleTargetRepository: WorkspaceScopedRepository<RoleTargetEntity>,
@InjectWorkspaceScopedRepository(ObjectMetadataEntity)
private readonly objectMetadataRepository: WorkspaceScopedRepository<ObjectMetadataEntity>,
private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,
- private readonly aiAgentRoleService: AiAgentRoleService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
private readonly findRecordsService: FindRecordsService,
private readonly featureFlagService: FeatureFlagService,
+ private readonly workflowAiAgentStepAgentService: WorkflowAiAgentStepAgentService,
) {}
async runWorkflowVersionStepDeletionSideEffects({
@@ -122,34 +118,6 @@ export class WorkflowVersionStepOperationsWorkspaceService {
});
break;
}
- case WorkflowActionType.AI_AGENT: {
- if (!isDefined(step.settings.input.agentId)) {
- break;
- }
-
- const roleTarget = await this.roleTargetRepository.findOne(
- workspaceId,
- {
- where: {
- agentId: step.settings.input.agentId,
- },
- },
- );
-
- await this.agentService.deleteManyAgents({
- ids: [step.settings.input.agentId],
- workspaceId,
- });
-
- if (isDefined(roleTarget?.roleId) && isDefined(roleTarget?.id)) {
- await this.aiAgentRoleService.deleteAgentOnlyRoleIfUnused({
- roleId: roleTarget.roleId,
- roleTargetId: roleTarget.id,
- workspaceId,
- });
- }
- break;
- }
}
}
@@ -556,29 +524,42 @@ export class WorkflowVersionStepOperationsWorkspaceService {
};
}
case WorkflowActionType.AI_AGENT: {
- const newAgent = await this.agentService.createOneAgent(
- {
- label: 'Workflow Agent ' + baseStep.id.substring(0, 4),
- icon: 'IconLego',
- description: '',
- prompt:
- 'You are a helpful AI assistant. Complete the task based on the workflow context.',
- modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
- responseFormat: { type: 'text' },
- isSystem: true,
- },
- workspaceId,
- );
+ const defaultAgentInput = defaultSettings?.input;
+ const defaultAgentId = isPlainObject(defaultAgentInput)
+ ? defaultAgentInput.agentId
+ : undefined;
+
+ if (isNonEmptyString(defaultAgentId)) {
+ const agent =
+ await this.workflowAiAgentStepAgentService.findAgentRunnableByNewStepOrThrow(
+ { agentId: defaultAgentId, workspaceId },
+ );
+
+ return {
+ builtStep: {
+ ...baseStep,
+ name: agent.label,
+ type: WorkflowActionType.AI_AGENT,
+ settings: {
+ ...BASE_STEP_DEFINITION,
+ input: {
+ agentId: agent.id,
+ prompt: '',
+ },
+ },
+ },
+ };
+ }
return {
builtStep: {
...baseStep,
- name: 'Agent',
+ name: WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME,
type: WorkflowActionType.AI_AGENT,
settings: {
...BASE_STEP_DEFINITION,
input: {
- agentId: newAgent.id,
+ instructions: '',
prompt: '',
},
},
@@ -926,38 +907,6 @@ export class WorkflowVersionStepOperationsWorkspaceService {
},
};
}
- case WorkflowActionType.AI_AGENT: {
- const agentId = step.settings.input.agentId;
-
- if (!isDefined(agentId)) {
- throw new WorkflowVersionStepException(
- 'Agent ID is required for cloning',
- WorkflowVersionStepExceptionCode.AI_AGENT_STEP_FAILURE,
- );
- }
-
- const clonedStepId = v4();
-
- const clonedAgent = await this.duplicateAgent({
- agentId,
- labelSuffix: clonedStepId.substring(0, 4),
- workspaceId,
- });
-
- return {
- ...step,
- id: clonedStepId,
- nextStepIds: [],
- position: duplicatedStepPosition,
- settings: {
- ...step.settings,
- input: {
- ...step.settings.input,
- agentId: clonedAgent.id,
- },
- },
- };
- }
case WorkflowActionType.ITERATOR: {
return {
...step,
@@ -1109,75 +1058,9 @@ export class WorkflowVersionStepOperationsWorkspaceService {
},
};
}
- case WorkflowActionType.AI_AGENT: {
- const agentId = step.settings.input.agentId;
-
- if (!isDefined(agentId)) {
- return step;
- }
-
- const newAgent = await this.duplicateAgent({
- agentId,
- labelSuffix: v4().substring(0, 4),
- workspaceId,
- });
-
- const roleId = await this.aiAgentRoleService.findAgentRoleId({
- agentId,
- workspaceId,
- });
-
- if (isDefined(roleId)) {
- await this.aiAgentRoleService.assignRoleToAgent({
- agentId: newAgent.id,
- roleId,
- workspaceId,
- });
- }
-
- return {
- ...step,
- settings: {
- ...step.settings,
- input: {
- ...step.settings.input,
- agentId: newAgent.id,
- },
- },
- };
- }
default: {
return step;
}
}
}
-
- private async duplicateAgent({
- agentId,
- labelSuffix,
- workspaceId,
- }: {
- agentId: string;
- labelSuffix: string;
- workspaceId: string;
- }) {
- const existingAgent = await this.agentService.findOneAgentById({
- id: agentId,
- workspaceId,
- });
-
- return this.agentService.createOneAgent(
- {
- label: existingAgent.label + ' ' + labelSuffix,
- icon: existingAgent.icon ?? undefined,
- description: existingAgent.description ?? undefined,
- prompt: existingAgent.prompt,
- modelId: existingAgent.modelId,
- responseFormat: existingAgent.responseFormat ?? undefined,
- modelConfiguration: existingAgent.modelConfiguration ?? undefined,
- isSystem: true,
- },
- workspaceId,
- );
- }
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
index 60234885870..400df9b6786 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
@@ -3,17 +3,16 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workflow-version-core.module';
-import { AiAgentRoleModule } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.module';
import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
-import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { WorkflowSchemaModule } from 'src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.module';
import { CodeStepBuildModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/code-step-build.module';
+import { WorkflowAiAgentStepAgentService } from 'src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service';
import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-crud.module';
@@ -24,19 +23,21 @@ import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-cru
WorkflowCommonModule,
CodeStepBuildModule,
FeatureFlagModule,
- AiAgentRoleModule,
AiAgentModule,
WorkspaceCacheModule,
- TypeOrmModule.forFeature([ObjectMetadataEntity, RoleTargetEntity]),
+ TypeOrmModule.forFeature([ObjectMetadataEntity]),
WorkspaceManyOrAllFlatEntityMapsCacheModule,
WorkflowVersionCoreModule,
RecordCrudModule,
],
providers: [
WorkflowVersionStepOperationsWorkspaceService,
- provideWorkspaceScopedRepository(RoleTargetEntity),
+ WorkflowAiAgentStepAgentService,
provideWorkspaceScopedRepository(ObjectMetadataEntity),
],
- exports: [WorkflowVersionStepOperationsWorkspaceService],
+ exports: [
+ WorkflowVersionStepOperationsWorkspaceService,
+ WorkflowAiAgentStepAgentService,
+ ],
})
export class WorkflowVersionStepModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts
index 3e9d99fd33d..05f0fc4a68c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts
@@ -85,7 +85,7 @@ export class WorkflowExecutionContextService {
WorkflowExecutionContext,
'application' | 'authContext'
>;
- targetApplicationId: string;
+ targetApplicationId: string | null;
targetLabel: string;
}): void {
if (
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
index 1897d02427c..2279702e3ed 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts
@@ -1,9 +1,6 @@
import { Module } from '@nestjs/common';
-import { TypeOrmModule } from '@nestjs/typeorm';
import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
-import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
-import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkflowExecutionContextModule } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.module';
import { WorkflowAgentConversationModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@@ -14,14 +11,10 @@ import { AiAgentWorkflowAction } from './ai-agent.workflow-action';
imports: [
WorkflowExecutionContextModule,
AiAgentExecutionModule,
- TypeOrmModule.forFeature([AgentEntity]),
WorkflowRunModule,
WorkflowAgentConversationModule,
],
- providers: [
- AiAgentWorkflowAction,
- provideWorkspaceScopedRepository(AgentEntity),
- ],
+ providers: [AiAgentWorkflowAction],
exports: [AiAgentWorkflowAction],
})
export class AiAgentActionModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index bfa8d9b79a4..78241695189 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -1,17 +1,24 @@
import { Injectable } from '@nestjs/common';
-import { msg } from '@lingui/core/macro';
import { isNonEmptyString, isString } from '@sniptt/guards';
import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';
+import {
+ getWorkflowAiAgentStepConfigIssues,
+ isWorkflowAiAgentGenerateStep,
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES,
+} from 'twenty-shared/workflow';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
+import { AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
+import { type ResolvedAgentRunPersona } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/resolved-agent-run-persona.type';
import { buildStartedAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-started-agent-run-summary.util';
-import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
-import { resolveEffectiveAgent } from 'src/engine/metadata-modules/flat-agent/utils/resolve-effective-agent.util';
-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -40,8 +47,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,
private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
- @InjectWorkspaceScopedRepository(AgentEntity)
- private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
+ private readonly agentRunPersonaService: AgentRunPersonaService,
) {}
async execute({
@@ -62,7 +68,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
- const { agentId, prompt } = step.settings.input;
+ const { prompt } = step.settings.input;
const workspaceId = runInfo.workspaceId;
const {
workspaceMemberId: recipientWorkspaceMemberId,
@@ -90,69 +96,72 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
- const agentRow = await this.agentRepository.findOne(workspaceId, {
- where: { id: agentId },
- });
-
- if (!isDefined(agentRow)) {
- throw new WorkflowStepExecutorException(
- `Agent with id ${agentId} not found`,
- WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
- );
- }
-
- const agent = resolveEffectiveAgent(agentRow);
-
- if (!agent.isActive) {
- const { label } = agent;
+ const [configIssue] = getWorkflowAiAgentStepConfigIssues(
+ step.settings.input,
+ );
+ if (isDefined(configIssue)) {
throw new WorkflowStepExecutorException(
- `Agent "${label}" is archived`,
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES[configIssue],
WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
- { userFriendlyMessage: msg`Agent "${label}" is archived.` },
);
}
const executionContext =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
+ const spec = buildWorkflowAgentRunSpec({
+ step,
+ // a run without an application id belongs to the workspace custom application
+ applicationId:
+ executionContext.application?.id ??
+ executionContext.authContext.workspace.workspaceCustomApplicationId,
+ });
+
+ const persona = await this.resolvePersonaOrThrow({ workspaceId, spec });
+
this.workflowExecutionContextService.assertRunApplicationCanTriggerStepTargetOrThrow(
{
executionContext,
- targetApplicationId: agent.applicationId,
- targetLabel: `Agent "${agent.name}"`,
+ targetApplicationId: persona.applicationId,
+ targetLabel: `The agent of step "${step.name}"`,
},
);
- const conversation =
- await this.workflowAgentConversationService.openConversation({
- runInfo,
- stepId: currentStepId,
- title: step.name,
- recipientWorkspaceMemberId: isNonEmptyString(recipientWorkspaceMemberId)
- ? recipientWorkspaceMemberId
- : null,
- threadKey: resolveConversationThreadKey({
- conversation: conversationSettings,
- defaultScope: 'STEP',
- workflowRunId: runInfo.workflowRunId,
- stepExecutionKey: buildStepExecutionKey({
- stepId: currentStepId,
- steps,
- context,
+ // an Agent step converses so it keeps its wait tools; a Generate step runs one-shot
+ const hasConversation = !isWorkflowAiAgentGenerateStep(step.settings.input);
+ const conversation = hasConversation
+ ? await this.workflowAgentConversationService.openConversation({
+ runInfo,
+ stepId: currentStepId,
+ title: step.name,
+ recipientWorkspaceMemberId: isNonEmptyString(
+ recipientWorkspaceMemberId,
+ )
+ ? recipientWorkspaceMemberId
+ : null,
+ threadKey: resolveConversationThreadKey({
+ conversation: conversationSettings,
+ defaultScope: 'STEP',
+ workflowRunId: runInfo.workflowRunId,
+ stepExecutionKey: buildStepExecutionKey({
+ stepId: currentStepId,
+ steps,
+ context,
+ }),
}),
- }),
- });
+ })
+ : null;
const resolvedPrompt = resolveInput(prompt, context) as string | undefined;
- // the conversation is linked from the start, so the run can be followed while it goes on
+ // a conversation is linked from the start, so the run can be followed while it goes on
await this.workflowRunStepLogService.setAiAgentStepLog({
workflowRunId: runInfo.workflowRunId,
workspaceId,
stepId: currentStepId,
- summary: buildStartedAgentRunSummary(agent.modelId),
- threadId: conversation.threadId,
+ summary: buildStartedAgentRunSummary(persona.modelId),
+ threadId: conversation?.threadId ?? null,
});
await this.agentRunnerService.start({
@@ -162,7 +171,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
workflowRunId: runInfo.workflowRunId,
stepId: currentStepId,
}),
- spec: buildWorkflowAgentRunSpec({ step }),
+ spec,
prompt: isDefined(resolvedPrompt)
? {
messages: [{ role: 'user', content: resolvedPrompt }],
@@ -175,4 +184,33 @@ export class AiAgentWorkflowAction implements WorkflowAction {
return { wait: { type: 'CALLBACK' } };
}
+
+ private async resolvePersonaOrThrow({
+ workspaceId,
+ spec,
+ }: {
+ workspaceId: string;
+ spec: AgentRunSpec;
+ }): Promise<ResolvedAgentRunPersona> {
+ try {
+ return await this.agentRunPersonaService.resolveOrThrow({
+ workspaceId,
+ spec,
+ });
+ } catch (error) {
+ if (
+ error instanceof AiException &&
+ (error.code === AiExceptionCode.AGENT_NOT_FOUND ||
+ error.code === AiExceptionCode.AGENT_IS_INACTIVE)
+ ) {
+ throw new WorkflowStepExecutorException(
+ error.message,
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ { userFriendlyMessage: error.userFriendlyMessage },
+ );
+ }
+
+ throw error;
+ }
+ }
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
index d34516fd3a7..70c5be8c730 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
@@ -1,11 +1,6 @@
-import { type AgentResponseFormat } from 'twenty-shared/ai';
-import { type WorkflowConversation } from 'twenty-shared/workflow';
+import { type z } from 'zod';
+import { type workflowAiAgentActionSettingsSchema } from 'twenty-shared/workflow';
-export type WorkflowAiAgentActionInput = {
- agentId: string;
- prompt?: string;
- responseFormat?: AgentResponseFormat;
- humanInputInstructions?: string;
- workspaceMemberId?: string;
- conversation?: WorkflowConversation;
-};
+export type WorkflowAiAgentActionInput = z.infer<
+ typeof workflowAiAgentActionSettingsSchema
+>['input'];
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
index 64b0eb9cfbb..b0edfb99f10 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-ai-agent-step-log.util.spec.ts
@@ -30,4 +30,10 @@ describe('buildAiAgentStepLog', () => {
sizeBytes: 0,
});
});
+
+ it('logs no conversation for a run without one', () => {
+ expect(
+ buildAiAgentStepLog({ summary: SUMMARY, threadId: null }).details,
+ ).toEqual({ type: 'AI_AGENT', ...SUMMARY });
+ });
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
index 97e25a03581..c95a0961e29 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
@@ -1,3 +1,4 @@
+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
import { WorkflowActionType } from 'twenty-shared/workflow';
import { buildWorkflowAgentRunSpec } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util';
@@ -30,6 +31,7 @@ describe('buildWorkflowAgentRunSpec', () => {
prompt: 'Draft the quote',
humanInputInstructions: ' ',
}),
+ applicationId: 'application-id',
});
expect(spec).toMatchObject({
@@ -49,6 +51,7 @@ describe('buildWorkflowAgentRunSpec', () => {
agentId: 'agent-id',
humanInputInstructions: ' Ask before choosing a plan. ',
}),
+ applicationId: 'application-id',
});
expect(spec.agentId).toBe('agent-id');
@@ -69,6 +72,7 @@ describe('buildWorkflowAgentRunSpec', () => {
const spec = buildWorkflowAgentRunSpec({
step: buildStep({ agentId: 'agent-id', responseFormat }),
+ applicationId: 'application-id',
});
expect(spec.responseFormat).toEqual(responseFormat);
@@ -77,8 +81,48 @@ describe('buildWorkflowAgentRunSpec', () => {
it("leaves the agent's output format to apply when the step gives none", () => {
const spec = buildWorkflowAgentRunSpec({
step: buildStep({ agentId: 'agent-id' }),
+ applicationId: 'application-id',
});
expect(spec).not.toHaveProperty('responseFormat');
});
+
+ it("carries the step's own config when it runs no agent", () => {
+ const scope = {
+ objectPermissions: [
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: true },
+ ],
+ };
+
+ const spec = buildWorkflowAgentRunSpec({
+ step: buildStep({
+ instructions: 'Qualify the lead.',
+ modelConfiguration: { webSearch: { enabled: true } },
+ scope,
+ prompt: 'Qualify {{trigger.name}}',
+ }),
+ applicationId: 'application-id',
+ });
+
+ expect(spec).toMatchObject({
+ agentId: null,
+ inlineConfig: {
+ instructions: 'Qualify the lead.',
+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ modelConfiguration: { webSearch: { enabled: true } },
+ scope,
+ applicationId: 'application-id',
+ promptCacheKey: 'workflow-step:step-id',
+ },
+ });
+ });
+
+ it('gives a step without an agent or scope no data tools', () => {
+ const spec = buildWorkflowAgentRunSpec({
+ step: buildStep({ instructions: 'Summarize.' }),
+ applicationId: 'application-id',
+ });
+
+ expect(spec.inlineConfig?.scope).toBeNull();
+ });
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
index 11dc6af998a..700eec00fe6 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util.ts
@@ -1,4 +1,5 @@
import { type AgentRunSummary } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
export const buildAiAgentStepLog = ({
@@ -6,9 +7,13 @@ export const buildAiAgentStepLog = ({
threadId,
}: {
summary: AgentRunSummary;
- threadId: string;
+ threadId: string | null;
}): WorkflowRunStepLog => ({
- details: { type: 'AI_AGENT', ...summary, threadId },
+ details: {
+ type: 'AI_AGENT',
+ ...summary,
+ ...(isDefined(threadId) ? { threadId } : {}),
+ },
entries: [],
sizeBytes: 0,
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
index cc2d7072988..192044d0ac7 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts
@@ -1,6 +1,5 @@
import { type ActorMetadata } from 'twenty-shared/types';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';
import { type AgentRunRoleIds } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-role-ids.type';
import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
@@ -21,7 +20,7 @@ const getAgentRunRoleIdsFromRolePermissionConfig = (
return agentRunRoleIds;
};
-// The step's agent acts with the run's permissions, derived again each time the agent continues
+// The run's roles narrow the step's agent, derived again each time the agent continues
export const buildWorkflowAgentRunExecutionContext = ({
executionContext,
turnCreatedBy,
@@ -35,10 +34,7 @@ export const buildWorkflowAgentRunExecutionContext = ({
: undefined,
turnCreatedBy,
userWorkspaceId: getWorkflowRunUserWorkspaceId(executionContext),
- rolePermissionConfig: executionContext.rolePermissionConfig,
- usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
agentRunRoleIds: getAgentRunRoleIdsFromRolePermissionConfig(
executionContext.rolePermissionConfig,
),
- application: executionContext.application,
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
index 7f376597ed6..bc794058f9f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
@@ -1,24 +1,60 @@
import { isNonEmptyString } from '@sniptt/guards';
+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
+import { isWorkflowAiAgentGenerateStep } from 'twenty-shared/workflow';
-import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
+import {
+ type AgentRunPersonaSpec,
+ type AgentRunSpec,
+} from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';
import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-base-system-prompt.constant';
import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { WORKFLOW_AGENT_HUMAN_INPUT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant';
-// what the engine needs to run the step's agent, and to continue it after a pause
+const buildPersonaSpec = ({
+ step,
+ applicationId,
+}: {
+ step: Pick<WorkflowAiAgentAction, 'id' | 'settings'>;
+ applicationId: string;
+}): AgentRunPersonaSpec => {
+ const { agentId, instructions, modelId, modelConfiguration, scope } =
+ step.settings.input;
+
+ if (
+ !isWorkflowAiAgentGenerateStep(step.settings.input) &&
+ isDefined(agentId)
+ ) {
+ return { agentId };
+ }
+
+ return {
+ agentId: null,
+ inlineConfig: {
+ instructions: instructions ?? '',
+ modelId: modelId ?? AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ modelConfiguration: modelConfiguration ?? null,
+ scope: scope ?? null,
+ applicationId,
+ promptCacheKey: `workflow-step:${step.id}`,
+ },
+ };
+};
+
export const buildWorkflowAgentRunSpec = ({
step,
+ applicationId,
}: {
step: WorkflowAiAgentAction;
+ // the application the workflow belongs to, which a step without an agent runs under
+ applicationId: string;
}): AgentRunSpec => {
- const { agentId, humanInputInstructions, responseFormat } =
- step.settings.input;
+ const { humanInputInstructions, responseFormat } = step.settings.input;
const trimmedHumanInputInstructions = humanInputInstructions?.trim();
const canAskHumans = isNonEmptyString(trimmedHumanInputInstructions);
return {
- agentId,
+ ...buildPersonaSpec({ step, applicationId }),
title: step.name,
baseSystemPrompt: WORKFLOW_BASE_SYSTEM_PROMPT,
instructions: canAskHumans
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
index 8b439b91604..7a5c9af6de8 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
@@ -5,6 +5,7 @@ import { type AgentCallerConversationService } from 'src/engine/metadata-modules
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { WorkflowStepExecutorExceptionCode } from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { createMockIteratorStep } from 'src/modules/workflow/workflow-executor/utils/create-mock-workflow-steps.util';
import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
@@ -15,6 +16,9 @@ const WORKSPACE_ID = 'workspace-id';
const WORKFLOW_RUN_ID = 'workflow-run-id';
const WORKFLOW_ID = 'workflow-id';
const WORKSPACE_MEMBER_ID = '20202020-2222-4222-8222-222222222222';
+const EXECUTION_CONTEXT = {
+ rolePermissionConfig: { intersectionOf: { applicationRoleId: 'role-id' } },
+};
const buildStep = (input: Record<string, unknown>): WorkflowAction =>
({
@@ -75,6 +79,9 @@ describe('SendChatMessageWorkflowAction', () => {
{} as WorkspaceCacheService,
),
{ arm: armStepWait } as unknown as WorkflowStepWaitWorkspaceService,
+ {
+ getExecutionContext: jest.fn().mockResolvedValue(EXECUTION_CONTEXT),
+ } as unknown as WorkflowExecutionContextService,
);
});
@@ -126,10 +133,7 @@ describe('SendChatMessageWorkflowAction', () => {
awaitedToolCall: {
toolName: 'update_one_company',
arguments: { id: 'id' },
- caller: {
- type: 'WORKFLOW_STEP',
- ref: { workflowRunId: WORKFLOW_RUN_ID, stepId: 'step-1' },
- },
+ permissions: EXECUTION_CONTEXT,
waitOnAnswer: expect.any(Function),
},
}),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
index f697d1aac69..d378e358bcd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
+import { WorkflowExecutionContextModule } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.module';
import { WorkflowRunInboxSenderModule } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module';
import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
import { WorkflowStepWaitModule } from 'src/modules/workflow/workflow-wait/workflow-step-wait.module';
@@ -8,6 +9,7 @@ import { WorkflowStepWaitModule } from 'src/modules/workflow/workflow-wait/workf
@Module({
imports: [
AiAgentExecutionModule,
+ WorkflowExecutionContextModule,
WorkflowRunInboxSenderModule,
WorkflowStepWaitModule,
],
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
index ee29b589647..20012b451f9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
@@ -10,11 +10,11 @@ import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
import { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';
-import { buildWorkflowStepCaller } from 'src/modules/workflow/workflow-executor/utils/build-workflow-step-caller.util';
import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
import { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util';
import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';
@@ -27,6 +27,7 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
private readonly agentCallerConversationService: AgentCallerConversationService,
private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,
private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
+ private readonly workflowExecutionContextService: WorkflowExecutionContextService,
) {}
async execute({
@@ -96,10 +97,10 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
awaitedToolCall: isDefined(toolCall)
? {
...toolCall,
- caller: buildWorkflowStepCaller({
- workflowRunId: runInfo.workflowRunId,
- stepId: currentStepId,
- }),
+ permissions:
+ await this.workflowExecutionContextService.getExecutionContext(
+ runInfo,
+ ),
waitOnAnswer: (postedCall) =>
this.workflowStepWaitWorkspaceService.arm({
workspaceId: runInfo.workspaceId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
index cfc40b9b0a8..aed96799459 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service.ts
@@ -73,7 +73,7 @@ export class WorkflowRunStepLogWorkspaceService {
workspaceId: string;
stepId: string;
summary: AgentRunSummary;
- threadId: string;
+ threadId: string | null;
}): Promise<void> {
const stepLog = buildAiAgentStepLog({ summary, threadId });
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/services/workflow-tool.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/services/workflow-tool.workspace-service.ts
index c4b775adc85..c90c69ea656 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/services/workflow-tool.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/services/workflow-tool.workspace-service.ts
@@ -14,6 +14,7 @@ import { LogicFunctionFromSourceService } from 'src/engine/metadata-modules/logi
import { type RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { WorkflowSchemaWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service';
+import { WorkflowAiAgentStepAgentService } from 'src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service';
import { createActivateWorkflowVersionTool } from 'src/modules/workflow/workflow-tools/tools/activate-workflow-version.tool';
import { createComputeStepOutputSchemaTool } from 'src/modules/workflow/workflow-tools/tools/compute-step-output-schema.tool';
import { createCreateCompleteWorkflowTool } from 'src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool';
@@ -30,7 +31,6 @@ import { createGetWorkflowRunTool } from 'src/modules/workflow/workflow-tools/to
import { createListLogicFunctionToolsTool } from 'src/modules/workflow/workflow-tools/tools/list-logic-function-tools.tool';
import { createListWorkflowRunsTool } from 'src/modules/workflow/workflow-tools/tools/list-workflow-runs.tool';
import { createListWorkflowsTool } from 'src/modules/workflow/workflow-tools/tools/list-workflows.tool';
-import { createUpdateWorkflowAgentTool } from 'src/modules/workflow/workflow-tools/tools/update-workflow-agent.tool';
import { createUpdateLogicFunctionSourceTool } from 'src/modules/workflow/workflow-tools/tools/update-logic-function-source.tool';
import { createUpdateWorkflowVersionPositionsTool } from 'src/modules/workflow/workflow-tools/tools/update-workflow-version-positions.tool';
import { createUpdateWorkflowVersionStepTool } from 'src/modules/workflow/workflow-tools/tools/update-workflow-version-step.tool';
@@ -57,6 +57,7 @@ export class WorkflowToolWorkspaceService {
logicFunctionFromSourceService: LogicFunctionFromSourceService,
flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
agentService: AgentService,
+ workflowAiAgentStepAgentService: WorkflowAiAgentStepAgentService,
) {
this.deps = {
coreWorkflowListService,
@@ -70,6 +71,7 @@ export class WorkflowToolWorkspaceService {
logicFunctionFromSourceService,
flatEntityMapsCacheService,
agentService,
+ workflowAiAgentStepAgentService,
};
}
@@ -109,7 +111,6 @@ export class WorkflowToolWorkspaceService {
createGetLogicFunctionSourceTool(this.deps, context),
createUpdateLogicFunctionSourceTool(this.deps, context),
createListLogicFunctionToolsTool(this.deps, context),
- createUpdateWorkflowAgentTool(this.deps, context),
createValidateWorkflowTool(this.deps, context),
];
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/create-complete-workflow.tool.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/create-complete-workflow.tool.spec.ts
index b30d8cad7a1..532e9e67f0f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/create-complete-workflow.tool.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/create-complete-workflow.tool.spec.ts
@@ -1,3 +1,7 @@
+import {
+ WorkflowVersionStepException,
+ WorkflowVersionStepExceptionCode,
+} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';
import { createCreateCompleteWorkflowTool } from 'src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool';
const CORE_WORKFLOW_ID = 'b3b8a4f0-0000-4000-8000-000000000001';
@@ -12,13 +16,19 @@ const trigger = {
nextStepIds: [],
};
-const buildStep = (type: string) => ({
+const buildStep = ({
+ type,
+ input = {},
+}: {
+ type: string;
+ input?: Record<string, unknown>;
+}) => ({
id: STEP_ID,
name: 'Step',
type,
valid: true,
nextStepIds: [],
- settings: { input: {}, outputSchema: {} },
+ settings: { input, outputSchema: {} },
});
const edges = [{ source: 'trigger', target: STEP_ID }];
@@ -36,17 +46,27 @@ const buildTool = () => {
const coreWorkflowLifecycleService = {
activateCoreWorkflowVersion: jest.fn().mockResolvedValue(true),
};
+ const workflowAiAgentStepAgentService = {
+ findAgentRunnableByNewStepOrThrow: jest.fn(),
+ };
+ const dependencies: Parameters<typeof createCreateCompleteWorkflowTool>[0] = {
+ coreWorkflowMutationService,
+ coreWorkflowLifecycleService,
+ workflowAiAgentStepAgentService,
+ };
- const tool = createCreateCompleteWorkflowTool(
- { coreWorkflowMutationService, coreWorkflowLifecycleService } as never,
- {
- workspaceId: 'workspace-id',
- userWorkspaceId: 'user-workspace-id',
- rolePermissionConfig: { shouldBypassPermissionChecks: true },
- },
- );
+ const tool = createCreateCompleteWorkflowTool(dependencies, {
+ workspaceId: 'workspace-id',
+ userWorkspaceId: 'user-workspace-id',
+ rolePermissionConfig: { shouldBypassPermissionChecks: true },
+ });
- return { tool, coreWorkflowMutationService, coreWorkflowLifecycleService };
+ return {
+ tool,
+ coreWorkflowMutationService,
+ coreWorkflowLifecycleService,
+ workflowAiAgentStepAgentService,
+ };
};
type ToolInput = Parameters<
@@ -57,7 +77,7 @@ const buildInput = (overrides: Partial<Record<string, unknown>> = {}) =>
({
name: 'My workflow',
trigger,
- steps: [buildStep('SEND_EMAIL')],
+ steps: [buildStep({ type: 'SEND_EMAIL' })],
edges,
...overrides,
}) as unknown as ToolInput;
@@ -79,7 +99,7 @@ describe('createCreateCompleteWorkflowTool', () => {
userWorkspaceId: 'user-workspace-id',
name: 'My workflow',
trigger,
- steps: [buildStep('SEND_EMAIL')],
+ steps: [buildStep({ type: 'SEND_EMAIL' })],
edges,
}),
);
@@ -114,21 +134,67 @@ describe('createCreateCompleteWorkflowTool', () => {
});
});
- it.each(['CODE', 'AI_AGENT'])(
- 'refuses %s steps without creating anything',
- async (stepType) => {
- const { tool, coreWorkflowMutationService } = buildTool();
-
- const result = await tool.execute(
- buildInput({ steps: [buildStep(stepType)] }),
- );
-
- expect(result.success).toBe(false);
- expect(
- coreWorkflowMutationService.createWorkflowWithContent,
- ).not.toHaveBeenCalled();
- },
- );
+ it('refuses CODE steps without creating anything', async () => {
+ const { tool, coreWorkflowMutationService } = buildTool();
+
+ const result = await tool.execute(
+ buildInput({ steps: [buildStep({ type: 'CODE' })] }),
+ );
+
+ expect(result.success).toBe(false);
+ expect(
+ coreWorkflowMutationService.createWorkflowWithContent,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('creates AI_AGENT steps, which need no agent', async () => {
+ const { tool, coreWorkflowMutationService } = buildTool();
+
+ const result = await tool.execute(
+ buildInput({ steps: [buildStep({ type: 'AI_AGENT' })] }),
+ );
+
+ expect(result.success).toBe(true);
+ expect(
+ coreWorkflowMutationService.createWorkflowWithContent,
+ ).toHaveBeenCalled();
+ });
+
+ it("refuses an AI_AGENT step running another step's hidden agent", async () => {
+ const {
+ tool,
+ coreWorkflowMutationService,
+ workflowAiAgentStepAgentService,
+ } = buildTool();
+
+ workflowAiAgentStepAgentService.findAgentRunnableByNewStepOrThrow.mockRejectedValue(
+ new WorkflowVersionStepException(
+ 'Agent "Hidden step agent" is archived or belongs to another workflow step',
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ ),
+ );
+
+ const result = await tool.execute(
+ buildInput({
+ steps: [
+ buildStep({
+ type: 'AI_AGENT',
+ input: { agentId: 'hidden-agent-id' },
+ }),
+ ],
+ }),
+ );
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ success: false,
+ error: expect.stringContaining('belongs to another workflow step'),
+ }),
+ );
+ expect(
+ coreWorkflowMutationService.createWorkflowWithContent,
+ ).not.toHaveBeenCalled();
+ });
it('activates the created version when asked to', async () => {
const { tool, coreWorkflowLifecycleService } = buildTool();
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/update-workflow-agent.tool.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/update-workflow-agent.tool.spec.ts
deleted file mode 100644
index 87ec024e3f1..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/__tests__/update-workflow-agent.tool.spec.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { createUpdateWorkflowAgentTool } from 'src/modules/workflow/workflow-tools/tools/update-workflow-agent.tool';
-
-const AGENT_ID = 'f47ac10b-58cc-4372-a567-0e02b2c3d479';
-const WORKSPACE_ID = 'workspace-id';
-
-const buildAiAgentStep = (agentId: string, stepId = 'step-1') => ({
- id: stepId,
- name: 'Agent',
- type: 'AI_AGENT',
- valid: true,
- settings: { input: { agentId }, outputSchema: {} },
-});
-
-const buildTool = ({
- draftCoreVersions = [],
-}: {
- draftCoreVersions?: { id: string; steps: unknown[] | null }[];
-} = {}) => {
- const agentService = {
- updateOneAgent: jest.fn().mockResolvedValue({ id: AGENT_ID }),
- };
- const coreWorkflowVersionMutationService = {
- updateStep: jest.fn().mockResolvedValue(undefined),
- };
- const coreWorkflowVersionListService = {
- findDraftCoreWorkflowVersions: jest
- .fn()
- .mockResolvedValue(draftCoreVersions),
- };
- const tool = createUpdateWorkflowAgentTool(
- {
- agentService,
- coreWorkflowVersionMutationService,
- coreWorkflowVersionListService,
- } as never,
- {
- workspaceId: WORKSPACE_ID,
- rolePermissionConfig: { shouldBypassPermissionChecks: true },
- },
- );
-
- return {
- tool,
- agentService,
- coreWorkflowVersionMutationService,
- coreWorkflowVersionListService,
- };
-};
-
-describe('createUpdateWorkflowAgentTool', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('should set the response format on the linked AI_AGENT steps rather than on the agent', async () => {
- const step = buildAiAgentStep(AGENT_ID);
- const responseFormat = {
- type: 'json',
- schema: {
- type: 'object',
- properties: { summary: { type: 'string' } },
- },
- };
- const { tool, agentService, coreWorkflowVersionMutationService } =
- buildTool({
- draftCoreVersions: [{ id: 'core-version-1', steps: [step] }],
- });
-
- const result = (await tool.execute({
- agentId: AGENT_ID,
- responseFormat,
- } as never)) as Record<string, unknown>;
-
- expect(result.success).toBe(true);
- expect(agentService.updateOneAgent).not.toHaveBeenCalled();
- expect(coreWorkflowVersionMutationService.updateStep).toHaveBeenCalledTimes(
- 1,
- );
- expect(coreWorkflowVersionMutationService.updateStep).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- coreWorkflowVersionId: 'core-version-1',
- step: {
- ...step,
- settings: {
- ...step.settings,
- input: { agentId: AGENT_ID, responseFormat },
- },
- },
- });
- });
-
- it('should set the response format on every step using the agent in a draft', async () => {
- const firstStep = buildAiAgentStep(AGENT_ID, 'step-1');
- const secondStep = buildAiAgentStep(AGENT_ID, 'step-2');
- const { tool, coreWorkflowVersionMutationService } = buildTool({
- draftCoreVersions: [
- { id: 'core-version-1', steps: [firstStep, secondStep] },
- ],
- });
-
- await tool.execute({
- agentId: AGENT_ID,
- responseFormat: { type: 'text' },
- } as never);
-
- expect(coreWorkflowVersionMutationService.updateStep).toHaveBeenCalledTimes(
- 2,
- );
- expect(
- coreWorkflowVersionMutationService.updateStep.mock.calls.map(
- ([{ step }]) => step.id,
- ),
- ).toEqual(['step-1', 'step-2']);
- });
-
- it('should only update the agent when responseFormat is not provided', async () => {
- const step = buildAiAgentStep(AGENT_ID);
- const {
- tool,
- agentService,
- coreWorkflowVersionMutationService,
- coreWorkflowVersionListService,
- } = buildTool({
- draftCoreVersions: [{ id: 'core-version-1', steps: [step] }],
- });
-
- const result = (await tool.execute({
- agentId: AGENT_ID,
- prompt: 'You are a helpful assistant',
- } as never)) as Record<string, unknown>;
-
- expect(result.success).toBe(true);
- expect(agentService.updateOneAgent).toHaveBeenCalledTimes(1);
- expect(agentService.updateOneAgent).toHaveBeenCalledWith({
- input: { id: AGENT_ID, prompt: 'You are a helpful assistant' },
- workspaceId: WORKSPACE_ID,
- });
- expect(
- coreWorkflowVersionListService.findDraftCoreWorkflowVersions,
- ).not.toHaveBeenCalled();
- expect(
- coreWorkflowVersionMutationService.updateStep,
- ).not.toHaveBeenCalled();
- });
-
- it('should skip steps referencing a different agent', async () => {
- const { tool, coreWorkflowVersionMutationService } = buildTool({
- draftCoreVersions: [
- {
- id: 'core-version-1',
- steps: [buildAiAgentStep('another-agent-id')],
- },
- ],
- });
-
- const result = await tool.execute({
- agentId: AGENT_ID,
- responseFormat: { type: 'text' },
- } as never);
-
- expect(
- coreWorkflowVersionMutationService.updateStep,
- ).not.toHaveBeenCalled();
- expect(result.success).toBe(false);
- expect(result.message).toContain('no draft AI_AGENT step uses agent');
- });
-
- it('should report a failure when the steps cannot be updated', async () => {
- const step = buildAiAgentStep(AGENT_ID);
- const { tool, coreWorkflowVersionMutationService } = buildTool({
- draftCoreVersions: [{ id: 'core-version-1', steps: [step] }],
- });
-
- coreWorkflowVersionMutationService.updateStep.mockRejectedValue(
- new Error('boom'),
- );
-
- const result = (await tool.execute({
- agentId: AGENT_ID,
- responseFormat: { type: 'text' },
- } as never)) as Record<string, unknown>;
-
- expect(result.success).toBe(false);
- expect(result.error).toBe('boom');
- });
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
index 749e0c98f93..fdbec54378c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
@@ -1,5 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
import {
+ isWorkflowAiAgentGenerateStep,
WORKFLOW_ACTION_FEATURE_FLAGS,
workflowActionSchema,
WorkflowActionType,
@@ -51,10 +52,20 @@ const createCompleteWorkflowSchema = z.object({
.describe('Whether to activate the workflow immediately (default: false)'),
});
-type CreateCompleteWorkflowToolDeps = Pick<
- WorkflowToolDependencies,
- 'coreWorkflowMutationService' | 'coreWorkflowLifecycleService'
->;
+type CreateCompleteWorkflowToolDeps = {
+ coreWorkflowMutationService: Pick<
+ WorkflowToolDependencies['coreWorkflowMutationService'],
+ 'createWorkflowWithContent'
+ >;
+ coreWorkflowLifecycleService: Pick<
+ WorkflowToolDependencies['coreWorkflowLifecycleService'],
+ 'activateCoreWorkflowVersion'
+ >;
+ workflowAiAgentStepAgentService: Pick<
+ WorkflowToolDependencies['workflowAiAgentStepAgentService'],
+ 'findAgentRunnableByNewStepOrThrow'
+ >;
+};
type CreateCompleteWorkflowFailure = {
success: false;
@@ -91,7 +102,7 @@ Common mistakes to avoid:
- Missing the "objectRecord" field in CREATE_RECORD actions
- Using "fieldsToUpdate" instead of "objectRecord" in CREATE_RECORD actions
- Including CODE steps in this tool — this tool does NOT create the underlying logic function needed by CODE steps. Instead, create the workflow without CODE steps first, then add CODE steps individually using create_workflow_version_step (which properly creates the logic function), then call update_logic_function_source to define the code.
-- Including AI_AGENT steps in this tool — this tool does NOT create the underlying agent needed by AI_AGENT steps. Instead, create the workflow without AI_AGENT steps first, then add AI_AGENT steps individually using create_workflow_version_step (which properly creates the agent), then call update_workflow_agent to configure the agent.
+- Setting an AI_AGENT step's agentId without being asked to run that agent: a step without agentId carries its own settings.input.instructions (system prompt), prompt (the message sent on each run), modelId, responseFormat and scope (the objects it may read or change, same shape as a role manifest's permissions, with object universal identifiers; no data access when unset). A step with agentId runs that existing agent: the agent supplies the instructions, model and permissions, and its response format unless the step sets settings.input.responseFormat.
IMPORTANT: The tool schema provides comprehensive field descriptions, examples, and validation rules. Always refer to the schema for:
- Field requirements and data types
@@ -202,6 +213,11 @@ const createWorkflowOrBuildFailure = async ({
> => {
try {
assertStepTypesAreSupported(steps);
+ await assertAiAgentStepsRunReusableAgentsOrThrow({
+ deps,
+ workspaceId,
+ steps,
+ });
return {
createdWorkflow:
@@ -233,13 +249,6 @@ const assertStepTypesAreSupported = (steps: WorkflowAction[]): void => {
);
}
- if (steps.some((step) => step.type === WorkflowActionType.AI_AGENT)) {
- throw new WorkflowVersionStepException(
- 'AI_AGENT steps cannot be created via create_complete_workflow because it does not create the underlying agent. Use create_workflow_version_step instead, then call update_workflow_agent to configure the agent.',
- WorkflowVersionStepExceptionCode.INVALID_REQUEST,
- );
- }
-
const flagGatedStep = steps.find((step) =>
isDefined(WORKFLOW_ACTION_FEATURE_FLAGS[step.type]),
);
@@ -251,3 +260,32 @@ const assertStepTypesAreSupported = (steps: WorkflowAction[]): void => {
);
}
};
+
+const assertAiAgentStepsRunReusableAgentsOrThrow = async ({
+ deps,
+ workspaceId,
+ steps,
+}: {
+ deps: Pick<CreateCompleteWorkflowToolDeps, 'workflowAiAgentStepAgentService'>;
+ workspaceId: string;
+ steps: WorkflowAction[];
+}): Promise<void> => {
+ const agentIds = new Set(
+ steps.flatMap((step) =>
+ step.type === WorkflowActionType.AI_AGENT &&
+ !isWorkflowAiAgentGenerateStep(step.settings.input) &&
+ isDefined(step.settings.input.agentId)
+ ? [step.settings.input.agentId]
+ : [],
+ ),
+ );
+
+ await Promise.all(
+ [...agentIds].map((agentId) =>
+ deps.workflowAiAgentStepAgentService.findAgentRunnableByNewStepOrThrow({
+ agentId,
+ workspaceId,
+ }),
+ ),
+ );
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-workflow-version-step.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-workflow-version-step.tool.ts
index 7e450d3bb15..01c6dc3f50d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-workflow-version-step.tool.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-workflow-version-step.tool.ts
@@ -83,7 +83,7 @@ const enrichResultWithNextStep = ({
return {
...result,
nextStep:
- 'This AI_AGENT step was created with a default placeholder agent. You MUST now call update_workflow_agent with the agentId from this step\'s settings.input.agentId to set the agent\'s system prompt (and optionally its model and responseFormat). Use responseFormat { type: "json", schema: { ... } } when downstream steps need to reference structured fields via {{stepId.fieldName}}, otherwise the output is referenced as {{stepId.response}}. If the step needs a task-specific prompt, also set it via update_workflow_version_step on settings.input.prompt.',
+ 'If this AI_AGENT step runs no agent (no settings.input.agentId), it was created without instructions: you MUST now call update_workflow_version_step to set settings.input.instructions (its system prompt) and settings.input.prompt (the message sent on each run), and optionally modelId and responseFormat. Use responseFormat { type: "json", schema: { ... } } when downstream steps need to reference structured fields via {{stepId.fieldName}}, otherwise the output is referenced as {{stepId.response}}. The step reads no records until settings.input.scope grants it objects (same shape as a role manifest\'s permissions, with object universal identifiers). If it runs an agent, set settings.input.prompt: the agent supplies the instructions, model and permissions, and its response format unless the step sets settings.input.responseFormat.',
};
default:
return result;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/update-workflow-agent.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/update-workflow-agent.tool.ts
deleted file mode 100644
index 312c99f45a3..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/update-workflow-agent.tool.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-import {
- agentResponseFormatSchema,
- WorkflowActionType,
-} from 'twenty-shared/workflow';
-import { z } from 'zod';
-
-import { type AgentResponseFormat } from 'src/engine/metadata-modules/ai/ai-agent/types/agent-response-format.type';
-import { type ModelId } from 'src/engine/metadata-modules/ai/ai-models/types/model-id.type';
-import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-import {
- type WorkflowToolContext,
- type WorkflowToolDependencies,
-} from 'src/modules/workflow/workflow-tools/types/workflow-tool-dependencies.type';
-
-const updateAgentSchema = z.object({
- agentId: z
- .string()
- .uuid()
- .describe(
- "The ID of the agent to update (from the AI_AGENT step's settings.input.agentId)",
- ),
- prompt: z
- .string()
- .optional()
- .describe(
- "The agent's system prompt describing its role, behavior and the task it must accomplish.",
- ),
- modelId: z
- .string()
- .optional()
- .describe(
- 'Optional model id to use for the agent. Leave empty to keep the auto-selected model.',
- ),
- responseFormat: agentResponseFormatSchema
- .optional()
- .describe(
- 'Optional response format. Use { type: "text" } for free-form text output, or { type: "json", schema: { type: "object", properties: { fieldName: { type: "string" } } } } for structured output. Downstream steps can reference structured fields via {{stepId.fieldName}} (or {{stepId.response}} for text format).',
- ),
-});
-
-const setAiAgentStepsResponseFormat = async (
- deps: Pick<
- WorkflowToolDependencies,
- 'coreWorkflowVersionListService' | 'coreWorkflowVersionMutationService'
- >,
- {
- workspaceId,
- userWorkspaceId,
- agentId,
- responseFormat,
- }: {
- workspaceId: string;
- userWorkspaceId: string | undefined;
- agentId: string;
- responseFormat: AgentResponseFormat;
- },
-): Promise<number> => {
- let updatedStepCount = 0;
-
- const draftCoreVersions =
- await deps.coreWorkflowVersionListService.findDraftCoreWorkflowVersions({
- workspaceId,
- });
-
- for (const draftCoreVersion of draftCoreVersions) {
- const matchingSteps = (draftCoreVersion.steps ?? []).filter(
- (step): step is WorkflowAiAgentAction =>
- step.type === WorkflowActionType.AI_AGENT &&
- step.settings?.input?.agentId === agentId,
- );
-
- for (const matchingStep of matchingSteps) {
- await deps.coreWorkflowVersionMutationService.updateStep({
- workspaceId,
- userWorkspaceId,
- coreWorkflowVersionId: draftCoreVersion.id,
- step: {
- ...matchingStep,
- settings: {
- ...matchingStep.settings,
- input: { ...matchingStep.settings.input, responseFormat },
- },
- },
- });
-
- updatedStepCount++;
- }
- }
-
- return updatedStepCount;
-};
-
-export const createUpdateWorkflowAgentTool = (
- deps: Pick<
- WorkflowToolDependencies,
- | 'agentService'
- | 'coreWorkflowVersionListService'
- | 'coreWorkflowVersionMutationService'
- >,
- context: WorkflowToolContext,
-) => ({
- name: 'update_workflow_agent' as const,
- description: `Update the agent used by a workflow AI_AGENT step.
-
-Use this tool to configure the agent created when an AI_AGENT step is added: set its system prompt, the model it should use, and the format of the step's output.
-
-- prompt: the agent's system prompt (its role, behavior and task).
-- modelId: optional model id; omit to keep the auto-selected model.
-- responseFormat: set on the draft AI_AGENT steps using this agent. { type: "text" } for free-form text (referenced as {{stepId.response}}), or { type: "json", schema: { ... } } for structured output whose fields can be referenced as {{stepId.fieldName}}.
-
-To find the agentId, look at the AI_AGENT step's settings.input.agentId field.`,
- inputSchema: updateAgentSchema,
- execute: async (parameters: {
- agentId: string;
- prompt?: string;
- modelId?: string;
- responseFormat?: AgentResponseFormat;
- }) => {
- try {
- const { agentId, prompt, modelId, responseFormat } = parameters;
- const { workspaceId } = context;
-
- if (isDefined(prompt) || isDefined(modelId)) {
- await deps.agentService.updateOneAgent({
- input: {
- id: agentId,
- ...(isDefined(prompt) ? { prompt } : {}),
- ...(isDefined(modelId) ? { modelId: modelId as ModelId } : {}),
- },
- workspaceId,
- });
- }
-
- if (!isDefined(responseFormat)) {
- return {
- success: true,
- message: `Successfully updated agent ${agentId}`,
- agentId,
- };
- }
-
- const updatedStepCount = await setAiAgentStepsResponseFormat(deps, {
- workspaceId,
- userWorkspaceId: context.userWorkspaceId,
- agentId,
- responseFormat,
- });
-
- if (updatedStepCount === 0) {
- return {
- success: false,
- error: 'No draft AI_AGENT step uses this agent',
- message: `The response format was not applied: no draft AI_AGENT step uses agent ${agentId}. Create a draft version first.`,
- agentId,
- };
- }
-
- return {
- success: true,
- message: `Successfully updated agent ${agentId} and the response format of ${updatedStepCount} draft step(s)`,
- agentId,
- updatedStepCount,
- };
- } catch (error) {
- return {
- success: false,
- error: error.message,
- message: `Failed to update agent: ${error.message}`,
- };
- }
- },
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/types/workflow-tool-dependencies.type.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/types/workflow-tool-dependencies.type.ts
index 76812d5d057..823085f3b2d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/types/workflow-tool-dependencies.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/types/workflow-tool-dependencies.type.ts
@@ -10,6 +10,7 @@ import type { LogicFunctionFromSourceService } from 'src/engine/metadata-modules
import type { RolePermissionConfig } from 'src/engine/permissions/principal/types/role-permission-config.type';
import type { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import type { WorkflowSchemaWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service';
+import type { WorkflowAiAgentStepAgentService } from 'src/modules/workflow/workflow-builder/workflow-version-step/services/workflow-ai-agent-step-agent.service';
export type WorkflowToolDependencies = {
coreWorkflowListService: CoreWorkflowListService;
@@ -23,6 +24,7 @@ export type WorkflowToolDependencies = {
logicFunctionFromSourceService: LogicFunctionFromSourceService;
flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService;
agentService: AgentService;
+ workflowAiAgentStepAgentService: WorkflowAiAgentStepAgentService;
};
export type WorkflowToolContext = {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/workflow-tools.module.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/workflow-tools.module.ts
index 35294b972cd..9091a0d634f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/workflow-tools.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/workflow-tools.module.ts
@@ -6,6 +6,7 @@ import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
import { WorkflowSchemaModule } from 'src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.module';
+import { WorkflowVersionStepModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module';
import { WorkflowToolWorkspaceService } from './services/workflow-tool.workspace-service';
@@ -19,6 +20,7 @@ import { WorkflowToolWorkspaceService } from './services/workflow-tool.workspace
LogicFunctionModule,
WorkspaceManyOrAllFlatEntityMapsCacheModule,
AiAgentModule,
+ WorkflowVersionStepModule,
],
providers: [
WorkflowToolWorkspaceService,
diff --git a/packages/twenty-server/test/integration/ai/suites/agent-conversation-stream.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/agent-conversation-stream.integration-spec.ts
new file mode 100644
index 00000000000..c3533a40a37
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/suites/agent-conversation-stream.integration-spec.ts
@@ -0,0 +1,214 @@
+import { randomUUID } from 'node:crypto';
+
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';
+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { agentConversationHistoryQueryFactory } from 'test/integration/ai/utils/agent-conversation-history-query-factory.util';
+import { runAgentInConversationQueryFactory } from 'test/integration/ai/utils/run-agent-in-conversation-query-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import {
+ buildAgentExecutionResult,
+ mockAgentRunTurns,
+} from 'test/utils/mock-agent-run-turns.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const REPLYING_RESULT = buildAgentExecutionResult({
+ result: { response: 'Acme renews in May' },
+ steps: [
+ { content: [{ type: 'text', text: 'Acme renews in May' }] },
+ ] as AgentExecutionResult['steps'],
+});
+
+const findAgentUniversalIdentifier = async (agentId: string) => {
+ const [agent] = await globalThis.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core."agent" WHERE id = $1`,
+ [agentId],
+ );
+
+ return agent.universalIdentifier;
+};
+
+describe('Agent conversations read by their application (integration)', () => {
+ let application: ApplicationWithResources;
+ let agentUniversalIdentifier: string;
+ let applicationToken: string;
+ let otherApplicationAgentId: string;
+ let otherApplicationAgentUniversalIdentifier: string;
+ const threadIds: string[] = [];
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Agent Conversation Probe',
+ });
+
+ const [applicationAgentUniversalIdentifier, tokenPair, { data }] =
+ await Promise.all([
+ findAgentUniversalIdentifier(application.agentId),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ createOneAgent({
+ expectToFail: false,
+ input: {
+ label: 'Agent Of Another Application',
+ prompt: 'Answer questions',
+ modelId: TEST_AI_MODEL_ID,
+ },
+ }),
+ ]);
+
+ agentUniversalIdentifier = applicationAgentUniversalIdentifier;
+ applicationToken = tokenPair.applicationAccessToken.token;
+ otherApplicationAgentId = data.createOneAgent.id;
+
+ otherApplicationAgentUniversalIdentifier =
+ await findAgentUniversalIdentifier(otherApplicationAgentId);
+ }, 120000);
+
+ afterEach(() => jest.restoreAllMocks());
+
+ afterAll(async () => {
+ // no member is granted the threads runAgent creates, so the API cannot destroy them
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."agentChatThread" WHERE id = ANY($1)`,
+ [threadIds],
+ );
+
+ if (isDefined(otherApplicationAgentId)) {
+ await deleteOneAgent({
+ expectToFail: false,
+ input: { id: otherApplicationAgentId },
+ });
+ }
+
+ if (isDefined(application)) {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ }
+ });
+
+ it('reads the history of a run through the chat queries, named by agent and key', async () => {
+ const threadKey = randomUUID();
+
+ mockAgentRunTurns(REPLYING_RESULT);
+
+ const runResponse = await makeMetadataApiRequest(
+ runAgentInConversationQueryFactory({
+ agentUniversalIdentifier,
+ content: 'When does Acme renew?',
+ threadKey,
+ }),
+ applicationToken,
+ );
+
+ expect(runResponse.body.errors).toBeUndefined();
+ expect(runResponse.body.data.runAgent.status).toBe('COMPLETED');
+
+ const { threadId, runId } = runResponse.body.data.runAgent;
+
+ threadIds.push(threadId);
+
+ const historyResponse = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({
+ agentUniversalIdentifier,
+ threadKey,
+ }),
+ applicationToken,
+ );
+
+ expect(historyResponse.body.errors).toBeUndefined();
+ expect(historyResponse.body.data.chatMessages).toEqual([
+ {
+ threadId,
+ turnId: runId,
+ role: 'user',
+ parts: [{ type: 'text', textContent: 'When does Acme renew?' }],
+ },
+ {
+ threadId,
+ turnId: runId,
+ role: 'assistant',
+ parts: [
+ { type: 'step-start', textContent: '' },
+ { type: 'text', textContent: 'Acme renews in May' },
+ ],
+ },
+ ]);
+ expect(historyResponse.body.data.chatStreamCatchupChunks).toEqual({
+ chunks: [],
+ maxSeq: 0,
+ });
+ });
+
+ it('reads a conversation before its first run as empty', async () => {
+ const response = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({
+ agentUniversalIdentifier,
+ threadKey: randomUUID(),
+ }),
+ applicationToken,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.chatMessages).toEqual([]);
+ });
+
+ it('refuses the conversations of an agent of another application', async () => {
+ const response = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({
+ agentUniversalIdentifier: otherApplicationAgentUniversalIdentifier,
+ threadKey: randomUUID(),
+ }),
+ applicationToken,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');
+ });
+
+ it('refuses a thread id together with a key', async () => {
+ const response = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({
+ threadId: randomUUID(),
+ agentUniversalIdentifier,
+ threadKey: randomUUID(),
+ }),
+ applicationToken,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ });
+
+ it('refuses a thread id from an application without a member', async () => {
+ const response = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({ threadId: randomUUID() }),
+ applicationToken,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ });
+
+ it('refuses a conversation named by key from a member session', async () => {
+ const response = await makeMetadataApiRequest(
+ agentConversationHistoryQueryFactory({
+ agentUniversalIdentifier,
+ threadKey: randomUUID(),
+ }),
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ });
+});
diff --git a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
index 91baa39be91..73453dd96d3 100644
--- a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
@@ -24,7 +24,9 @@ import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-q
import { type PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';
import { fromWorkspaceEntityToFlat } from 'src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { RUN_AGENT_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/run-agent-job-name.constant';
import { type AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';
+import { type AgentRunSettlementService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-settlement.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';
import { AGENT_CHAT_WAITING_RUN_OWNER_TYPE } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-waiting-run-owner-type.constant';
@@ -35,6 +37,7 @@ import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-c
import { type AgentChatWaitingRunService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-waiting-run.service';
import { type RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';
import { type StreamAgentChatJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat-job.types';
+import { AGENT_TURN_INTERRUPTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-interrupted-error.constant';
import { type AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
import { type AgentTriggerRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
@@ -666,6 +669,55 @@ describe('agent runs that wait (integration)', () => {
expect(runTurn).toHaveBeenCalledTimes(2);
});
+ it('settles a run whose worker died when its job comes back, without running the agent again', async () => {
+ const runTurn = mockAgent(replyingResult);
+ const aiQueue = global.app.get<MessageQueueService>(
+ getQueueToken(MessageQueue.aiQueue),
+ );
+ const enqueueRun = jest.spyOn(aiQueue, 'add');
+ const runOnThread = await buildRunOnThread({ waitForCompletion: false });
+
+ const { threadId, runId } = await runOnThread('Follow up tomorrow');
+
+ try {
+ await expectEventually(async () => {
+ expect(await findTurnStatuses(threadId)).toEqual(['completed']);
+ });
+
+ const [[, runJobData, runJobOptions]] = enqueueRun.mock.calls.filter(
+ ([jobName]) => jobName === RUN_AGENT_JOB_NAME,
+ );
+
+ await global.testDataSource.query(
+ `UPDATE "${schema}"."agentTurn" SET status = 'running', "endedAt" = NULL WHERE id = $1`,
+ [runId],
+ );
+ await getAppProviderByClassName<AgentChatStreamHeartbeatService>(
+ 'AgentChatStreamHeartbeatService',
+ ).clear(await holdConversation(threadId));
+
+ await aiQueue.add(RUN_AGENT_JOB_NAME, runJobData, runJobOptions);
+
+ await expectEventually(async () => {
+ expect(
+ await getAppProviderByClassName<AgentRunSettlementService>(
+ 'AgentRunSettlementService',
+ ).waitFor({ runId, timeoutMs: 1000 }),
+ ).toMatchObject({
+ status: 'FAILED',
+ error: AGENT_TURN_INTERRUPTED_ERROR.message,
+ });
+ });
+ expect(await findTurnStatuses(threadId)).toEqual(['failed']);
+ expect(await findUserMessageTexts(threadId)).toEqual([
+ 'Follow up tomorrow',
+ ]);
+ expect(runTurn).toHaveBeenCalledTimes(1);
+ } finally {
+ await destroyAgentChatThread({ threadId });
+ }
+ });
+
it('sends the messages a member queued before a run that started waiting after them', async () => {
const runTurn = mockAgent(replyingResult);
const threadKey = `lead:${randomUUID()}`;
diff --git a/packages/twenty-server/test/integration/ai/suites/ai-generate-stream.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/ai-generate-stream.integration-spec.ts
new file mode 100644
index 00000000000..5757c8b0f72
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/suites/ai-generate-stream.integration-spec.ts
@@ -0,0 +1,249 @@
+import { randomUUID } from 'node:crypto';
+
+import { followAgentRunEventsOrThrow } from 'test/integration/ai/utils/follow-agent-run-events.util';
+import { generateQueryFactory } from 'test/integration/ai/utils/generate-query-factory.util';
+import {
+ answerWith,
+ mockScriptedAiModel,
+} from 'test/integration/ai/utils/mock-scripted-ai-model.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import { isAgentChatTurnEndEvent } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+const INPUT = [{ role: 'user' as const, content: 'Qualify Acme' }];
+const GENERATE_TIMEOUT_MS = 30_000;
+const STREAM_WAIT_TIMEOUT_MS = 10_000;
+
+const setupApplicationWithToken = async (name: string) => {
+ const application = await setupApplicationWithResources({ name });
+ const { applicationAccessToken } = await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ });
+
+ return { application, token: applicationAccessToken.token };
+};
+
+const waitForOrThrow = async (isDone: () => boolean) => {
+ const startedAt = Date.now();
+
+ while (!isDone()) {
+ if (Date.now() - startedAt > STREAM_WAIT_TIMEOUT_MS) {
+ throw new Error('Timed out waiting for the run stream');
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+};
+
+describe('ai.generate runs followed by their application (integration)', () => {
+ let application: ApplicationWithResources;
+ let token: string;
+ let otherApplication: ApplicationWithResources;
+ let otherToken: string;
+
+ beforeAll(async () => {
+ // one after the other, since each setup switches Jest's process-wide timer mode
+ ({ application, token } = await setupApplicationWithToken(
+ 'Generate Stream Probe',
+ ));
+ ({ application: otherApplication, token: otherToken } =
+ await setupApplicationWithToken('Generate Stream Other Probe'));
+ }, 120000);
+
+ // setupApplicationWithResources leaves fake timers on, which would freeze every wait below
+ beforeEach(() => jest.useRealTimers());
+
+ afterEach(() => jest.restoreAllMocks());
+
+ afterAll(async () => {
+ await Promise.all(
+ [application, otherApplication]
+ .filter(isDefined)
+ .map(({ universalIdentifier }) =>
+ cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: universalIdentifier,
+ }),
+ ),
+ );
+ });
+
+ it('streams a run to its application under the run id it chose, and to no other application', async () => {
+ const runId = randomUUID();
+ const streams: Awaited<ReturnType<typeof followAgentRunEventsOrThrow>>[] =
+ [];
+
+ try {
+ const ownStream = await followAgentRunEventsOrThrow({ runId, token });
+
+ streams.push(ownStream);
+
+ const otherStream = await followAgentRunEventsOrThrow({
+ runId,
+ token: otherToken,
+ });
+
+ streams.push(otherStream);
+
+ await waitForOrThrow(
+ () => ownStream.events.length > 0 && otherStream.events.length > 0,
+ );
+ mockScriptedAiModel(() => answerWith('Acme looks like a fit'));
+
+ const response = await makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId }),
+ token,
+ ).timeout(GENERATE_TIMEOUT_MS);
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.generate).toMatchObject({
+ success: true,
+ text: 'Acme looks like a fit',
+ runId,
+ });
+
+ await waitForOrThrow(() =>
+ ownStream.events.some(isAgentChatTurnEndEvent),
+ );
+
+ const chunks = ownStream.events.flatMap((event) =>
+ event.type === 'stream-chunk' ? [event.chunk] : [],
+ );
+
+ expect(chunks[0]).toMatchObject({ type: 'start' });
+ expect(
+ chunks
+ .filter(({ type }) => type === 'text-delta')
+ .map(({ delta }) => delta)
+ .join(''),
+ ).toBe('Acme looks like a fit');
+ expect(ownStream.events.find(isAgentChatTurnEndEvent)).toMatchObject({
+ type: 'run-finished',
+ });
+
+ // the server's one Redis subscriber relays both channels in publish order, so a keepalive the
+ // other stream gets after the run ended comes after anything the run published
+ const otherEventCountAtRunEnd = otherStream.events.length;
+
+ await waitForOrThrow(
+ () => otherStream.events.length > otherEventCountAtRunEnd,
+ );
+ } finally {
+ await Promise.all(streams.map((stream) => stream.close()));
+ }
+
+ const [ownStream, otherStream] = streams;
+
+ expect(ownStream.errors).toEqual([]);
+ expect(otherStream.errors).toEqual([]);
+ expect(otherStream.events.every(({ type }) => type === 'keepalive')).toBe(
+ true,
+ );
+ });
+
+ it('streams a run started with a member-bound token of the application to the same channel', async () => {
+ const runId = randomUUID();
+ const { applicationAccessToken: memberBoundToken } =
+ await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ userId: USER_DATA_SEED_IDS.JANE,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ });
+ const stream = await followAgentRunEventsOrThrow({
+ runId,
+ token: memberBoundToken.token,
+ });
+
+ try {
+ await waitForOrThrow(() => stream.events.length > 0);
+ mockScriptedAiModel(() => answerWith('Acme looks like a fit'));
+
+ const response = await makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId }),
+ memberBoundToken.token,
+ ).timeout(GENERATE_TIMEOUT_MS);
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.generate).toMatchObject({
+ success: true,
+ runId,
+ });
+
+ await waitForOrThrow(() => stream.events.some(isAgentChatTurnEndEvent));
+ } finally {
+ await stream.close();
+ }
+
+ expect(stream.errors).toEqual([]);
+ expect(
+ stream.events.some(
+ (event) =>
+ event.type === 'stream-chunk' && event.chunk.type === 'text-delta',
+ ),
+ ).toBe(true);
+ });
+
+ it('refuses a run id that is already used', async () => {
+ const runId = randomUUID();
+
+ mockScriptedAiModel(() => answerWith('Done'));
+
+ const firstResponse = await makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId }),
+ token,
+ );
+
+ expect(firstResponse.body.data.generate.runId).toBe(runId);
+
+ const secondResponse = await makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId }),
+ token,
+ );
+
+ expect(secondResponse.body.errors[0].extensions.code).toBe(
+ 'BAD_USER_INPUT',
+ );
+ });
+
+ it('runs only one of two concurrent calls with the same run id', async () => {
+ const runId = randomUUID();
+
+ mockScriptedAiModel(() => answerWith('Done'));
+
+ const responses = await Promise.all(
+ [1, 2].map(() =>
+ makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId }),
+ token,
+ ),
+ ),
+ );
+
+ expect(
+ responses.map(({ body }) =>
+ isDefined(body.errors)
+ ? body.errors[0].extensions.code
+ : body.data.generate.runId,
+ ),
+ ).toEqual(expect.arrayContaining([runId, 'BAD_USER_INPUT']));
+ });
+
+ it('refuses a run id from a member session', async () => {
+ const response = await makeMetadataApiRequest(
+ generateQueryFactory({ input: INPUT, runId: randomUUID() }),
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ });
+});
diff --git a/packages/twenty-server/test/integration/ai/suites/ai-generate.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/ai-generate.integration-spec.ts
new file mode 100644
index 00000000000..0a253c55c72
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/suites/ai-generate.integration-spec.ts
@@ -0,0 +1,209 @@
+import { APICallError } from '@ai-sdk/provider';
+import {
+ generateQueryFactory,
+ type GenerateTestInput,
+} from 'test/integration/ai/utils/generate-query-factory.util';
+import {
+ answerWith,
+ mockScriptedAiModel,
+ SCRIPTED_MODEL_USAGE,
+} from 'test/integration/ai/utils/mock-scripted-ai-model.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type ScriptedModelResponse } from 'test/utils/scripted-model-response.type';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const DATA_TOOL_NAME_PATTERN =
+ /^(find_many|find_one|group_by|create_one|create_many|update_one|update_many|delete_one|delete_many|upsert_many|merge_many)_/;
+
+const failWith = (message: string): ScriptedModelResponse => ({
+ ...answerWith(''),
+ streamError: new APICallError({
+ message,
+ url: 'https://provider.test',
+ requestBodyValues: {},
+ statusCode: 400,
+ }),
+});
+
+const generate = async (input: GenerateTestInput) => {
+ const response = await makeMetadataApiRequest(generateQueryFactory(input));
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.generate;
+};
+
+describe('generate mutation (integration)', () => {
+ afterEach(() => jest.restoreAllMocks());
+
+ it('returns the text of the reply with its run and usage', async () => {
+ mockScriptedAiModel(() => answerWith('Acme looks like a fit'));
+
+ expect(
+ await generate({ input: [{ role: 'user', content: 'Qualify Acme' }] }),
+ ).toEqual({
+ success: true,
+ text: 'Acme looks like a fit',
+ object: null,
+ error: null,
+ runId: expect.any(String),
+ usage: { inputTokens: 12, outputTokens: 3 },
+ });
+ });
+
+ it('returns the object of a json response format from one model call', async () => {
+ const offeredToolNamesByCall = mockScriptedAiModel(() =>
+ answerWith(JSON.stringify({ fit: true })),
+ );
+
+ const result = await generate({
+ input: [{ role: 'user', content: 'Qualify Acme' }],
+ responseFormat: {
+ type: 'json',
+ schema: { type: 'object', properties: { fit: { type: 'boolean' } } },
+ },
+ });
+
+ expect(result).toMatchObject({
+ success: true,
+ text: null,
+ object: { fit: true },
+ });
+ expect(offeredToolNamesByCall).toHaveLength(1);
+ });
+
+ it('offers the model no data tools without a scope', async () => {
+ const offeredToolNamesByCall = mockScriptedAiModel(() =>
+ answerWith('Done'),
+ );
+
+ await generate({ input: [{ role: 'user', content: 'List the people' }] });
+
+ expect(
+ offeredToolNamesByCall[0].filter((toolName) =>
+ DATA_TOOL_NAME_PATTERN.test(toolName),
+ ),
+ ).toEqual([]);
+ });
+
+ it('reports a failing model in the result instead of a GraphQL error', async () => {
+ mockScriptedAiModel(() => failWith('Invalid request'));
+
+ expect(
+ await generate({ input: [{ role: 'user', content: 'Qualify Acme' }] }),
+ ).toMatchObject({
+ success: false,
+ text: null,
+ object: null,
+ error: expect.stringContaining('Invalid request'),
+ runId: expect.any(String),
+ usage: { inputTokens: 0, outputTokens: 0 },
+ });
+ });
+
+ it('reports the usage of the steps that finished before the model failed', async () => {
+ const callMissingTool: ScriptedModelResponse = {
+ content: [
+ {
+ type: 'tool-call',
+ toolCallId: 'missing-1',
+ toolName: 'missing_tool',
+ input: '{}',
+ },
+ ],
+ finishReason: { unified: 'tool-calls', raw: undefined },
+ usage: SCRIPTED_MODEL_USAGE,
+ };
+
+ mockScriptedAiModel((callIndex) =>
+ callIndex === 0 ? callMissingTool : failWith('Invalid request'),
+ );
+
+ expect(
+ await generate({ input: [{ role: 'user', content: 'Qualify Acme' }] }),
+ ).toMatchObject({
+ success: false,
+ error: expect.stringContaining('Invalid request'),
+ runId: expect.any(String),
+ usage: { inputTokens: 12, outputTokens: 3 },
+ });
+ });
+});
+
+describe('generate mutation for an application without a default role (integration)', () => {
+ const countAgentTurns = async (): Promise<number> => {
+ const [{ count }] = await globalThis.testDataSource.query(
+ `SELECT count(*)::int AS count FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentTurn"`,
+ );
+
+ return count;
+ };
+
+ let application: ApplicationWithResources;
+ let memberBoundToken: string;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Generate Roleless Probe',
+ });
+
+ await globalThis.testDataSource.query(
+ 'UPDATE core."application" SET "defaultRoleId" = NULL WHERE id = $1',
+ [application.id],
+ );
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, ['flatApplicationMaps']);
+
+ memberBoundToken = (
+ await generateAppleAdminApplicationTokenPair({
+ applicationId: application.id,
+ })
+ ).applicationAccessToken.token;
+ }, 120000);
+
+ beforeEach(() => jest.useRealTimers());
+
+ afterEach(() => jest.restoreAllMocks());
+
+ afterAll(async () => {
+ if (isDefined(application)) {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ }
+ });
+
+ it('refuses a member-bound application rather than run with the member role alone', async () => {
+ const offeredToolNamesByCall = mockScriptedAiModel(() =>
+ answerWith('Acme looks like a fit'),
+ );
+ const turnCountBefore = await countAgentTurns();
+
+ const response = await makeMetadataApiRequest(
+ generateQueryFactory({
+ input: [{ role: 'user', content: 'Qualify Acme' }],
+ }),
+ memberBoundToken,
+ );
+
+ // the AI permission guard refuses it before the generate service's own default role check
+ expect(response.body.errors?.[0]).toMatchObject({
+ extensions: { code: 'FORBIDDEN' },
+ });
+ expect(response.body.data?.generate ?? null).toBeNull();
+ expect(offeredToolNamesByCall).toHaveLength(0);
+ expect(await countAgentTurns()).toBe(turnCountBefore);
+ });
+});
diff --git a/packages/twenty-server/test/integration/ai/utils/agent-conversation-history-query-factory.util.ts b/packages/twenty-server/test/integration/ai/utils/agent-conversation-history-query-factory.util.ts
new file mode 100644
index 00000000000..7096e84eb14
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/agent-conversation-history-query-factory.util.ts
@@ -0,0 +1,42 @@
+import gql from 'graphql-tag';
+
+type AgentConversationVariables = {
+ threadId?: string;
+ agentUniversalIdentifier?: string;
+ threadKey?: string;
+};
+
+export const agentConversationHistoryQueryFactory = (
+ variables: AgentConversationVariables,
+) => ({
+ query: gql`
+ query ConversationHistory(
+ $threadId: UUID
+ $agentUniversalIdentifier: UUID
+ $threadKey: String
+ ) {
+ chatMessages(
+ threadId: $threadId
+ agentUniversalIdentifier: $agentUniversalIdentifier
+ threadKey: $threadKey
+ ) {
+ threadId
+ turnId
+ role
+ parts {
+ type
+ textContent
+ }
+ }
+ chatStreamCatchupChunks(
+ threadId: $threadId
+ agentUniversalIdentifier: $agentUniversalIdentifier
+ threadKey: $threadKey
+ ) {
+ chunks
+ maxSeq
+ }
+ }
+ `,
+ variables,
+});
diff --git a/packages/twenty-server/test/integration/ai/utils/follow-agent-run-events.util.ts b/packages/twenty-server/test/integration/ai/utils/follow-agent-run-events.util.ts
new file mode 100644
index 00000000000..b115fb54396
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/follow-agent-run-events.util.ts
@@ -0,0 +1,120 @@
+import { type Readable } from 'node:stream';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+const CONNECT_TIMEOUT_MS = 10_000;
+const CLOSE_TIMEOUT_MS = 5_000;
+
+const ON_AGENT_RUN_EVENT_SUBSCRIPTION = `
+ subscription OnAgentRunEvent($runId: UUID!) {
+ onAgentChatEvent(runId: $runId) {
+ event
+ }
+ }
+`;
+
+export const followAgentRunEventsOrThrow = async ({
+ runId,
+ token,
+}: {
+ runId: string;
+ token: string;
+}) => {
+ const abortController = new AbortController();
+ const events: AgentChatSubscriptionEvent[] = [];
+ const errors: string[] = [];
+
+ const connectTimeout = setTimeout(
+ () => abortController.abort(),
+ CONNECT_TIMEOUT_MS,
+ );
+
+ const response = await fetch(`http://localhost:${APP_PORT}/metadata`, {
+ method: 'POST',
+ headers: {
+ Accept: 'text/event-stream',
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({
+ query: ON_AGENT_RUN_EVENT_SUBSCRIPTION,
+ variables: { runId },
+ }),
+ signal: abortController.signal,
+ }).finally(() => clearTimeout(connectTimeout));
+
+ if (!response.ok || !isDefined(response.body)) {
+ abortController.abort();
+ throw new Error(`The subscription failed with HTTP ${response.status}`);
+ }
+
+ // the integration setup swaps in node-fetch, whose body is a Node stream, not a web ReadableStream
+ const body = response.body as unknown as Readable;
+
+ const reading = (async () => {
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ try {
+ for await (const chunk of body) {
+ buffer += decoder.decode(chunk, { stream: true });
+
+ let boundary = buffer.indexOf('\n\n');
+
+ while (boundary !== -1) {
+ const data = buffer
+ .slice(0, boundary)
+ .split('\n')
+ .filter((line) => line.startsWith('data:'))
+ .map((line) => line.slice('data:'.length).trim())
+ .join('\n');
+
+ buffer = buffer.slice(boundary + 2);
+ boundary = buffer.indexOf('\n\n');
+
+ if (!isNonEmptyString(data)) {
+ continue;
+ }
+
+ const result = JSON.parse(data);
+
+ if (isDefined(result.errors)) {
+ errors.push(
+ ...result.errors.map(
+ (error: { extensions?: { code?: string }; message?: string }) =>
+ error.extensions?.code ?? error.message,
+ ),
+ );
+ } else {
+ events.push(result.data.onAgentChatEvent.event);
+ }
+ }
+ }
+ } catch (error) {
+ if (!abortController.signal.aborted) {
+ errors.push(String(error));
+ }
+ }
+ })();
+
+ return {
+ events,
+ errors,
+ // an open stream keeps the test app from shutting down, so closing must not depend on the abort alone
+ close: async () => {
+ abortController.abort();
+ body.destroy();
+
+ let closeTimeout: ReturnType<typeof setTimeout> | undefined;
+
+ await Promise.race([
+ reading,
+ new Promise((resolve) => {
+ closeTimeout = setTimeout(resolve, CLOSE_TIMEOUT_MS);
+ }),
+ ]).finally(() => clearTimeout(closeTimeout));
+ },
+ };
+};
diff --git a/packages/twenty-server/test/integration/ai/utils/generate-query-factory.util.ts b/packages/twenty-server/test/integration/ai/utils/generate-query-factory.util.ts
new file mode 100644
index 00000000000..302c6ce8cea
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/generate-query-factory.util.ts
@@ -0,0 +1,28 @@
+import gql from 'graphql-tag';
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
+import { type RunAgentMessage } from 'twenty-shared/application';
+
+import { type GenerateInputDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/generate.input';
+
+export type GenerateTestInput = Omit<GenerateInputDTO, 'input' | 'modelId'> & {
+ input: RunAgentMessage[];
+};
+
+export const generateQueryFactory = (input: GenerateTestInput) => ({
+ query: gql`
+ mutation Generate($input: GenerateInput!) {
+ generate(input: $input) {
+ success
+ text
+ object
+ error
+ runId
+ usage {
+ inputTokens
+ outputTokens
+ }
+ }
+ }
+ `,
+ variables: { input: { ...input, modelId: TEST_AI_MODEL_ID } },
+});
diff --git a/packages/twenty-server/test/integration/ai/utils/mock-scripted-ai-model.util.ts b/packages/twenty-server/test/integration/ai/utils/mock-scripted-ai-model.util.ts
new file mode 100644
index 00000000000..983ee751786
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/mock-scripted-ai-model.util.ts
@@ -0,0 +1,51 @@
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { createScriptedLanguageModel } from 'test/utils/create-scripted-language-model.util';
+import { type ScriptedModelResponse } from 'test/utils/scripted-model-response.type';
+
+import {
+ type AiModelRegistryService,
+ type RegisteredAiModel,
+} from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+
+export const SCRIPTED_MODEL_USAGE = {
+ inputTokens: {
+ total: 12,
+ noCache: 12,
+ cacheRead: undefined,
+ cacheWrite: undefined,
+ },
+ outputTokens: { total: 3, text: 3, reasoning: undefined },
+};
+
+export const answerWith = (text: string): ScriptedModelResponse => ({
+ content: [{ type: 'text', text }],
+ finishReason: { unified: 'stop', raw: undefined },
+ usage: SCRIPTED_MODEL_USAGE,
+});
+
+export const mockScriptedAiModel = (
+ respond: (callIndex: number) => ScriptedModelResponse,
+) => {
+ const offeredToolNamesByCall: string[][] = [];
+ const model = createScriptedLanguageModel((options, callIndex) => {
+ offeredToolNamesByCall.push((options.tools ?? []).map((tool) => tool.name));
+
+ return respond(callIndex);
+ });
+
+ jest
+ .spyOn(
+ getAppProviderByClassName<AiModelRegistryService>(
+ 'AiModelRegistryService',
+ ),
+ 'resolveModelForAgent',
+ )
+ .mockReturnValue({
+ modelId: TEST_AI_MODEL_ID,
+ sdkPackage: '@ai-sdk/openai',
+ model,
+ } as unknown as RegisteredAiModel);
+
+ return offeredToolNamesByCall;
+};
diff --git a/packages/twenty-server/test/integration/ai/utils/run-agent-in-conversation-query-factory.util.ts b/packages/twenty-server/test/integration/ai/utils/run-agent-in-conversation-query-factory.util.ts
new file mode 100644
index 00000000000..ab52934faba
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/run-agent-in-conversation-query-factory.util.ts
@@ -0,0 +1,28 @@
+import gql from 'graphql-tag';
+
+export const runAgentInConversationQueryFactory = ({
+ agentUniversalIdentifier,
+ content,
+ threadKey,
+}: {
+ agentUniversalIdentifier: string;
+ content: string;
+ threadKey: string;
+}) => ({
+ query: gql`
+ mutation RunAgent($input: RunAgentInput!) {
+ runAgent(input: $input) {
+ threadId
+ runId
+ status
+ }
+ }
+ `,
+ variables: {
+ input: {
+ agentUniversalIdentifier,
+ input: [{ role: 'user', content }],
+ thread: { key: threadKey },
+ },
+ },
+});
diff --git a/packages/twenty-server/test/integration/emailing/save-campaign-variable-validation.integration-spec.ts b/packages/twenty-server/test/integration/emailing/save-campaign-variable-validation.integration-spec.ts
index 5a6a4423bf0..5f145ea5e87 100644
--- a/packages/twenty-server/test/integration/emailing/save-campaign-variable-validation.integration-spec.ts
+++ b/packages/twenty-server/test/integration/emailing/save-campaign-variable-validation.integration-spec.ts
@@ -2,7 +2,6 @@ import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-th
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { type MessageCampaignDraftService } from 'src/modules/emailing/services/message-campaign-draft.service';
import { SaveCampaignToolInputZodSchema } from 'src/modules/emailing/tools/save-campaign-tool.schema';
@@ -30,7 +29,7 @@ const saveDraftWithVariables = (...variables: string[]) =>
'MessageCampaignDraftService',
).saveDraft({
workspaceId: SEED_APPLE_WORKSPACE_ID,
- userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ rolePermissionConfig: { shouldBypassPermissionChecks: true },
subject: 'Hello',
body: buildBodyWithVariables(variables),
});
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index 574589bdbb7..df9c8476045 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -75,10 +75,10 @@ exports[`endpoint permission declarations should match the auth principals, perm
"AgentChatChannelResolver.reopenAgentChatThreadInChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatChannelResolver.snoozeAgentChatThreadInChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatChannelResolver.updateAgentChatChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI","AI_SETTINGS"]}",
+ "AgentChatHistoryResolver.chatMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
+ "AgentChatHistoryResolver.chatStreamCatchupChunks {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatMessageReactionResolver.addAgentChatMessageReaction {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatMessageReactionResolver.removeAgentChatMessageReaction {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
- "AgentChatResolver.chatMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
- "AgentChatResolver.chatStreamCatchupChunks {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatResolver.chatThread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatResolver.createChatThread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatResolver.deleteQueuedChatMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
@@ -86,7 +86,7 @@ exports[`endpoint permission declarations should match the auth principals, perm
"AgentChatResolver.retryChatMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatResolver.sendChatMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatResolver.stopAgentChatStream {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
- "AgentChatSubscriptionResolver.onAgentChatEvent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
+ "AgentChatSubscriptionResolver.onAgentChatEvent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatThreadParticipantResolver.agentChatOpenThreadsSummary {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatThreadParticipantResolver.assignAgentChatThread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentChatThreadParticipantResolver.updateAgentChatThreadInboxState {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
@@ -98,6 +98,7 @@ exports[`endpoint permission declarations should match the auth principals, perm
"AgentResolver.findManyAgents {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentResolver.findOneAgent {"applicationTarget":{"argName":"input","idKey":"id","kind":"applicationOwnedEntity","metadataName":"agent","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentResolver.updateOneAgent {"applicationTarget":{"argName":"input","idKey":"id","kind":"applicationOwnedEntity","metadataName":"agent","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI","AI_SETTINGS"]}",
+ "AgentRunResolver.generate {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentRunResolver.runAgent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AgentRunsResolver.agentRuns {"applicationTarget":{"argName":"agentId","kind":"applicationOwnedEntity","metadataName":"agent","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI_SETTINGS"]}",
"AiChatUsageResolver.aiChatUsage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
diff --git a/packages/twenty-server/test/integration/graphql/suites/nested-relation-per-parent-limit.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/nested-relation-per-parent-limit.integration-spec.ts
index 82a698ccb1e..ba6d42c2142 100644
--- a/packages/twenty-server/test/integration/graphql/suites/nested-relation-per-parent-limit.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/nested-relation-per-parent-limit.integration-spec.ts
@@ -3,6 +3,7 @@ import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delet
import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
import { QUERY_MAX_RECORDS_FROM_RELATION } from 'twenty-shared/constants';
const HOT_COMPANY_ID = '20202020-ffff-4000-8000-000000000001';
@@ -110,6 +111,8 @@ describe('Nested relation per-parent limit (e2e)', () => {
});
await makeGraphqlApiRequest(destroyCompanies);
+ // a shard's last suite has no next suite to drain the jobs its cleanup starts
+ await waitForAllJobsToFinish();
});
it('caps a hot parent at the per-parent limit without starving siblings', async () => {
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts
index b121d39700d..3bdfa37b5f9 100644
--- a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts
@@ -467,4 +467,48 @@ describe('Agent run conversation should be recorded for the caller', () => {
).toContain(WORKSPACE_MEMBER_DATA_SEED_IDS.JANE);
expect(partTypes.filter((type) => type === 'tool-probe')).toHaveLength(2);
});
+
+ it('should show the application the tool output of a turn it ran as a member, and another member only its text', async () => {
+ const threadKey = randomUUID();
+
+ await runAgent({
+ token: globalTestContext.applicationToken,
+ threadKey,
+ runAsWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ steps: TOOL_CALL_STEPS,
+ });
+
+ const readPartTypes = async (token: string) => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: parse(
+ 'query($agentUniversalIdentifier: UUID!, $threadKey: String!) { chatMessages(agentUniversalIdentifier: $agentUniversalIdentifier, threadKey: $threadKey) { parts { type } } }',
+ ),
+ variables: {
+ agentUniversalIdentifier:
+ globalTestContext.agentUniversalIdentifier,
+ threadKey,
+ },
+ },
+ token,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return (
+ response.body.data.chatMessages as { parts: { type: string }[] }[]
+ ).flatMap(({ parts }) => parts.map(({ type }) => type));
+ };
+
+ expect(await readPartTypes(globalTestContext.applicationToken)).toContain(
+ 'tool-probe',
+ );
+
+ const partTypesForJane = await readPartTypes(
+ globalTestContext.janeApplicationToken,
+ );
+
+ expect(partTypesForJane).toContain('text');
+ expect(partTypesForJane).not.toContain('tool-probe');
+ });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
index e0a3cd8d3f3..6f95702bccd 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
@@ -1,21 +1,31 @@
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
import {
activateCoreWorkflowVersion,
+ coreWorkflowGraphqlRequest,
createCoreWorkflow,
createCoreWorkflowVersionStep,
createDraftFromCoreWorkflowVersion,
deleteCoreWorkflows,
findCoreWorkflowVersion,
+ updateCoreWorkflowVersionStep,
updateCoreWorkflowVersionTrigger,
} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';
+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';
+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';
+import { findOneAgent } from 'test/integration/metadata/suites/agent/utils/find-one-agent.util';
type AiAgentStep = {
id: string;
type: string;
- settings: { input: { agentId: string } };
+ name?: string;
+ settings: {
+ input: { agentId?: string; instructions?: string; prompt?: string };
+ outputSchema?: Record<string, unknown>;
+ };
};
describe('Draft creation (e2e)', () => {
- it('gives AI agent steps their own copy of the agent', async () => {
+ it('keeps the config of an AI agent step in the draft, with no agent to copy', async () => {
const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
name: 'Draft Step Resources Test',
});
@@ -31,10 +41,26 @@ describe('Draft creation (e2e)', () => {
},
});
- const agentStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ const createdAgentStep = await createCoreWorkflowVersionStep<AiAgentStep>({
coreWorkflowVersionId,
stepType: 'AI_AGENT',
});
+ const agentStep = {
+ ...createdAgentStep,
+ settings: {
+ ...createdAgentStep.settings,
+ input: {
+ ...createdAgentStep.settings.input,
+ instructions: 'You qualify leads.',
+ prompt: 'Qualify the new lead.',
+ },
+ },
+ };
+
+ await updateCoreWorkflowVersionStep({
+ coreWorkflowVersionId,
+ step: agentStep,
+ });
await activateCoreWorkflowVersion({ coreWorkflowVersionId });
@@ -47,11 +73,185 @@ describe('Draft creation (e2e)', () => {
coreWorkflowVersionId: draft.id,
});
- const draftAgentId = steps?.find((step) => step.id === agentStep.id)
- ?.settings.input.agentId;
+ const draftAgentStep = steps?.find((step) => step.id === agentStep.id);
+
+ expect(draftAgentStep?.settings.input).toEqual(agentStep.settings.input);
+ expect(draftAgentStep?.settings.input).not.toHaveProperty('agentId');
+
+ await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
+ });
+});
+
+describe('AI agent step duplication and deletion (e2e)', () => {
+ it('creates a step that runs a reusable agent, copies a duplicated step, and never copies or deletes the agent', async () => {
+ const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
+ name: 'AI Step Duplication Test',
+ });
+ const { data: agentData } = await createOneAgent({
+ expectToFail: false,
+ input: {
+ label: 'Reusable Step Agent',
+ prompt: 'You qualify leads.',
+ modelId: TEST_AI_MODEL_ID,
+ responseFormat: {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { score: { type: 'number' } },
+ },
+ },
+ },
+ });
+ const reusableAgentId = agentData.createOneAgent.id;
+
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId,
+ trigger: {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+ },
+ });
+
+ const createAiAgentStep = async (
+ input: AiAgentStep['settings']['input'],
+ ) => {
+ const createdStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ coreWorkflowVersionId,
+ stepType: 'AI_AGENT',
+ });
+ const step = {
+ ...createdStep,
+ settings: { ...createdStep.settings, input },
+ };
+
+ await updateCoreWorkflowVersionStep({ coreWorkflowVersionId, step });
+
+ return step;
+ };
+
+ const duplicateStep = async (stepId: string) => {
+ const { steps: stepsBefore } = await findCoreWorkflowVersion<AiAgentStep>(
+ { coreWorkflowVersionId },
+ );
+
+ await coreWorkflowGraphqlRequest({
+ query: `
+ mutation DuplicateCoreWorkflowVersionStep(
+ $input: DuplicateCoreWorkflowVersionStepInput!
+ ) {
+ duplicateCoreWorkflowVersionStep(input: $input) {
+ stepsDiff
+ }
+ }
+ `,
+ variables: { input: { coreWorkflowVersionId, stepId } },
+ });
+
+ const { steps } = await findCoreWorkflowVersion<AiAgentStep>({
+ coreWorkflowVersionId,
+ });
+
+ return steps?.find(
+ (step) => !stepsBefore?.some((stepBefore) => stepBefore.id === step.id),
+ );
+ };
+
+ const inlineStep = await createAiAgentStep({
+ instructions: 'You qualify leads.',
+ prompt: 'Qualify the new lead.',
+ });
+ const reusableAgentStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ coreWorkflowVersionId,
+ stepType: 'AI_AGENT',
+ defaultSettings: { input: { agentId: reusableAgentId } },
+ });
+
+ expect(reusableAgentStep.name).toBe('Reusable Step Agent');
+ expect(reusableAgentStep.settings.input).toEqual({
+ agentId: reusableAgentId,
+ prompt: '',
+ });
+ expect(Object.keys(reusableAgentStep.settings.outputSchema ?? {})).toEqual([
+ 'score',
+ ]);
+
+ for (const step of [inlineStep, reusableAgentStep]) {
+ const duplicatedStep = await duplicateStep(step.id);
+
+ expect(duplicatedStep?.settings.input).toEqual(step.settings.input);
+ }
+
+ await coreWorkflowGraphqlRequest({
+ query: `
+ mutation DeleteCoreWorkflowVersionStep(
+ $input: DeleteCoreWorkflowVersionStepInput!
+ ) {
+ deleteCoreWorkflowVersionStep(input: $input) {
+ stepsDiff
+ }
+ }
+ `,
+ variables: {
+ input: { coreWorkflowVersionId, stepId: reusableAgentStep.id },
+ },
+ });
+
+ const { data: foundAgentData } = await findOneAgent({
+ expectToFail: false,
+ input: { id: reusableAgentId },
+ gqlFields: 'id',
+ });
+
+ expect(foundAgentData.findOneAgent.id).toBe(reusableAgentId);
+
+ await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
+ await deleteOneAgent({
+ expectToFail: false,
+ input: { id: reusableAgentId },
+ });
+ });
+});
+
+describe('AI agent step kind change (e2e)', () => {
+ it('refuses to switch a Generate step to an agent', async () => {
+ const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
+ name: 'AI Step Kind Change Test',
+ });
+
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId,
+ trigger: {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+ },
+ });
+
+ const generateStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ coreWorkflowVersionId,
+ stepType: 'AI_AGENT',
+ });
- expect(draftAgentId).toBeDefined();
- expect(draftAgentId).not.toBe(agentStep.settings.input.agentId);
+ await expect(
+ updateCoreWorkflowVersionStep({
+ coreWorkflowVersionId,
+ step: {
+ ...generateStep,
+ settings: {
+ ...generateStep.settings,
+ input: {
+ ...generateStep.settings.input,
+ agentId: '20202020-0000-4000-8000-000000000001',
+ },
+ },
+ },
+ }),
+ ).rejects.toThrow('Create a new step instead');
await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/system-agents-and-workflows.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/system-agents-and-workflows.integration-spec.ts
index 0fba0ecbb05..75b6a8eed2d 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/system-agents-and-workflows.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/system-agents-and-workflows.integration-spec.ts
@@ -124,7 +124,24 @@ describe('system agents and workflows (e2e)', () => {
await deleteOneAgent({ expectToFail: false, input: { id: userAgentId } });
});
- it('flags the agent created by an AI agent step as system, not the ones members create', async () => {
+ it('creates an AI agent step without a hidden agent, and never flags member agents as system', async () => {
+ const findAgentSystemFlags = async () => {
+ const { data } = await findAgents({
+ expectToFail: false,
+ input: undefined,
+ gqlFields: 'id isSystem',
+ });
+
+ return {
+ agentIds: data.findManyAgents.map((agent) => agent.id).sort(),
+ isUserAgentSystem: data.findManyAgents.find(
+ (agent) => agent.id === userAgentId,
+ )?.isSystem,
+ };
+ };
+
+ const { agentIds: agentIdsBefore } = await findAgentSystemFlags();
+
const createStepResponse = await workflowGraphqlRequest(
`
mutation CreateCoreWorkflowVersionStep(
@@ -152,23 +169,14 @@ describe('system agents and workflows (e2e)', () => {
);
expect(versionResponse.body.errors).toBeUndefined();
+ expect(
+ versionResponse.body.data.coreWorkflowVersionById.steps[0].settings.input,
+ ).toEqual({ instructions: '', prompt: '' });
- const workflowAgentId =
- versionResponse.body.data.coreWorkflowVersionById.steps[0].settings.input
- .agentId;
-
- const { data } = await findAgents({
- expectToFail: false,
- input: undefined,
- gqlFields: 'id isSystem',
- });
-
- const isSystemByAgentId = new Map(
- data.findManyAgents.map((agent) => [agent.id, agent.isSystem]),
- );
+ const { agentIds, isUserAgentSystem } = await findAgentSystemFlags();
- expect(isSystemByAgentId.get(workflowAgentId)).toBe(true);
- expect(isSystemByAgentId.get(userAgentId)).toBe(false);
+ expect(agentIds).toEqual(agentIdsBefore);
+ expect(isUserAgentSystem).toBe(false);
});
it('leaves system workflows out of the list when filtered on IS_SYSTEM', async () => {
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts
index be4065fe9b1..ebf569967ba 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts
@@ -20,19 +20,25 @@ import { upsertObjectPermissions } from 'test/integration/metadata/suites/object
import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { updateOneRole } from 'test/integration/metadata/suites/role/utils/update-one-role.util';
import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';
import { upsertPermissionFlags } from 'test/integration/metadata/suites/role-permission-flag/utils/upsert-permission-flags.util';
import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { createScriptedLanguageModel } from 'test/utils/create-scripted-language-model.util';
+import { type AiRunScope } from 'twenty-shared/ai';
import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';
import { WorkflowActionType } from 'twenty-shared/workflow';
-import { PermissionFlagType } from 'twenty-shared/constants';
+import {
+ PermissionFlagType,
+ SystemPermissionFlag,
+} from 'twenty-shared/constants';
import {
type AiModelRegistryService,
type RegisteredAiModel,
} from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
@@ -42,6 +48,9 @@ const schema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
const OBJECT_NAME = 'aiStepRunRoleRecord';
const OBJECT_PLURAL = 'aiStepRunRoleRecords';
const FIND_TOOL_NAME = 'find_many_ai_step_run_role_records';
+const HTTP_REQUEST_TOOL_NAME = 'http_request';
+const SAVE_CAMPAIGN_TOOL_NAME = 'save_campaign';
+const SCOPED_CAMPAIGN_NAME = 'Campaign saved by a scoped AI step';
const VISIBLE_RECORD_NAME = 'Visible to the member';
const HIDDEN_RECORD_NAME = 'Hidden from the member';
@@ -60,10 +69,16 @@ type ModelCall = {
toolOutputs: string[];
};
-// The model calls the find tool once, then answers, so the test sees the tools the step offers and what they return
+// The model calls a tool once, then answers, so the test sees the tools the step offers and what they return
const mockModelCallingFindTool = ({
- failsOnceMidAnswer = false,
-}: { failsOnceMidAnswer?: boolean } = {}): ModelCall[] => {
+ providerFailure,
+ toolName = FIND_TOOL_NAME,
+ toolInput = { select: ['id', 'name'] },
+}: {
+ providerFailure?: 'ONCE_MID_ANSWER' | 'EVERY_ANSWER' | 'EVERY_CALL';
+ toolName?: string;
+ toolInput?: object;
+} = {}): ModelCall[] => {
const calls: ModelCall[] = [];
const model = createScriptedLanguageModel((options) => {
calls.push({
@@ -74,23 +89,12 @@ const mockModelCallingFindTool = ({
.map((part) => JSON.stringify(part)),
});
- if (calls.length === 1) {
- return {
- content: [
- {
- type: 'tool-call',
- toolCallId: 'find-1',
- toolName: FIND_TOOL_NAME,
- input: JSON.stringify({ select: ['id', 'name'] }),
- providerMetadata: { openai: { itemId: 'find-item' } },
- },
- ],
- finishReason: { unified: 'tool-calls', raw: undefined },
- usage: USAGE,
- };
- }
+ const shouldFailThisCall =
+ providerFailure === 'EVERY_CALL' ||
+ (providerFailure === 'EVERY_ANSWER' && calls.length > 1) ||
+ (providerFailure === 'ONCE_MID_ANSWER' && calls.length === 2);
- if (failsOnceMidAnswer && calls.length === 2) {
+ if (shouldFailThisCall) {
return {
content: [{ type: 'text', text: 'Do' }],
finishReason: { unified: 'error', raw: undefined },
@@ -104,6 +108,22 @@ const mockModelCallingFindTool = ({
};
}
+ if (calls.length === 1) {
+ return {
+ content: [
+ {
+ type: 'tool-call',
+ toolCallId: 'find-1',
+ toolName,
+ input: JSON.stringify(toolInput),
+ providerMetadata: { openai: { itemId: 'find-item' } },
+ },
+ ],
+ finishReason: { unified: 'tool-calls', raw: undefined },
+ usage: USAGE,
+ };
+ }
+
return {
content: [{ type: 'text', text: 'Done' }],
finishReason: { unified: 'stop', raw: undefined },
@@ -163,7 +183,18 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
},
});
- const createAgentStepWorkflow = async (): Promise<string> => {
+ const setMemberToolAccess = (canAccessAllTools: boolean) =>
+ updateOneRole({
+ expectToFail: false,
+ input: {
+ idToUpdate: memberRoleId,
+ updatePayload: { canAccessAllTools },
+ },
+ });
+
+ const createAiStepWorkflow = async (
+ stepInput: Partial<WorkflowAiAgentAction['settings']['input']> = {},
+ ): Promise<string> => {
const { coreWorkflowId, coreWorkflowVersionId, workspaceWorkflowId } =
await createCoreWorkflow({ name: 'AI step run roles' });
@@ -176,7 +207,7 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
valid: true,
nextStepIds: [],
settings: {
- input: { agentId, prompt: 'List the records' },
+ input: { agentId, prompt: 'List the records', ...stepInput },
outputSchema: {},
errorHandlingOptions: {
retryOnFailure: { value: 0 },
@@ -223,6 +254,13 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
return coreWorkflowVersionId;
};
+ const createScopedStepWorkflow = (scope: AiRunScope) =>
+ createAiStepWorkflow({
+ agentId: undefined,
+ modelId: TEST_AI_MODEL_ID,
+ scope,
+ });
+
const runAsMemberUntilDone = async (coreWorkflowVersionId: string) => {
const workflowRunId = await runCoreWorkflowVersion({
coreWorkflowVersionId,
@@ -347,6 +385,7 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
jest.restoreAllMocks();
await setMemberRowRule([]);
await setMemberObjectAccess(true);
+ await setMemberToolAccess(true);
});
afterAll(async () => {
@@ -388,7 +427,7 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
await setMemberObjectAccess(false);
const calls = mockModelCallingFindTool();
- expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(
+ expect(await runAsMemberUntilDone(await createAiStepWorkflow())).toBe(
'COMPLETED',
);
@@ -401,7 +440,7 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
await setMemberRowRule([{ value: 'Visible' }]);
const calls = mockModelCallingFindTool();
- expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(
+ expect(await runAsMemberUntilDone(await createAiStepWorkflow())).toBe(
'COMPLETED',
);
@@ -410,6 +449,129 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
expect(calls[1].toolOutputs.join()).not.toContain(HIDDEN_RECORD_NAME);
});
+ it('withholds a tool its member may use when the step scope does not grant it', async () => {
+ const calls = mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({ canReadAllObjectRecords: true }),
+ ),
+ ).toBe('COMPLETED');
+
+ expect(calls[0].offeredToolNames).toContain(FIND_TOOL_NAME);
+ expect(calls[0].offeredToolNames).not.toContain(HTTP_REQUEST_TOOL_NAME);
+ });
+
+ it('offers a tool both its member and the step scope grant', async () => {
+ const calls = mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({
+ canReadAllObjectRecords: true,
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag[PermissionFlagType.HTTP_REQUEST_TOOL],
+ ],
+ }),
+ ),
+ ).toBe('COMPLETED');
+
+ expect(calls[0].offeredToolNames).toContain(HTTP_REQUEST_TOOL_NAME);
+ });
+
+ it('withholds a tool the step scope grants but its member may not use', async () => {
+ await setMemberToolAccess(false);
+ const calls = mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({
+ canReadAllObjectRecords: true,
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag[PermissionFlagType.HTTP_REQUEST_TOOL],
+ ],
+ }),
+ ),
+ ).toBe('COMPLETED');
+
+ expect(calls[0].offeredToolNames).toContain(FIND_TOOL_NAME);
+ expect(calls[0].offeredToolNames).not.toContain(HTTP_REQUEST_TOOL_NAME);
+ });
+
+ it('gives the step nothing beyond its member when the scope grants everything', async () => {
+ await setMemberObjectAccess(false);
+ await setMemberToolAccess(false);
+ const calls = mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ canUpdateAllSettings: true,
+ canAccessAllTools: true,
+ }),
+ ),
+ ).toBe('COMPLETED');
+
+ expect(calls[0].offeredToolNames).not.toContain(FIND_TOOL_NAME);
+ expect(calls[0].offeredToolNames).not.toContain(HTTP_REQUEST_TOOL_NAME);
+ expect(calls[1].toolOutputs.join()).not.toContain(VISIBLE_RECORD_NAME);
+ });
+
+ describe('saving a campaign draft', () => {
+ const mockModelSavingCampaign = () =>
+ mockModelCallingFindTool({
+ toolName: SAVE_CAMPAIGN_TOOL_NAME,
+ toolInput: { name: SCOPED_CAMPAIGN_NAME },
+ });
+
+ const findScopedCampaignIds = async (): Promise<string[]> =>
+ (
+ await global.testDataSource.query(
+ `SELECT id FROM "${schema}"."messageCampaign" WHERE name = $1`,
+ [SCOPED_CAMPAIGN_NAME],
+ )
+ ).map(({ id }: { id: string }) => id);
+
+ afterEach(async () => {
+ await global.testDataSource.query(
+ `DELETE FROM "${schema}"."messageCampaign" WHERE name = $1`,
+ [SCOPED_CAMPAIGN_NAME],
+ );
+ });
+
+ it('writes no draft when the step scope grants nothing', async () => {
+ const calls = mockModelSavingCampaign();
+
+ expect(
+ await runAsMemberUntilDone(await createScopedStepWorkflow({})),
+ ).toBe('COMPLETED');
+
+ expect(calls[0].offeredToolNames).toContain(SAVE_CAMPAIGN_TOOL_NAME);
+ expect(calls[1].toolOutputs.join()).toContain('Failed to save campaign');
+ expect(await findScopedCampaignIds()).toEqual([]);
+ });
+
+ it('writes the draft when the step scope grants writing records', async () => {
+ const calls = mockModelSavingCampaign();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ }),
+ ),
+ ).toBe('COMPLETED');
+
+ expect(calls[1].toolOutputs.join()).toContain('created');
+ expect(await findScopedCampaignIds()).toHaveLength(1);
+ });
+ });
+
const findSavedReplyParts = (): Promise<
{
type: string;
@@ -430,13 +592,106 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
ORDER BY part."orderIndex"`,
);
- it('saves the step reply in the parts chat saves', async () => {
+ const findLatestAgentTurn = async (
+ turnAgentId: string | null = agentId,
+ ): Promise<{
+ id: string;
+ threadId: string | null;
+ status: AgentTurnStatus;
+ inputTokens: number | null;
+ outputTokens: number | null;
+ }> => {
+ const [turn] = await global.testDataSource.query(
+ `SELECT id, "threadId", status, "inputTokens"::float8 AS "inputTokens",
+ "outputTokens"::float8 AS "outputTokens"
+ FROM "${schema}"."agentTurn"
+ WHERE "agentId" IS NOT DISTINCT FROM $1 ORDER BY "createdAt" DESC LIMIT 1`,
+ [turnAgentId],
+ );
+
+ return turn;
+ };
+
+ it('records an Agent step without conversation settings in a conversation', async () => {
mockModelCallingFindTool();
- expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(
+ expect(await runAsMemberUntilDone(await createAiStepWorkflow())).toBe(
'COMPLETED',
);
+ expect((await findLatestAgentTurn()).threadId).not.toBeNull();
+ });
+
+ it('runs a Generate step one-shot, outside any thread', async () => {
+ mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createAiStepWorkflow({
+ agentId: undefined,
+ instructions: 'Read the records you are asked about',
+ modelId: TEST_AI_MODEL_ID,
+ }),
+ ),
+ ).toBe('COMPLETED');
+
+ const turn = await findLatestAgentTurn(null);
+
+ expect(turn).toMatchObject({
+ threadId: null,
+ status: AgentTurnStatus.COMPLETED,
+ });
+ expect(
+ await global.testDataSource.query(
+ `SELECT id FROM "${schema}"."agentMessage" WHERE "turnId" = $1`,
+ [turn.id],
+ ),
+ ).toEqual([]);
+ });
+
+ it('fails a step without a conversation when the provider keeps failing', async () => {
+ mockModelCallingFindTool({ providerFailure: 'EVERY_CALL' });
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({ canReadAllObjectRecords: true }),
+ ),
+ ).toBe('FAILED');
+
+ expect(await findLatestAgentTurn(null)).toMatchObject({
+ threadId: null,
+ status: AgentTurnStatus.FAILED,
+ });
+ });
+
+ it('keeps the usage of the steps a failed run without a conversation spent', async () => {
+ mockModelCallingFindTool({ providerFailure: 'EVERY_ANSWER' });
+
+ expect(
+ await runAsMemberUntilDone(
+ await createScopedStepWorkflow({ canReadAllObjectRecords: true }),
+ ),
+ ).toBe('FAILED');
+
+ const turn = await findLatestAgentTurn(null);
+
+ expect(turn).toMatchObject({
+ threadId: null,
+ status: AgentTurnStatus.FAILED,
+ });
+ expect(turn.inputTokens).toBeGreaterThan(0);
+ expect(turn.outputTokens).toBeGreaterThan(0);
+ });
+
+ it('saves the step reply in the parts chat saves', async () => {
+ mockModelCallingFindTool();
+
+ expect(
+ await runAsMemberUntilDone(
+ await createAiStepWorkflow({ conversation: { scope: 'STEP' } }),
+ ),
+ ).toBe('COMPLETED');
+
expect(await findSavedReplyParts()).toMatchObject([
{ type: 'step-start' },
{
@@ -451,11 +706,15 @@ describe('workflow AI step when a member runs a workspace-owned workflow (integr
});
it('completes the step when the provider fails midway through an answer once', async () => {
- const calls = mockModelCallingFindTool({ failsOnceMidAnswer: true });
+ const calls = mockModelCallingFindTool({
+ providerFailure: 'ONCE_MID_ANSWER',
+ });
- expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(
- 'COMPLETED',
- );
+ expect(
+ await runAsMemberUntilDone(
+ await createAiStepWorkflow({ conversation: { scope: 'STEP' } }),
+ ),
+ ).toBe('COMPLETED');
expect(calls).toHaveLength(3);
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
index 1103ba84997..6b6fa351c99 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
@@ -19,6 +19,7 @@ import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/
import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { type AgentCallerConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service';
import { type ToolCallAnswerRecorderService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer-recorder.service';
+import { type WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { type WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
@@ -267,6 +268,13 @@ describe('Send chat message workflow step', () => {
workflowRunId,
workspaceId: SEED_APPLE_WORKSPACE_ID,
});
+ const permissions =
+ await getAppProviderByClassName<WorkflowExecutionContextService>(
+ 'WorkflowExecutionContextService',
+ ).getExecutionContext({
+ workflowRunId,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
postAgain = () =>
getAppProviderByClassName<AgentCallerConversationService>(
@@ -284,10 +292,7 @@ describe('Send chat message workflow step', () => {
fallbackThreadKey: `${workflowRunId}:${workflowRunId}:${stepId}`,
awaitedToolCall: {
...toolCall,
- caller: {
- type: 'WORKFLOW_STEP',
- ref: { workflowRunId, stepId },
- },
+ permissions,
// the message was already written, so the call is not built again
waitOnAnswer: async () => {},
},
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
index be776d17560..a0c644c3868 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
@@ -1,3 +1,4 @@
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
import {
activateCoreWorkflowVersion,
createCoreWorkflow,
@@ -61,6 +62,7 @@ import {
TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
type ViewManifest,
type WorkflowManifest,
+ type WorkflowStepManifest,
} from 'twenty-shared/application';
import {
PermissionFlagType,
@@ -85,6 +87,7 @@ import {
WidgetType,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES } from 'twenty-shared/workflow';
import { version as getUuidVersion, v4 } from 'uuid';
import { type ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
@@ -2247,6 +2250,13 @@ const DIGEST_AGENT_ID = '7e3d1c2b-0303-4a7b-8c9d-0e1f2a3b4c5d';
const DIGEST_CRON_TRIGGER_ID = '7e3d1c2b-0304-4a7b-8c9d-0e1f2a3b4c5d';
const DIGEST_EVENT_TRIGGER_ID = '7e3d1c2b-0305-4a7b-8c9d-0e1f2a3b4c5d';
const TRIAGE_SKILL_ID = '7e3d1c2b-0306-4a7b-8c9d-0e1f2a3b4c5d';
+const AI_TICKET_OBJECT_ID = '7e3d1c2b-0307-4a7b-8c9d-0e1f2a3b4c5d';
+const AI_TICKET_PRIORITY_FIELD_ID = '7e3d1c2b-0308-4a7b-8c9d-0e1f2a3b4c5d';
+const AI_STEPS_WORKFLOW_ID = '7e3d1c2b-0309-4a7b-8c9d-0e1f2a3b4c5d';
+const AI_STEPS_TRIGGER_ID = '7e3d1c2b-0310-4a7b-8c9d-0e1f2a3b4c5d';
+const GENERATE_STEP_ID = '7e3d1c2b-0311-4a7b-8c9d-0e1f2a3b4c5d';
+const AGENT_STEP_ID = '7e3d1c2b-0312-4a7b-8c9d-0e1f2a3b4c5d';
+const UNKNOWN_OBJECT_ID = '7e3d1c2b-0313-4a7b-8c9d-0e1f2a3b4c5d';
const EXPORTED_AGENTS: AgentManifest[] = [
{
@@ -2301,24 +2311,137 @@ const EXPORTED_SKILLS: SkillManifest[] = [
},
];
-const aiManifest = buildBaseManifest({
- appId: AI_TEST_APP_ID,
- roleId: AI_TEST_ROLE_ID,
- overrides: {
- roles: [
- {
- universalIdentifier: AI_TEST_ROLE_ID,
- label: 'Test Role',
- description: 'A test role',
- canBeAssignedToAgents: true,
+type AiAgentStepManifest = Extract<WorkflowStepManifest, { type: 'AI_AGENT' }>;
+
+const GENERATE_STEP: AiAgentStepManifest = {
+ universalIdentifier: GENERATE_STEP_ID,
+ name: 'Rate the ticket',
+ type: 'AI_AGENT',
+ nextStepIds: [AGENT_STEP_ID],
+ input: {
+ prompt: 'Rate the priority of the new ticket',
+ instructions: 'You rate support tickets from low to urgent.',
+ modelId: TEST_AI_MODEL_ID,
+ modelConfiguration: { webSearch: { enabled: false } },
+ responseFormat: {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: {
+ priority: { type: 'string', description: 'The rated priority' },
+ },
+ required: ['priority'],
+ additionalProperties: false,
},
- ],
- agents: EXPORTED_AGENTS,
- skills: EXPORTED_SKILLS,
+ },
+ scope: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: AI_TICKET_OBJECT_ID,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ {
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company,
+ canReadObjectRecords: true,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: AI_TICKET_OBJECT_ID,
+ fieldUniversalIdentifier: AI_TICKET_PRIORITY_FIELD_ID,
+ canReadFieldValue: true,
+ canUpdateFieldValue: false,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag[PermissionFlagType.SEND_EMAIL_TOOL],
+ ],
+ },
},
-});
+};
+
+const AGENT_STEP: AiAgentStepManifest = {
+ universalIdentifier: AGENT_STEP_ID,
+ name: 'Triage with the support lead',
+ type: 'AI_AGENT',
+ nextStepIds: [],
+ input: {
+ agentUniversalIdentifier: TRIAGE_AGENT_ID,
+ prompt: 'Assign the new ticket to the right team',
+ humanInputInstructions: 'Ask the support lead when no team fits',
+ },
+};
+
+const AI_STEPS_WORKFLOW: WorkflowManifest = {
+ universalIdentifier: AI_STEPS_WORKFLOW_ID,
+ name: 'Triage new tickets',
+ version: {
+ trigger: {
+ universalIdentifier: AI_STEPS_TRIGGER_ID,
+ type: 'MANUAL',
+ nextStepIds: [GENERATE_STEP_ID],
+ },
+ steps: [GENERATE_STEP, AGENT_STEP],
+ },
+};
-describe('Application export - agents and skills', () => {
+const buildAiManifest = (aiSteps: AiAgentStepManifest[]) =>
+ buildBaseManifest({
+ appId: AI_TEST_APP_ID,
+ roleId: AI_TEST_ROLE_ID,
+ overrides: {
+ roles: [
+ {
+ universalIdentifier: AI_TEST_ROLE_ID,
+ label: 'Test Role',
+ description: 'A test role',
+ canBeAssignedToAgents: true,
+ },
+ ],
+ objects: [
+ buildDefaultObjectManifest({
+ universalIdentifier: AI_TICKET_OBJECT_ID,
+ nameSingular: 'exportAiTicket',
+ namePlural: 'exportAiTickets',
+ labelSingular: 'Ticket',
+ labelPlural: 'Tickets',
+ applicationUniversalIdentifier: AI_TEST_APP_ID,
+ additionalFields: [
+ {
+ universalIdentifier: AI_TICKET_PRIORITY_FIELD_ID,
+ name: 'priority',
+ label: 'Priority',
+ type: FieldMetadataType.TEXT,
+ },
+ ],
+ }),
+ ],
+ agents: EXPORTED_AGENTS,
+ skills: EXPORTED_SKILLS,
+ workflows: [
+ {
+ ...AI_STEPS_WORKFLOW,
+ version: { ...AI_STEPS_WORKFLOW.version, steps: aiSteps },
+ },
+ ],
+ },
+ });
+
+const aiManifest = buildAiManifest([GENERATE_STEP, AGENT_STEP]);
+
+const findAiSyncDryRunError = async (aiSteps: AiAgentStepManifest[]) => {
+ const { errors } = await syncApplication({
+ manifest: buildAiManifest(aiSteps),
+ dryRun: true,
+ expectToFail: true,
+ });
+
+ return errors?.[0]?.message;
+};
+
+describe('Application export - agents, skills and AI workflow steps', () => {
beforeAll(async () => {
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: AI_TEST_APP_ID,
@@ -2355,11 +2478,13 @@ describe('Application export - agents and skills', () => {
expect(exportedManifest.agents).toEqual(EXPORTED_AGENTS);
expect(exportedManifest.skills).toEqual(EXPORTED_SKILLS);
+ expect(exportedManifest.workflows).toEqual([AI_STEPS_WORKFLOW]);
for (const universalIdentifier of [
TRIAGE_AGENT_ID,
DIGEST_AGENT_ID,
TRIAGE_SKILL_ID,
+ AI_STEPS_WORKFLOW_ID,
getRoleTargetUniversalIdentifier({
applicationUniversalIdentifier: AI_TEST_APP_ID,
agentUniversalIdentifier: TRIAGE_AGENT_ID,
@@ -2387,4 +2512,82 @@ describe('Application export - agents and skills', () => {
expect(dryRun.errors).toBeUndefined();
expect(dryRun.data.syncApplication.actions).toEqual([]);
}, 60000);
+
+ it('installs a step with its own config and a step on an agent of the same application', async () => {
+ const [{ steps }] = await globalThis.testDataSource.query(
+ `SELECT version.steps FROM core."workflowVersion" version
+ JOIN core."workflow" workflow ON workflow.id = version."coreWorkflowId"
+ WHERE workflow."workspaceId" = $1 AND workflow."universalIdentifier" = $2`,
+ [SEED_APPLE_WORKSPACE_ID, AI_STEPS_WORKFLOW_ID],
+ );
+ const [{ id: triageAgentId }] = await globalThis.testDataSource.query(
+ `SELECT agent.id FROM core."agent" agent
+ JOIN core."application" application ON application.id = agent."applicationId"
+ WHERE application."universalIdentifier" = $1 AND agent."universalIdentifier" = $2`,
+ [AI_TEST_APP_ID, TRIAGE_AGENT_ID],
+ );
+ const {
+ agentUniversalIdentifier: _agentUniversalIdentifier,
+ ...agentStepInput
+ } = AGENT_STEP.input;
+
+ expect(
+ steps.map(
+ ({ settings }: { settings: { input: object } }) => settings.input,
+ ),
+ ).toEqual([
+ GENERATE_STEP.input,
+ { ...agentStepInput, agentId: triageAgentId },
+ ]);
+ }, 60000);
+
+ it('refuses a step on an agent that also carries its own instructions', async () => {
+ expect(
+ await findAiSyncDryRunError([
+ GENERATE_STEP,
+ {
+ ...AGENT_STEP,
+ input: { ...AGENT_STEP.input, instructions: 'Route by product' },
+ },
+ ]),
+ ).toContain(
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.AGENT_STEP_HAS_INLINE_CONFIG,
+ );
+ }, 60000);
+
+ it('refuses a step without an agent that keeps a conversation', async () => {
+ expect(
+ await findAiSyncDryRunError([
+ {
+ ...GENERATE_STEP,
+ input: { ...GENERATE_STEP.input, conversation: { scope: 'RUN' } },
+ },
+ AGENT_STEP,
+ ]),
+ ).toContain(
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.GENERATE_STEP_HAS_CONVERSATION_CONFIG,
+ );
+ }, 60000);
+
+ it('refuses a step scope naming an object the workspace does not have', async () => {
+ expect(
+ await findAiSyncDryRunError([
+ {
+ ...GENERATE_STEP,
+ input: {
+ ...GENERATE_STEP.input,
+ scope: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: UNKNOWN_OBJECT_ID,
+ canReadObjectRecords: true,
+ },
+ ],
+ },
+ },
+ },
+ AGENT_STEP,
+ ]),
+ ).toContain(`missing object ${UNKNOWN_OBJECT_ID}`);
+ }, 60000);
});
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-56-workspace-command-1793697418665-inline-workflow-step-agents.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-56-workspace-command-1793697418665-inline-workflow-step-agents.integration-spec.ts
new file mode 100644
index 00000000000..45520974159
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-56-workspace-command-1793697418665-inline-workflow-step-agents.integration-spec.ts
@@ -0,0 +1,647 @@
+import { randomUUID } from 'node:crypto';
+
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
+import {
+ activateCoreWorkflowVersion,
+ createCoreWorkflow,
+ createCoreWorkflowVersionStep,
+ deleteCoreWorkflows,
+ deleteLegacyWorkspaceWorkflowRecords,
+ linkCoreWorkflowToLegacyWorkspaceIds,
+ runCoreWorkflowVersion,
+ updateCoreWorkflowVersionTrigger,
+} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';
+import { waitForWorkflowCompletion } from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';
+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';
+import { updateOneAgent } from 'test/integration/metadata/suites/agent/utils/update-one-agent.util';
+import { upsertFieldPermissions } from 'test/integration/metadata/suites/field-permission/utils/upsert-field-permissions.util';
+import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';
+import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
+import { upsertPermissionFlags } from 'test/integration/metadata/suites/role-permission-flag/utils/upsert-permission-flags.util';
+import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { createScriptedLanguageModel } from 'test/utils/create-scripted-language-model.util';
+import {
+ type AgentResponseFormat,
+ type AiRunScope,
+ type ModelConfiguration,
+} from 'twenty-shared/ai';
+import {
+ PermissionFlagType,
+ SystemPermissionFlag,
+} from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type InlineWorkflowStepAgentsCommand } from 'src/database/commands/upgrade-version-command/2-56/2-56-workspace-command-1793697418665-inline-workflow-step-agents.command';
+import {
+ type AiModelRegistryService,
+ type RegisteredAiModel,
+} from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+import { type AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const COMPANY = STANDARD_OBJECTS.company;
+
+const MANUAL_TRIGGER = {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+};
+
+const STEP_NAME = 'Summarize the company';
+const STEP_PROMPT = 'Summarize the company you were given';
+
+const STEP_AGENT_INSTRUCTIONS = 'You write short company summaries.';
+
+const STEP_AGENT_MODEL_CONFIGURATION: ModelConfiguration = {
+ webSearch: { enabled: false },
+};
+
+const STEP_AGENT_RESPONSE_FORMAT: AgentResponseFormat = {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: { summary: { type: 'string', description: 'The summary' } },
+ required: ['summary'],
+ additionalProperties: false,
+ },
+};
+
+const STEP_AGENT_ROLE_SCOPE: AiRunScope = {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: COMPANY.universalIdentifier,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: COMPANY.universalIdentifier,
+ fieldUniversalIdentifier:
+ COMPANY.fields.annualRevenue.universalIdentifier,
+ canReadFieldValue: false,
+ canUpdateFieldValue: false,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag[PermissionFlagType.HTTP_REQUEST_TOOL],
+ ],
+};
+
+const USAGE = {
+ inputTokens: {
+ total: 1,
+ noCache: 1,
+ cacheRead: undefined,
+ cacheWrite: undefined,
+ },
+ outputTokens: { total: 1, text: 1, reasoning: undefined },
+};
+
+type AiAgentStep = {
+ id: string;
+ type: string;
+ name?: string;
+ settings: { input: Record<string, unknown> } & Record<string, unknown>;
+} & Record<string, unknown>;
+
+type LegacyAiStepWorkflow = {
+ coreWorkflowId: string;
+ coreWorkflowVersionId: string;
+ workspaceWorkflowId: string;
+ workspaceWorkflowVersionId: string;
+ step: AiAgentStep;
+ agentId: string;
+};
+
+type ModelCall = {
+ systemPrompt: string;
+ offeredToolNames: string[];
+};
+
+const inlineStepAgentOf = ({
+ settings: {
+ input: { agentId: _agentId, ...input },
+ ...settings
+ },
+ ...step
+}: AiAgentStep): AiAgentStep => ({
+ ...step,
+ settings: {
+ ...settings,
+ input: {
+ ...input,
+ instructions: STEP_AGENT_INSTRUCTIONS,
+ modelId: TEST_AI_MODEL_ID,
+ modelConfiguration: STEP_AGENT_MODEL_CONFIGURATION,
+ scope: STEP_AGENT_ROLE_SCOPE,
+ responseFormat: STEP_AGENT_RESPONSE_FORMAT,
+ },
+ },
+});
+
+const scriptModelAnsweringASummary = (): ModelCall[] => {
+ const calls: ModelCall[] = [];
+ const model = createScriptedLanguageModel((options) => {
+ calls.push({
+ systemPrompt: options.prompt
+ .flatMap((message) =>
+ message.role === 'system' ? [message.content] : [],
+ )
+ .join('\n'),
+ offeredToolNames: (options.tools ?? []).map((tool) => tool.name),
+ });
+
+ return {
+ content: [{ type: 'text', text: JSON.stringify({ summary: 'Done' }) }],
+ finishReason: { unified: 'stop', raw: undefined },
+ usage: USAGE,
+ };
+ });
+
+ jest
+ .spyOn(
+ getAppProviderByClassName<AiModelRegistryService>(
+ 'AiModelRegistryService',
+ ),
+ 'resolveModelForAgent',
+ )
+ .mockReturnValue({
+ modelId: TEST_AI_MODEL_ID,
+ sdkPackage: '@ai-sdk/openai',
+ model,
+ } as unknown as RegisteredAiModel);
+
+ return calls;
+};
+
+describe('2-56 workspace command - inline workflow step agents (integration)', () => {
+ let command: InlineWorkflowStepAgentsCommand;
+ let stepAgentRoleId: string;
+ const roleIds: string[] = [];
+ let generateWorkflow: LegacyAiStepWorkflow;
+ let conversationalWorkflow: LegacyAiStepWorkflow;
+ let seededSystemAgentIds: string[];
+ const coreWorkflowIds: string[] = [];
+ const workspaceWorkflowIds: string[] = [];
+ const agentIds: string[] = [];
+
+ const runCommand = () =>
+ command.runOnWorkspace({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ options: {},
+ index: 0,
+ total: 1,
+ dataSource: global.testDataSource,
+ });
+
+ const readCoreSteps = async (
+ coreWorkflowVersionId: string,
+ ): Promise<AiAgentStep[]> => {
+ const [{ steps }] = await global.testDataSource.query(
+ `SELECT steps FROM core."workflowVersion" WHERE id = $1`,
+ [coreWorkflowVersionId],
+ );
+
+ return steps;
+ };
+
+ const readWorkspaceSteps = async (
+ workspaceWorkflowVersionId: string,
+ ): Promise<AiAgentStep[]> => {
+ const [{ steps }] = await global.testDataSource.query(
+ `SELECT steps FROM ${SCHEMA}."workflowVersion" WHERE id = $1`,
+ [workspaceWorkflowVersionId],
+ );
+
+ return steps;
+ };
+
+ const readAgent = async (agentId: string): Promise<{ isSystem: boolean }> => {
+ const [agent] = await global.testDataSource.query(
+ `SELECT "isSystem" FROM core."agent" WHERE id = $1`,
+ [agentId],
+ );
+
+ return agent;
+ };
+
+ const readMigratedRows = async () => ({
+ generateCoreSteps: await readCoreSteps(
+ generateWorkflow.coreWorkflowVersionId,
+ ),
+ generateWorkspaceSteps: await readWorkspaceSteps(
+ generateWorkflow.workspaceWorkflowVersionId,
+ ),
+ conversationalCoreSteps: await readCoreSteps(
+ conversationalWorkflow.coreWorkflowVersionId,
+ ),
+ generateAgent: await readAgent(generateWorkflow.agentId),
+ conversationalAgent: await readAgent(conversationalWorkflow.agentId),
+ });
+
+ const createLegacyAiStepWorkflow = async ({
+ name,
+ stepInput,
+ }: {
+ name: string;
+ stepInput: Record<string, unknown>;
+ }): Promise<LegacyAiStepWorkflow> => {
+ const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
+ name,
+ });
+
+ coreWorkflowIds.push(coreWorkflowId);
+
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId,
+ trigger: MANUAL_TRIGGER,
+ });
+
+ const createdStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ coreWorkflowVersionId,
+ stepType: 'AI_AGENT',
+ });
+ const { data } = await createOneAgent({
+ expectToFail: false,
+ input: {
+ label: `Workflow Agent ${randomUUID().substring(0, 4)}`,
+ prompt: STEP_AGENT_INSTRUCTIONS,
+ modelId: TEST_AI_MODEL_ID,
+ modelConfiguration: STEP_AGENT_MODEL_CONFIGURATION,
+ responseFormat: STEP_AGENT_RESPONSE_FORMAT,
+ roleId: stepAgentRoleId,
+ },
+ });
+ const agentId = data.createOneAgent.id;
+
+ agentIds.push(agentId);
+
+ // the builder no longer gives a step its own hidden agent, so the legacy shape is written as it left it
+ const legacyStep: AiAgentStep = {
+ ...createdStep,
+ name: STEP_NAME,
+ settings: {
+ ...createdStep.settings,
+ input: { agentId, prompt: '', ...stepInput },
+ },
+ };
+
+ await global.testDataSource.query(
+ `UPDATE core."agent" SET "isSystem" = true WHERE id = $1`,
+ [agentId],
+ );
+ await global.testDataSource.query(
+ `UPDATE core."workflowVersion" SET steps = $2::jsonb WHERE id = $1`,
+ [coreWorkflowVersionId, JSON.stringify([legacyStep])],
+ );
+ await global.workflowTestServices.workspaceCache.invalidateAndRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatAgentMaps', 'flatWorkflowVersionMaps'],
+ );
+
+ const {
+ workspaceWorkflowId,
+ workspaceWorkflowVersionIds: [workspaceWorkflowVersionId],
+ } = await linkCoreWorkflowToLegacyWorkspaceIds({
+ coreWorkflowId,
+ withWorkspaceRecords: true,
+ });
+
+ workspaceWorkflowIds.push(workspaceWorkflowId);
+
+ const [step] = await readCoreSteps(coreWorkflowVersionId);
+
+ return {
+ coreWorkflowId,
+ coreWorkflowVersionId,
+ workspaceWorkflowId,
+ workspaceWorkflowVersionId,
+ step,
+ agentId,
+ };
+ };
+
+ beforeAll(async () => {
+ command = getAppProviderByClassName<InlineWorkflowStepAgentsCommand>(
+ 'InlineWorkflowStepAgentsCommand',
+ );
+
+ const [{ objectMetadataId, fieldMetadataId }] =
+ await global.testDataSource.query(
+ `SELECT object.id AS "objectMetadataId", field.id AS "fieldMetadataId"
+ FROM core."objectMetadata" object
+ JOIN core."fieldMetadata" field ON field."objectMetadataId" = object.id
+ WHERE object."workspaceId" = $1 AND object."universalIdentifier" = $2
+ AND field."universalIdentifier" = $3`,
+ [
+ SEED_APPLE_WORKSPACE_ID,
+ COMPANY.universalIdentifier,
+ COMPANY.fields.annualRevenue.universalIdentifier,
+ ],
+ );
+
+ const { data: roleData } = await createOneRole({
+ expectToFail: false,
+ input: {
+ label: 'Inline step agents step role',
+ description: 'The role a builder step gave its hidden agent',
+ canUpdateAllSettings: false,
+ canAccessAllTools: false,
+ canReadAllObjectRecords: false,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ canBeAssignedToUsers: false,
+ canBeAssignedToAgents: true,
+ canBeAssignedToApiKeys: false,
+ },
+ });
+
+ stepAgentRoleId = roleData.createOneRole.id;
+ roleIds.push(stepAgentRoleId);
+
+ await upsertObjectPermissions({
+ expectToFail: false,
+ input: {
+ roleId: stepAgentRoleId,
+ objectPermissions: [
+ {
+ objectMetadataId,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ },
+ });
+ await upsertFieldPermissions({
+ expectToFail: false,
+ input: {
+ roleId: stepAgentRoleId,
+ fieldPermissions: [
+ {
+ objectMetadataId,
+ fieldMetadataId,
+ canReadFieldValue: false,
+ canUpdateFieldValue: false,
+ },
+ ],
+ },
+ });
+ await upsertPermissionFlags({
+ expectToFail: false,
+ input: {
+ roleId: stepAgentRoleId,
+ permissionFlagKeys: [PermissionFlagType.HTTP_REQUEST_TOOL],
+ },
+ });
+
+ generateWorkflow = await createLegacyAiStepWorkflow({
+ name: 'Company summary',
+ stepInput: { prompt: STEP_PROMPT },
+ });
+ conversationalWorkflow = await createLegacyAiStepWorkflow({
+ name: 'Reviewed company summary',
+ stepInput: {
+ prompt: STEP_PROMPT,
+ humanInputInstructions: 'Have a person approve the summary',
+ },
+ });
+
+ const seededSystemAgents: { id: string }[] =
+ await global.testDataSource.query(
+ `SELECT id FROM core."agent"
+ WHERE "workspaceId" = $1 AND "isSystem" = true AND NOT (id = ANY($2::uuid[]))`,
+ [SEED_APPLE_WORKSPACE_ID, agentIds],
+ );
+
+ seededSystemAgentIds = seededSystemAgents.map(({ id }) => id);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ afterAll(async () => {
+ await global.testDataSource.query(
+ `DELETE FROM ${SCHEMA}."workflowRun" WHERE "coreWorkflowId" = ANY($1::uuid[])`,
+ [coreWorkflowIds],
+ );
+ await deleteCoreWorkflows({ coreWorkflowIds });
+
+ for (const workspaceWorkflowId of workspaceWorkflowIds) {
+ await deleteLegacyWorkspaceWorkflowRecords({ workspaceWorkflowId });
+ }
+
+ const remainingAgents: { id: string }[] = await global.testDataSource.query(
+ `SELECT id FROM core."agent" WHERE id = ANY($1::uuid[])`,
+ [agentIds],
+ );
+
+ for (const { id } of remainingAgents) {
+ await deleteOneAgent({ expectToFail: false, input: { id } });
+ }
+
+ for (const roleId of roleIds) {
+ const [remainingRole] = await global.testDataSource.query(
+ `SELECT id FROM core."role" WHERE id = $1`,
+ [roleId],
+ );
+
+ if (isDefined(remainingRole)) {
+ await deleteOneRole({
+ expectToFail: false,
+ input: { idToDelete: roleId },
+ });
+ }
+ }
+
+ // the command also reveals the conversational step agents the dev seed creates
+ await global.testDataSource.query(
+ `UPDATE core."agent" SET "isSystem" = true WHERE id = ANY($1::uuid[])`,
+ [seededSystemAgentIds],
+ );
+ await global.workflowTestServices.workspaceCache.invalidateAndRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatAgentMaps'],
+ );
+ });
+
+ it('moves the instructions, model, response format and role of a step agent into the step', async () => {
+ await runCommand();
+
+ const inlinedStep = inlineStepAgentOf(generateWorkflow.step);
+
+ expect(await readCoreSteps(generateWorkflow.coreWorkflowVersionId)).toEqual(
+ [inlinedStep],
+ );
+ expect(
+ await readWorkspaceSteps(generateWorkflow.workspaceWorkflowVersionId),
+ ).toEqual([inlinedStep]);
+ expect(await readAgent(generateWorkflow.agentId)).toMatchObject({
+ isSystem: true,
+ });
+ });
+
+ it('keeps the agent of a step with human input and makes it visible', async () => {
+ expect(
+ await readCoreSteps(conversationalWorkflow.coreWorkflowVersionId),
+ ).toEqual([conversationalWorkflow.step]);
+ expect(
+ await readWorkspaceSteps(
+ conversationalWorkflow.workspaceWorkflowVersionId,
+ ),
+ ).toEqual([conversationalWorkflow.step]);
+ expect(await readAgent(conversationalWorkflow.agentId)).toEqual({
+ isSystem: false,
+ });
+ });
+
+ it('changes nothing when run again', async () => {
+ const migratedRows = await readMigratedRows();
+
+ await runCommand();
+
+ expect(await readMigratedRows()).toEqual(migratedRows);
+ });
+
+ it('activates the inlined workflow and runs its step with the instructions and scope of the former agent', async () => {
+ const calls = scriptModelAnsweringASummary();
+
+ await activateCoreWorkflowVersion({
+ coreWorkflowVersionId: generateWorkflow.coreWorkflowVersionId,
+ });
+
+ const workflowRunId = await runCoreWorkflowVersion({
+ coreWorkflowVersionId: generateWorkflow.coreWorkflowVersionId,
+ });
+
+ expect((await waitForWorkflowCompletion(workflowRunId))?.status).toBe(
+ 'COMPLETED',
+ );
+ expect(calls[0].systemPrompt).toContain(STEP_AGENT_INSTRUCTIONS);
+ expect(calls[0].offeredToolNames).toEqual(
+ expect.arrayContaining(['find_many_companies', 'http_request']),
+ );
+ expect(calls[0].offeredToolNames).not.toContain('find_many_people');
+ });
+
+ it('keeps an archived step agent visible, so its step still stops and the agent can be restored', async () => {
+ const archivedWorkflow = await createLegacyAiStepWorkflow({
+ name: 'Company summary with an archived agent',
+ stepInput: { prompt: STEP_PROMPT },
+ });
+
+ await global.testDataSource.query(
+ `UPDATE core."agent" SET "isActive" = false WHERE id = $1`,
+ [archivedWorkflow.agentId],
+ );
+ await global.workflowTestServices.workspaceCache.invalidateAndRecompute(
+ SEED_APPLE_WORKSPACE_ID,
+ ['flatAgentMaps'],
+ );
+
+ await runCommand();
+
+ expect(await readCoreSteps(archivedWorkflow.coreWorkflowVersionId)).toEqual(
+ [archivedWorkflow.step],
+ );
+ expect(await readAgent(archivedWorkflow.agentId)).toMatchObject({
+ isSystem: false,
+ });
+ await expect(
+ getAppProviderByClassName<AgentRunPersonaService>(
+ 'AgentRunPersonaService',
+ ).resolveOrThrow({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ spec: { agentId: archivedWorkflow.agentId },
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.AGENT_IS_INACTIVE });
+ });
+
+ it('keeps a step agent whose role has row-level predicates and makes it visible', async () => {
+ const { data: roleData } = await createOneRole({
+ expectToFail: false,
+ input: {
+ label: 'Inline step agents row-level role',
+ description: 'A step agent role a scope cannot express',
+ canUpdateAllSettings: false,
+ canAccessAllTools: false,
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ canBeAssignedToUsers: false,
+ canBeAssignedToAgents: true,
+ canBeAssignedToApiKeys: false,
+ },
+ });
+ const rowLevelRoleId = roleData.createOneRole.id;
+
+ roleIds.push(rowLevelRoleId);
+
+ const [{ objectMetadataId, fieldMetadataId }] =
+ await global.testDataSource.query(
+ `SELECT object.id AS "objectMetadataId", field.id AS "fieldMetadataId"
+ FROM core."objectMetadata" object
+ JOIN core."fieldMetadata" field ON field."objectMetadataId" = object.id
+ WHERE object."workspaceId" = $1 AND object."universalIdentifier" = $2
+ AND field."universalIdentifier" = $3`,
+ [
+ SEED_APPLE_WORKSPACE_ID,
+ COMPANY.universalIdentifier,
+ COMPANY.fields.name.universalIdentifier,
+ ],
+ );
+
+ await upsertRowLevelPermissionPredicates({
+ expectToFail: false,
+ input: {
+ roleId: rowLevelRoleId,
+ objectMetadataId,
+ predicates: [
+ {
+ fieldMetadataId,
+ operand: RowLevelPermissionPredicateOperand.CONTAINS,
+ value: 'Acme',
+ },
+ ],
+ predicateGroups: [],
+ },
+ });
+
+ const rowLevelWorkflow = await createLegacyAiStepWorkflow({
+ name: 'Company summary limited to some companies',
+ stepInput: { prompt: STEP_PROMPT },
+ });
+
+ await updateOneAgent({
+ expectToFail: false,
+ input: { id: rowLevelWorkflow.agentId, roleId: rowLevelRoleId },
+ });
+
+ await runCommand();
+
+ expect(await readCoreSteps(rowLevelWorkflow.coreWorkflowVersionId)).toEqual(
+ [rowLevelWorkflow.step],
+ );
+ expect(await readAgent(rowLevelWorkflow.agentId)).toEqual({
+ isSystem: false,
+ });
+ });
+});
diff --git a/packages/twenty-server/test/utils/mock-agent-run-turns.util.ts b/packages/twenty-server/test/utils/mock-agent-run-turns.util.ts
index 4c5392b443f..e875291b671 100644
--- a/packages/twenty-server/test/utils/mock-agent-run-turns.util.ts
+++ b/packages/twenty-server/test/utils/mock-agent-run-turns.util.ts
@@ -129,6 +129,7 @@ export const mockAgentRunTurns = (
startTurn.mockImplementationOnce(async () => ({
turn: {} as never,
spenders: {},
+ isStructuredOutputInSameRequest: false,
source: {
parts: new ReadableStream({
start: (controller) => {
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index bafaf644f71..59fdbb3ab67 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -44,7 +44,6 @@ export { PUBLISH_FRONT_COMPONENT_TOOL_NAME } from './constants/publish-front-com
export { REACT_TO_MESSAGE_TOOL_NAME } from './constants/react-to-message-tool-name.const';
export { REQUEST_FORM_TOOL_NAME } from './constants/request-form-tool-name.const';
export { ToolCategory } from './constants/tool-category.const';
-export { agentRunSummarySchema } from './schemas/agent-run-summary-schema';
export type { AgentChatInboxAction } from './types/AgentChatInboxAction';
export type { AgentChatInboxState } from './types/AgentChatInboxState';
export type { AgentChatSubscriptionEvent } from './types/AgentChatSubscriptionEvent';
@@ -61,6 +60,11 @@ export type {
} from './types/AgentResponseSchema';
export type { AgentRunSummary } from './types/AgentRunSummary';
export type { AgentRunToolCallLog } from './types/AgentRunToolCallLog';
+export type {
+ AiRunScope,
+ AiRunScopeObjectPermission,
+ AiRunScopeFieldPermission,
+} from './types/AiRunScope';
export type { AskQuestionAnswer } from './types/AskQuestionAnswer';
export type { AskQuestionItem } from './types/AskQuestionItem';
export type { AskQuestionOption } from './types/AskQuestionOption';
@@ -113,8 +117,10 @@ export { formatRecordReference } from './utils/format-record-reference.util';
export { formatSkillReference } from './utils/format-skill-reference.util';
export { getAgentChatMentionsResolvedAt } from './utils/get-agent-chat-mentions-resolved-at.util';
export { getAiModelTierFromModelId } from './utils/get-ai-model-tier-from-model-id.util';
+export { hasAiRunScopeRepeatedEntries } from './utils/has-ai-run-scope-repeated-entries.util';
export { inferAiSdkPackage } from './utils/infer-ai-sdk-package.util';
export { isAgentChatMentionUnresolved } from './utils/is-agent-chat-mention-unresolved.util';
+export { isAgentChatTurnEndEvent } from './utils/is-agent-chat-turn-end-event.util';
export { isAiEvaluationQuestionType } from './utils/is-ai-evaluation-question-type.util';
export { isAiModelEffort } from './utils/is-ai-model-effort.util';
export { isAiModelTier } from './utils/is-ai-model-tier.util';
@@ -128,4 +134,8 @@ export { isSilentAgentChatMessageParts } from './utils/is-silent-agent-chat-mess
export { isSucceededCompleteWorkspaceSetupToolPart } from './utils/is-succeeded-complete-workspace-setup-tool-part.util';
export { isValidAgentMessageReactionEmoji } from './utils/is-valid-agent-message-reaction-emoji.util';
export { isValidAgentResponseSchemaPropertyKey } from './utils/is-valid-agent-response-schema-property-key.util';
+export type { AgentMessagePartRow } from './utils/map-agent-message-part-to-ui-message-part.util';
+export { mapAgentMessagePartToUIMessagePart } from './utils/map-agent-message-part-to-ui-message-part.util';
+export type { AgentMessageRow } from './utils/map-agent-messages-to-ui-messages.util';
+export { mapAgentMessagesToUIMessages } from './utils/map-agent-messages-to-ui-messages.util';
export { parseAiModelVariantId } from './utils/parse-ai-model-variant-id.util';
diff --git a/packages/twenty-shared/src/ai/schemas/agent-run-summary-schema.ts b/packages/twenty-shared/src/ai/schemas/internal/agent-run-summary-schema.ts
similarity index 100%
rename from packages/twenty-shared/src/ai/schemas/agent-run-summary-schema.ts
rename to packages/twenty-shared/src/ai/schemas/internal/agent-run-summary-schema.ts
diff --git a/packages/twenty-shared/src/ai/schemas/internal/ai-run-scope-schema.ts b/packages/twenty-shared/src/ai/schemas/internal/ai-run-scope-schema.ts
new file mode 100644
index 00000000000..4a0ea34a1c8
--- /dev/null
+++ b/packages/twenty-shared/src/ai/schemas/internal/ai-run-scope-schema.ts
@@ -0,0 +1,6 @@
+import { rolePermissionGrantsSchema } from '@/application/rolePermissionGrantsSchema';
+
+// ungranted is denied, but members and system objects stay readable
+export const aiRunScopeSchema = rolePermissionGrantsSchema.omit({
+ canAccessAllAgentChatChannels: true,
+});
diff --git a/packages/twenty-shared/src/ai/schemas/internal/model-configuration-schema.ts b/packages/twenty-shared/src/ai/schemas/internal/model-configuration-schema.ts
new file mode 100644
index 00000000000..8d4af5040bd
--- /dev/null
+++ b/packages/twenty-shared/src/ai/schemas/internal/model-configuration-schema.ts
@@ -0,0 +1,12 @@
+import { z } from 'zod';
+
+const nativeToolConfigurationSchema = z.object({
+ enabled: z.boolean(),
+ // not z.unknown(): TypeORM cannot type a partial update of a workflow step holding unknown values
+ configuration: z.record(z.string(), z.any()).optional(),
+});
+
+export const modelConfigurationSchema = z.object({
+ webSearch: nativeToolConfigurationSchema.optional(),
+ twitterSearch: nativeToolConfigurationSchema.optional(),
+});
diff --git a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
index 232b88ceec0..c2e8c5343a6 100644
--- a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
+++ b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
@@ -3,7 +3,10 @@ import { type AgentMessageReactionSummary } from '@/ai/types/AgentMessageReactio
// Not UIMessageChunk, to keep the `ai` package out of twenty-shared.
export type AgentChatSubscriptionEvent =
| { type: 'stream-chunk'; chunk: Record<string, unknown>; seq?: number }
- | { type: 'message-persisted'; messageId: string }
+ // turnId is set on the reply that ends a turn, not on a member's message
+ | { type: 'message-persisted'; messageId: string; turnId?: string }
+ // the end of a run without a thread, which saves no message
+ | { type: 'run-finished'; turnId: string }
// A message saved without a turn, which must not reset a reply in progress
| { type: 'message-added'; messageId: string }
| { type: 'queue-updated' }
@@ -15,7 +18,7 @@ export type AgentChatSubscriptionEvent =
revision: number;
}
| { type: 'stream-error'; code: string; message: string }
- | { type: 'credits-exhausted' }
+ | { type: 'credits-exhausted'; turnId?: string }
| {
type: 'user-credits-exhausted';
workspaceMemberId: string;
diff --git a/packages/twenty-shared/src/ai/types/AgentRunSummary.ts b/packages/twenty-shared/src/ai/types/AgentRunSummary.ts
index c15f360d0c6..0494d13713a 100644
--- a/packages/twenty-shared/src/ai/types/AgentRunSummary.ts
+++ b/packages/twenty-shared/src/ai/types/AgentRunSummary.ts
@@ -1,5 +1,5 @@
import type z from 'zod';
-import { type agentRunSummarySchema } from '@/ai/schemas/agent-run-summary-schema';
+import { type agentRunSummarySchema } from '@/ai/schemas/internal/agent-run-summary-schema';
export type AgentRunSummary = z.infer<typeof agentRunSummarySchema>;
diff --git a/packages/twenty-shared/src/ai/types/AiRunScope.ts b/packages/twenty-shared/src/ai/types/AiRunScope.ts
new file mode 100644
index 00000000000..edbf1d356cd
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/AiRunScope.ts
@@ -0,0 +1,13 @@
+import { type z } from 'zod';
+
+import { type aiRunScopeSchema } from '@/ai/schemas/internal/ai-run-scope-schema';
+
+export type AiRunScope = z.infer<typeof aiRunScopeSchema>;
+
+export type AiRunScopeObjectPermission = NonNullable<
+ AiRunScope['objectPermissions']
+>[number];
+
+export type AiRunScopeFieldPermission = NonNullable<
+ AiRunScope['fieldPermissions']
+>[number];
diff --git a/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts
index 55b1ee977ed..ddc27fb3608 100644
--- a/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts
+++ b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts
@@ -20,6 +20,7 @@ type Metadata = {
startedAt?: string;
finishedAt?: string;
senderWorkspaceMemberId?: string | null;
+ turnId?: string | null;
usage?: AiChatUsageMetadata;
model?: AiChatModelMetadata;
};
diff --git a/packages/twenty-shared/src/ai/types/ModelConfiguration.ts b/packages/twenty-shared/src/ai/types/ModelConfiguration.ts
index 0e95fdcece8..ada06a1fb40 100644
--- a/packages/twenty-shared/src/ai/types/ModelConfiguration.ts
+++ b/packages/twenty-shared/src/ai/types/ModelConfiguration.ts
@@ -1,10 +1,5 @@
-export type ModelConfiguration = {
- webSearch?: {
- enabled: boolean;
- configuration?: Record<string, unknown>;
- };
- twitterSearch?: {
- enabled: boolean;
- configuration?: Record<string, unknown>;
- };
-};
+import { type z } from 'zod';
+
+import { type modelConfigurationSchema } from '@/ai/schemas/internal/model-configuration-schema';
+
+export type ModelConfiguration = z.infer<typeof modelConfigurationSchema>;
diff --git a/packages/twenty-shared/src/ai/utils/__tests__/is-agent-chat-turn-end-event.util.spec.ts b/packages/twenty-shared/src/ai/utils/__tests__/is-agent-chat-turn-end-event.util.spec.ts
new file mode 100644
index 00000000000..fc8da06ba62
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/__tests__/is-agent-chat-turn-end-event.util.spec.ts
@@ -0,0 +1,34 @@
+import { type AgentChatSubscriptionEvent } from '@/ai/types/AgentChatSubscriptionEvent';
+import { isAgentChatTurnEndEvent } from '@/ai/utils/is-agent-chat-turn-end-event.util';
+
+const TURN_END_EVENTS: AgentChatSubscriptionEvent[] = [
+ { type: 'message-persisted', messageId: 'message-id', turnId: 'turn-id' },
+ { type: 'run-finished', turnId: 'turn-id' },
+ { type: 'credits-exhausted' },
+ { type: 'stream-error', code: 'STREAM_ERROR', message: 'Failed' },
+];
+
+describe('isAgentChatTurnEndEvent', () => {
+ it.each(TURN_END_EVENTS)('ends the turn on $type', (event) => {
+ expect(isAgentChatTurnEndEvent(event)).toBe(true);
+ });
+
+ it('does not end a turn on a message a member saved, which has no turn', () => {
+ expect(
+ isAgentChatTurnEndEvent({
+ type: 'message-persisted',
+ messageId: 'message-id',
+ }),
+ ).toBe(false);
+ });
+
+ it('does not end a turn on a chunk or a keepalive', () => {
+ expect(isAgentChatTurnEndEvent({ type: 'keepalive' })).toBe(false);
+ expect(
+ isAgentChatTurnEndEvent({
+ type: 'stream-chunk',
+ chunk: { type: 'text-delta' },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/mapDBPartToUIMessagePart.test.ts b/packages/twenty-shared/src/ai/utils/__tests__/map-agent-message-part-to-ui-message-part.util.spec.ts
similarity index 68%
rename from packages/twenty-front/src/modules/ai/utils/__tests__/mapDBPartToUIMessagePart.test.ts
rename to packages/twenty-shared/src/ai/utils/__tests__/map-agent-message-part-to-ui-message-part.util.spec.ts
index 29e76d62405..dcd6ca5cf82 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/mapDBPartToUIMessagePart.test.ts
+++ b/packages/twenty-shared/src/ai/utils/__tests__/map-agent-message-part-to-ui-message-part.util.spec.ts
@@ -1,8 +1,6 @@
-import { type AgentMessagePart } from '~/generated-metadata/graphql';
+import { mapAgentMessagePartToUIMessagePart } from '@/ai/utils/map-agent-message-part-to-ui-message-part.util';
-import { mapDBPartToUIMessagePart } from '@/ai/utils/mapDBPartToUIMessagePart';
-
-describe('mapDBPartToUIMessagePart', () => {
+describe('mapAgentMessagePartToUIMessagePart', () => {
it('preserves OpenAI encrypted reasoning metadata', () => {
const providerMetadata = {
openai: {
@@ -12,12 +10,13 @@ describe('mapDBPartToUIMessagePart', () => {
};
expect(
- mapDBPartToUIMessagePart({
+ mapAgentMessagePartToUIMessagePart({
type: 'reasoning',
reasoningContent: 'reasoning summary',
+ orderIndex: 0,
state: 'done',
providerMetadata,
- } as AgentMessagePart),
+ }),
).toEqual({
type: 'reasoning',
text: 'reasoning summary',
@@ -28,11 +27,12 @@ describe('mapDBPartToUIMessagePart', () => {
it('maps reasoning stored without content to empty text', () => {
expect(
- mapDBPartToUIMessagePart({
+ mapAgentMessagePartToUIMessagePart({
type: 'reasoning',
reasoningContent: null,
+ orderIndex: 0,
state: 'done',
- } as AgentMessagePart),
+ }),
).toMatchObject({ type: 'reasoning', text: '' });
});
});
diff --git a/packages/twenty-shared/src/ai/utils/has-ai-run-scope-repeated-entries.util.ts b/packages/twenty-shared/src/ai/utils/has-ai-run-scope-repeated-entries.util.ts
new file mode 100644
index 00000000000..a86361d12df
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/has-ai-run-scope-repeated-entries.util.ts
@@ -0,0 +1,21 @@
+import { type AiRunScope } from '@/ai/types/AiRunScope';
+import { isDefined } from '@/utils/validation/isDefined';
+
+const hasRepeatedKey = (keys: string[]): boolean =>
+ new Set(keys).size !== keys.length;
+
+// a repeated object or field would leave the permission that applies ambiguous, so a scope names each once
+export const hasAiRunScopeRepeatedEntries = (
+ scope: AiRunScope | null | undefined,
+): boolean =>
+ isDefined(scope) &&
+ (hasRepeatedKey(
+ (scope.objectPermissions ?? []).map(
+ ({ objectUniversalIdentifier }) => objectUniversalIdentifier,
+ ),
+ ) ||
+ hasRepeatedKey(
+ (scope.fieldPermissions ?? []).map(
+ ({ fieldUniversalIdentifier }) => fieldUniversalIdentifier,
+ ),
+ ));
diff --git a/packages/twenty-shared/src/ai/utils/is-agent-chat-turn-end-event.util.ts b/packages/twenty-shared/src/ai/utils/is-agent-chat-turn-end-event.util.ts
new file mode 100644
index 00000000000..4bb391aa7f2
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/is-agent-chat-turn-end-event.util.ts
@@ -0,0 +1,11 @@
+import { type AgentChatSubscriptionEvent } from '@/ai/types/AgentChatSubscriptionEvent';
+import { isDefined } from '@/utils/validation/isDefined';
+
+// one stream runs at a time on a channel, so a stream error ends the turn streaming on it
+export const isAgentChatTurnEndEvent = (
+ event: AgentChatSubscriptionEvent,
+): boolean =>
+ (event.type === 'message-persisted' && isDefined(event.turnId)) ||
+ event.type === 'run-finished' ||
+ event.type === 'credits-exhausted' ||
+ event.type === 'stream-error';
diff --git a/packages/twenty-shared/src/ai/utils/map-agent-message-part-to-ui-message-part.util.ts b/packages/twenty-shared/src/ai/utils/map-agent-message-part-to-ui-message-part.util.ts
new file mode 100644
index 00000000000..d9b9b864323
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/map-agent-message-part-to-ui-message-part.util.ts
@@ -0,0 +1,105 @@
+import { type ReasoningUIPart } from 'ai';
+
+import { type ExtendedFileUIPart } from '@/ai/types/DataMessagePart';
+import { type ExtendedUIMessagePart } from '@/ai/types/ExtendedUIMessagePart';
+import { isDefined } from '@/utils/validation/isDefined';
+
+export type AgentMessagePartRow = {
+ type: string;
+ orderIndex: number;
+ textContent?: string | null;
+ reasoningContent?: string | null;
+ toolName?: string | null;
+ toolCallId?: string | null;
+ toolInput?: unknown;
+ toolOutput?: unknown;
+ state?: string | null;
+ providerExecuted?: boolean | null;
+ errorMessage?: string | 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;
+ fileId?: string | null;
+ providerMetadata?: Record<string, unknown> | null;
+};
+
+export const mapAgentMessagePartToUIMessagePart = (
+ part: AgentMessagePartRow,
+): ExtendedUIMessagePart | null => {
+ const providerMetadata = (part.providerMetadata ??
+ undefined) as ReasoningUIPart['providerMetadata'];
+
+ switch (part.type) {
+ case 'text':
+ return { type: 'text', text: part.textContent ?? '' };
+ case 'reasoning':
+ return {
+ type: 'reasoning',
+ text: part.reasoningContent ?? '',
+ state: (part.state ?? 'done') as ReasoningUIPart['state'],
+ providerMetadata,
+ };
+ case 'file':
+ return {
+ type: 'file',
+ mediaType: part.fileMediaType ?? 'application/octet-stream',
+ filename: part.fileFilename ?? '',
+ url: part.fileUrl ?? '',
+ fileId: part.fileId ?? '',
+ } as ExtendedFileUIPart;
+ case 'source-url':
+ return {
+ type: 'source-url',
+ sourceId: part.sourceUrlSourceId ?? '',
+ url: part.sourceUrlUrl ?? '',
+ title: part.sourceUrlTitle ?? '',
+ providerMetadata,
+ };
+ case 'source-document':
+ return {
+ type: 'source-document',
+ sourceId: part.sourceDocumentSourceId ?? '',
+ mediaType: part.sourceDocumentMediaType ?? '',
+ title: part.sourceDocumentTitle ?? '',
+ filename: part.sourceDocumentFilename ?? '',
+ providerMetadata,
+ };
+ case 'step-start':
+ return { type: 'step-start' };
+ default: {
+ const isStaticToolPart = part.type.startsWith('tool-');
+ const isDynamicToolPart = part.type === 'dynamic-tool';
+
+ // a tool part without its call id cannot be replayed to the model
+ if (
+ (!isStaticToolPart && !isDynamicToolPart) ||
+ !isDefined(part.toolCallId)
+ ) {
+ return null;
+ }
+
+ return {
+ type: part.type as `tool-${string}` | 'dynamic-tool',
+ ...(isDynamicToolPart && { toolName: part.toolName ?? '' }),
+ toolCallId: part.toolCallId,
+ input: part.toolInput ?? {},
+ output: part.toolOutput,
+ errorText: part.errorMessage ?? '',
+ state: part.state,
+ ...(isDefined(part.providerExecuted) && {
+ providerExecuted: part.providerExecuted,
+ }),
+ ...(isDefined(part.providerMetadata) && {
+ callProviderMetadata: part.providerMetadata,
+ }),
+ } as ExtendedUIMessagePart;
+ }
+ }
+};
diff --git a/packages/twenty-shared/src/ai/utils/map-agent-messages-to-ui-messages.util.ts b/packages/twenty-shared/src/ai/utils/map-agent-messages-to-ui-messages.util.ts
new file mode 100644
index 00000000000..18336820123
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/map-agent-messages-to-ui-messages.util.ts
@@ -0,0 +1,44 @@
+import { type ExtendedUIMessage } from '@/ai/types/ExtendedUIMessage';
+import {
+ type AgentMessagePartRow,
+ mapAgentMessagePartToUIMessagePart,
+} from '@/ai/utils/map-agent-message-part-to-ui-message-part.util';
+import { isDefined } from '@/utils/validation/isDefined';
+
+export type AgentMessageRow = {
+ id: string;
+ threadId: string;
+ role: string;
+ status: string;
+ createdAt: string;
+ processedAt?: string | null;
+ senderWorkspaceMemberId?: string | null;
+ turnId?: string | null;
+ parts: AgentMessagePartRow[];
+};
+
+export const mapAgentMessagesToUIMessages = (
+ messages: AgentMessageRow[],
+): ExtendedUIMessage[] =>
+ messages.map((message) => ({
+ id: message.id,
+ role: message.role as ExtendedUIMessage['role'],
+ status: message.status as 'queued' | 'sent',
+ parts: [...message.parts]
+ .sort((a, b) => a.orderIndex - b.orderIndex)
+ .map(mapAgentMessagePartToUIMessagePart)
+ .filter(isDefined),
+ metadata: {
+ createdAt: message.createdAt,
+ senderWorkspaceMemberId: message.senderWorkspaceMemberId,
+ turnId: message.turnId,
+ ...(message.role === 'assistant'
+ ? {
+ startedAt: message.createdAt,
+ // the assistant message is rewritten until its stream finishes
+ finishedAt: message.processedAt ?? undefined,
+ }
+ : {}),
+ },
+ threadId: message.threadId,
+ }));
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
index 313e7291f78..6ec61a81737 100644
--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -1,6 +1,7 @@
/** @jest-environment node */
import { isDefined } from '@/utils/validation/isDefined';
+import { WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES } from '@/workflow/constants/WorkflowAiAgentStepConfigIssueMessages';
import {
workflowManifestSchema,
@@ -167,6 +168,23 @@ describe('workflow manifest step types', () => {
},
},
},
+ {
+ type: 'AI_AGENT',
+ input: {
+ instructions: 'Qualify the lead from its last email.',
+ modelId: 'auto-select-workspace-default-model',
+ modelConfiguration: { webSearch: { enabled: true } },
+ scope: {
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: '77777777-7777-4777-8777-777777777777',
+ canReadObjectRecords: true,
+ },
+ ],
+ },
+ prompt: '{{trigger.properties.after.summary}}',
+ },
+ },
{
type: 'SEND_CHAT_MESSAGE',
input: {
@@ -190,6 +208,87 @@ describe('workflow manifest step types', () => {
expect(workflowManifestSchema.safeParse(definition).success).toBe(true);
});
+ it('refuses an AI agent step running an agent with its own config', () => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), {
+ type: 'AI_AGENT',
+ input: {
+ agentUniversalIdentifier: '66666666-6666-4666-8666-666666666666',
+ instructions: 'Qualify the lead.',
+ },
+ });
+
+ const result = workflowManifestSchema.safeParse(definition);
+
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.message).toContain(
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.AGENT_STEP_HAS_INLINE_CONFIG,
+ );
+ }
+ });
+
+ it.each([
+ { humanInputInstructions: 'Ask when the company is unclear' },
+ { conversation: { scope: 'RUN' } },
+ ])('refuses %o on an AI agent step without an agent', (agentOnlyInput) => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), {
+ type: 'AI_AGENT',
+ input: {
+ instructions: 'Qualify the lead.',
+ prompt: 'Go',
+ ...agentOnlyInput,
+ },
+ });
+
+ const result = workflowManifestSchema.safeParse(definition);
+
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.message).toContain(
+ WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES.GENERATE_STEP_HAS_CONVERSATION_CONFIG,
+ );
+ }
+ });
+
+ it('accepts a conversation on an AI agent step running an agent', () => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), {
+ type: 'AI_AGENT',
+ input: {
+ agentUniversalIdentifier: '66666666-6666-4666-8666-666666666666',
+ prompt: 'Go',
+ conversation: { scope: 'RUN' },
+ },
+ });
+
+ expect(workflowManifestSchema.safeParse(definition).success).toBe(true);
+ });
+
+ it('accepts the blank human input instructions the builder stores on a step without an agent', () => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), {
+ type: 'AI_AGENT',
+ input: { prompt: 'Go', humanInputInstructions: ' ' },
+ });
+
+ expect(workflowManifestSchema.safeParse(definition).success).toBe(true);
+ });
+
+ it('refuses an AI agent step scope with row-level predicates', () => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), {
+ type: 'AI_AGENT',
+ input: {
+ instructions: 'Qualify the lead.',
+ scope: { rowLevelPermissionPredicates: [] },
+ },
+ });
+
+ expect(workflowManifestSchema.safeParse(definition).success).toBe(false);
+ });
+
describe('connected account reference', () => {
const CALENDAR_EVENT = {
title: 'Kick-off',
diff --git a/packages/twenty-shared/src/application/aiRunUsageType.ts b/packages/twenty-shared/src/application/aiRunUsageType.ts
new file mode 100644
index 00000000000..29b18d4724d
--- /dev/null
+++ b/packages/twenty-shared/src/application/aiRunUsageType.ts
@@ -0,0 +1,4 @@
+export type AiRunUsage = {
+ inputTokens: number;
+ outputTokens: number;
+};
diff --git a/packages/twenty-shared/src/application/generateJsonFieldsSchema.ts b/packages/twenty-shared/src/application/generateJsonFieldsSchema.ts
new file mode 100644
index 00000000000..cb9ed255d03
--- /dev/null
+++ b/packages/twenty-shared/src/application/generateJsonFieldsSchema.ts
@@ -0,0 +1,11 @@
+import { z } from 'zod';
+
+import { aiRunScopeSchema } from '@/ai/schemas/internal/ai-run-scope-schema';
+import { agentResponseFormatSchema } from '@/workflow/schemas/agent-response-format-schema';
+
+// the generate mutation takes these as JSON, so GraphQL cannot validate them
+export const generateJsonFieldsSchema = z.object({
+ responseFormat: agentResponseFormatSchema.nullish(),
+ // no data tools when unset
+ scope: aiRunScopeSchema.nullish(),
+});
diff --git a/packages/twenty-shared/src/application/generateType.ts b/packages/twenty-shared/src/application/generateType.ts
new file mode 100644
index 00000000000..5e1215946fd
--- /dev/null
+++ b/packages/twenty-shared/src/application/generateType.ts
@@ -0,0 +1,12 @@
+import { type AiRunUsage } from './aiRunUsageType';
+
+export type GenerateResult = {
+ success: boolean;
+ text: string | null;
+ object: Record<string, unknown> | null;
+ error: string | null;
+ // the run's recorded turn, with its model, usage and credits
+ runId: string;
+ // what the run spent, including the steps that finished before a failure
+ usage: AiRunUsage;
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index e8690eb8e29..df1207af889 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -15,6 +15,7 @@ export type {
AgentTrigger,
AgentTriggerManifest,
} from './agentTriggerType';
+export type { AiRunUsage } from './aiRunUsageType';
export type { AppConnection } from './appConnectionType';
export type { AppKeyValueScope } from './appKeyValueScopeType';
export type { AppKeyValue } from './appKeyValueType';
@@ -190,6 +191,8 @@ export type {
FrontComponentManifest,
} from './frontComponentManifestType';
export type { FrontComponentSharedDependenciesManifest } from './frontComponentSharedDependenciesManifestType';
+export { generateJsonFieldsSchema } from './generateJsonFieldsSchema';
+export type { GenerateResult } from './generateType';
export type { HealthCheckLogicFunctionApplicationManifest } from './healthCheckLogicFunctionApplicationType';
export type {
IdentifyAccountPayload,
@@ -241,6 +244,16 @@ export type {
RowLevelPermissionPredicateManifest,
RoleManifest,
} from './roleManifestType';
+export type {
+ ObjectPermissionGrant,
+ FieldPermissionGrant,
+ RolePermissionGrants,
+} from './rolePermissionGrantsSchema';
+export {
+ objectPermissionGrantSchema,
+ fieldPermissionGrantSchema,
+ rolePermissionGrantsSchema,
+} from './rolePermissionGrantsSchema';
export type { RunAgentMessageAttachment } from './runAgentMessageAttachmentType';
export type {
RunAgentMessageRole,
@@ -293,13 +306,17 @@ export {
} from './utils/applicationVariableValueSerialization';
export { computeDependencyFileChecksum } from './utils/computeDependencyFileChecksum';
export { computePackageJsonChecksum } from './utils/computePackageJsonChecksum';
-export type { EffectiveObjectPermissions } from './utils/getEffectiveObjectPermissionsFromRoleManifest';
+export type {
+ EffectiveObjectPermissions,
+ ObjectRecordsPermissionGrants,
+} from './utils/getEffectiveObjectPermissionsFromRoleManifest';
export {
ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION,
getEffectiveObjectPermissionsFromRoleManifest,
} from './utils/getEffectiveObjectPermissionsFromRoleManifest';
export { getRoleManifestGrantsNotCoveredBy } from './utils/getRoleManifestGrantsNotCoveredBy';
export { getRowLevelRestrictionSignature } from './utils/getRowLevelRestrictionSignature';
+export { hasRunAgentMessageContentOrAttachments } from './utils/hasRunAgentMessageContentOrAttachments';
export { isConnectionProviderScope } from './utils/isConnectionProviderScope';
export { isFrontComponentWidgetPageLayoutType } from './utils/isFrontComponentWidgetPageLayoutType';
export { isReservedSettingsMenuItemSlug } from './utils/isReservedSettingsMenuItemSlug';
@@ -309,6 +326,7 @@ export {
} from './utils/isReservedSettingsMenuItemTitle';
export { isValidSettingsMenuItemSlug } from './utils/isValidSettingsMenuItemSlug';
export { isValidUniversalIdentifier } from './utils/isValidUniversalIdentifier';
+export { resolveObjectPermissionValue } from './utils/resolveObjectPermissionValue';
export type {
ViewManifestFilterValue,
ViewFieldManifest,
diff --git a/packages/twenty-shared/src/application/roleManifestType.ts b/packages/twenty-shared/src/application/roleManifestType.ts
index c8f3a61452b..add2be4b404 100644
--- a/packages/twenty-shared/src/application/roleManifestType.ts
+++ b/packages/twenty-shared/src/application/roleManifestType.ts
@@ -1,3 +1,8 @@
+import {
+ type FieldPermissionGrant,
+ type ObjectPermissionGrant,
+ type RolePermissionGrants,
+} from '@/application/rolePermissionGrantsSchema';
import { type SyncableEntityOptions } from '@/application/syncableEntityOptionsType';
import {
type RowLevelPermissionPredicateGroupLogicalOperator,
@@ -5,20 +10,11 @@ import {
type RowLevelPermissionPredicateValue,
} from '@/types';
-export type ObjectPermissionManifest = Partial<SyncableEntityOptions> & {
- objectUniversalIdentifier: string;
- canReadObjectRecords?: boolean;
- canUpdateObjectRecords?: boolean;
- canSoftDeleteObjectRecords?: boolean;
- canDestroyObjectRecords?: boolean;
-};
+export type ObjectPermissionManifest = Partial<SyncableEntityOptions> &
+ ObjectPermissionGrant;
-export type FieldPermissionManifest = Partial<SyncableEntityOptions> & {
- objectUniversalIdentifier: string;
- fieldUniversalIdentifier: string;
- canReadFieldValue?: boolean;
- canUpdateFieldValue?: boolean;
-};
+export type FieldPermissionManifest = Partial<SyncableEntityOptions> &
+ FieldPermissionGrant;
export type RowLevelPermissionPredicateGroupManifest = SyncableEntityOptions & {
objectUniversalIdentifier: string;
@@ -39,23 +35,16 @@ export type RowLevelPermissionPredicateManifest = SyncableEntityOptions & {
position?: number | null;
};
-export type RoleManifest = SyncableEntityOptions & {
- label: string;
- description?: string;
- icon?: string;
- canUpdateAllSettings?: boolean;
- canAccessAllTools?: boolean;
- canAccessAllAgentChatChannels?: boolean;
- canReadAllObjectRecords?: boolean;
- canUpdateAllObjectRecords?: boolean;
- canSoftDeleteAllObjectRecords?: boolean;
- canDestroyAllObjectRecords?: boolean;
- canBeAssignedToUsers?: boolean;
- canBeAssignedToAgents?: boolean;
- canBeAssignedToApiKeys?: boolean;
- objectPermissions?: ObjectPermissionManifest[];
- fieldPermissions?: FieldPermissionManifest[];
- rowLevelPermissionPredicates?: RowLevelPermissionPredicateManifest[];
- rowLevelPermissionPredicateGroups?: RowLevelPermissionPredicateGroupManifest[];
- permissionFlagUniversalIdentifiers?: string[];
-};
+export type RoleManifest = SyncableEntityOptions &
+ Omit<RolePermissionGrants, 'objectPermissions' | 'fieldPermissions'> & {
+ label: string;
+ description?: string;
+ icon?: string;
+ canBeAssignedToUsers?: boolean;
+ canBeAssignedToAgents?: boolean;
+ canBeAssignedToApiKeys?: boolean;
+ objectPermissions?: ObjectPermissionManifest[];
+ fieldPermissions?: FieldPermissionManifest[];
+ rowLevelPermissionPredicates?: RowLevelPermissionPredicateManifest[];
+ rowLevelPermissionPredicateGroups?: RowLevelPermissionPredicateGroupManifest[];
+ };
diff --git a/packages/twenty-shared/src/application/rolePermissionGrantsSchema.ts b/packages/twenty-shared/src/application/rolePermissionGrantsSchema.ts
new file mode 100644
index 00000000000..6232cfe3463
--- /dev/null
+++ b/packages/twenty-shared/src/application/rolePermissionGrantsSchema.ts
@@ -0,0 +1,35 @@
+import { z } from 'zod';
+
+export const objectPermissionGrantSchema = z.strictObject({
+ objectUniversalIdentifier: z.string(),
+ canReadObjectRecords: z.boolean().optional(),
+ canUpdateObjectRecords: z.boolean().optional(),
+ canSoftDeleteObjectRecords: z.boolean().optional(),
+ canDestroyObjectRecords: z.boolean().optional(),
+});
+
+export const fieldPermissionGrantSchema = z.strictObject({
+ objectUniversalIdentifier: z.string(),
+ fieldUniversalIdentifier: z.string(),
+ canReadFieldValue: z.boolean().optional(),
+ canUpdateFieldValue: z.boolean().optional(),
+});
+
+export const rolePermissionGrantsSchema = z.strictObject({
+ canReadAllObjectRecords: z.boolean().optional(),
+ canUpdateAllObjectRecords: z.boolean().optional(),
+ canSoftDeleteAllObjectRecords: z.boolean().optional(),
+ canDestroyAllObjectRecords: z.boolean().optional(),
+ canUpdateAllSettings: z.boolean().optional(),
+ canAccessAllTools: z.boolean().optional(),
+ canAccessAllAgentChatChannels: z.boolean().optional(),
+ objectPermissions: z.array(objectPermissionGrantSchema).optional(),
+ fieldPermissions: z.array(fieldPermissionGrantSchema).optional(),
+ permissionFlagUniversalIdentifiers: z.array(z.string()).optional(),
+});
+
+export type ObjectPermissionGrant = z.infer<typeof objectPermissionGrantSchema>;
+
+export type FieldPermissionGrant = z.infer<typeof fieldPermissionGrantSchema>;
+
+export type RolePermissionGrants = z.infer<typeof rolePermissionGrantsSchema>;
diff --git a/packages/twenty-shared/src/application/runAgentType.ts b/packages/twenty-shared/src/application/runAgentType.ts
index 88e800cb49b..8850518db8c 100644
--- a/packages/twenty-shared/src/application/runAgentType.ts
+++ b/packages/twenty-shared/src/application/runAgentType.ts
@@ -45,6 +45,8 @@ export type RunAgentInput = {
export type RunAgentResult = {
threadId: string;
+ // the turn this call opened; a run that waits goes on in later turns of the same conversation
+ runId: string;
// SUSPENDED: the agent paused on a wait and goes on by itself; its reply lands in the thread
// RUNNING: the call did not wait for the run, or the run outlasted the wait; its reply lands in the thread
status: 'COMPLETED' | 'SUSPENDED' | 'FAILED' | 'RUNNING';
diff --git a/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts b/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts
index 22b2ec20a9f..85db12c2e14 100644
--- a/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts
+++ b/packages/twenty-shared/src/application/utils/getEffectiveObjectPermissionsFromRoleManifest.ts
@@ -1,5 +1,5 @@
import { type ObjectPermissionAction } from '@/application/objectPermissionActionType';
-import { type RoleManifest } from '@/application/roleManifestType';
+import { type RolePermissionGrants } from '@/application/rolePermissionGrantsSchema';
export type EffectiveObjectPermissions = Record<
ObjectPermissionAction,
@@ -11,13 +11,19 @@ export const ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION = {
canUpdateObjectRecords: 'canUpdateAllObjectRecords',
canSoftDeleteObjectRecords: 'canSoftDeleteAllObjectRecords',
canDestroyObjectRecords: 'canDestroyAllObjectRecords',
-} as const satisfies Record<ObjectPermissionAction, keyof RoleManifest>;
+} as const satisfies Record<ObjectPermissionAction, keyof RolePermissionGrants>;
+
+export type ObjectRecordsPermissionGrants = Pick<
+ RolePermissionGrants,
+ | (typeof ROLE_LEVEL_FLAG_BY_OBJECT_PERMISSION_ACTION)[ObjectPermissionAction]
+ | 'objectPermissions'
+>;
export const getEffectiveObjectPermissionsFromRoleManifest = ({
role,
objectUniversalIdentifier,
}: {
- role: RoleManifest;
+ role: ObjectRecordsPermissionGrants;
objectUniversalIdentifier: string;
}): EffectiveObjectPermissions => {
const objectPermission = role.objectPermissions?.find(
diff --git a/packages/twenty-shared/src/application/utils/hasRunAgentMessageContentOrAttachments.ts b/packages/twenty-shared/src/application/utils/hasRunAgentMessageContentOrAttachments.ts
new file mode 100644
index 00000000000..3b38ba85ac3
--- /dev/null
+++ b/packages/twenty-shared/src/application/utils/hasRunAgentMessageContentOrAttachments.ts
@@ -0,0 +1,10 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type RunAgentMessage } from '@/application/runAgentType';
+import { isNonEmptyArray } from '@/utils/array/isNonEmptyArray';
+
+export const hasRunAgentMessageContentOrAttachments = ({
+ content,
+ attachments,
+}: Pick<RunAgentMessage, 'content' | 'attachments'>): boolean =>
+ isNonEmptyString(content.trim()) || isNonEmptyArray(attachments);
diff --git a/packages/twenty-shared/src/application/utils/resolveObjectPermissionValue.ts b/packages/twenty-shared/src/application/utils/resolveObjectPermissionValue.ts
new file mode 100644
index 00000000000..bdd95a3dd73
--- /dev/null
+++ b/packages/twenty-shared/src/application/utils/resolveObjectPermissionValue.ts
@@ -0,0 +1,9 @@
+export const resolveObjectPermissionValue = ({
+ objectValue,
+ hasAllObjectsPermission,
+ isSystemObject,
+}: {
+ objectValue: boolean | null | undefined;
+ hasAllObjectsPermission: boolean;
+ isSystemObject: boolean;
+}): boolean => objectValue ?? (isSystemObject || hasAllObjectsPermission);
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
index 6eb1e5761e1..ca7dc4a930b 100644
--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -25,6 +25,8 @@ import { recordFilterGroupSchema } from '@/workflow/schemas/record-filter-group-
import { recordFilterSchema } from '@/workflow/schemas/record-filter-schema';
import { stepFilterSchema } from '@/workflow/schemas/step-filter-schema';
import { workflowPickRecordStrategySchema } from '@/workflow/schemas/pick-record-action-settings-schema';
+import { WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES } from '@/workflow/constants/WorkflowAiAgentStepConfigIssueMessages';
+import { getWorkflowAiAgentStepConfigIssues } from '@/workflow/utils/getWorkflowAiAgentStepConfigIssues';
export const workflowManifestPositionSchema = z.object({
x: z.number(),
@@ -256,8 +258,20 @@ const workflowStepManifestOptions = [
'AI_AGENT',
workflowAiAgentActionSettingsSchema.shape.input
.omit({ agentId: true })
- .extend({ agentUniversalIdentifier: z.uuid() })
- .strict(),
+ .extend({ agentUniversalIdentifier: z.uuid().optional() })
+ .strict()
+ .superRefine((input, context) => {
+ for (const issueCode of getWorkflowAiAgentStepConfigIssues({
+ ...input,
+ agentId: input.agentUniversalIdentifier,
+ })) {
+ context.addIssue({
+ code: 'custom',
+ path: ['agentUniversalIdentifier'],
+ message: WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES[issueCode],
+ });
+ }
+ }),
),
] as const;
diff --git a/packages/twenty-front/src/modules/marketplace/constants/PermissionFlagTypeByUniversalIdentifier.ts b/packages/twenty-shared/src/constants/PermissionFlagTypeByUniversalIdentifier.ts
similarity index 64%
rename from packages/twenty-front/src/modules/marketplace/constants/PermissionFlagTypeByUniversalIdentifier.ts
rename to packages/twenty-shared/src/constants/PermissionFlagTypeByUniversalIdentifier.ts
index 8885248b6a9..d67e63d387e 100644
--- a/packages/twenty-front/src/modules/marketplace/constants/PermissionFlagTypeByUniversalIdentifier.ts
+++ b/packages/twenty-shared/src/constants/PermissionFlagTypeByUniversalIdentifier.ts
@@ -1,7 +1,5 @@
-import {
- PermissionFlagType,
- SystemPermissionFlag,
-} from 'twenty-shared/constants';
+import { PermissionFlagType } from './PermissionFlagType';
+import { SystemPermissionFlag } from './SystemPermissionFlag';
export const PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER = new Map<
string,
diff --git a/packages/twenty-shared/src/constants/PermissionFlagUniversalIdentifierByType.ts b/packages/twenty-shared/src/constants/PermissionFlagUniversalIdentifierByType.ts
new file mode 100644
index 00000000000..e3eb3acc18d
--- /dev/null
+++ b/packages/twenty-shared/src/constants/PermissionFlagUniversalIdentifierByType.ts
@@ -0,0 +1,6 @@
+import { SystemPermissionFlag } from './SystemPermissionFlag';
+
+export const PERMISSION_FLAG_UNIVERSAL_IDENTIFIER_BY_TYPE = new Map<
+ string,
+ string
+>(Object.entries(SystemPermissionFlag));
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 222b0566906..15cf1fa79c6 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -72,6 +72,8 @@ export { MUTATION_MAX_MERGE_RECORDS } from './MutationMaxMergeRecords';
export { OBJECTS_WITH_CHANNEL_VISIBILITY_CONSTRAINTS } from './ObjectsWithChannelVisibilityConstraints';
export { PARTNER_PATTERN } from './PartnerPattern';
export { PermissionFlagType } from './PermissionFlagType';
+export { PERMISSION_FLAG_TYPE_BY_UNIVERSAL_IDENTIFIER } from './PermissionFlagTypeByUniversalIdentifier';
+export { PERMISSION_FLAG_UNIVERSAL_IDENTIFIER_BY_TYPE } from './PermissionFlagUniversalIdentifierByType';
export { PermissionsOnAllObjectRecords } from './PermissionsOnAllObjectRecords';
export { POLLED_MESSAGE_CHANNEL_TYPES } from './PolledMessageChannelTypes';
export { QUERY_DEFAULT_LIMIT_RECORDS } from './QueryDefaultLimitRecords';
diff --git a/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentGenerateStepDefaultName.ts b/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentGenerateStepDefaultName.ts
new file mode 100644
index 00000000000..bfbbbedd52b
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentGenerateStepDefaultName.ts
@@ -0,0 +1 @@
+export const WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME = 'Generate';
diff --git a/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentStepConfigIssueMessages.ts b/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentStepConfigIssueMessages.ts
new file mode 100644
index 00000000000..d5d2f45de15
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/constants/WorkflowAiAgentStepConfigIssueMessages.ts
@@ -0,0 +1,11 @@
+export const WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES = {
+ AGENT_STEP_HAS_INLINE_CONFIG:
+ 'A step running an agent takes its instructions, model and permissions from the agent. Remove the instructions, model and permissions set on the step, or remove its agent.',
+ GENERATE_STEP_HAS_CONVERSATION_CONFIG:
+ 'A step without an agent cannot ask humans or keep a conversation. Use an agent for this step, or remove its human input instructions and conversation setting.',
+ GENERATE_STEP_SCOPE_HAS_REPEATED_ENTRIES:
+ 'The permissions of a step without an agent list an object or field more than once. Keep a single entry for each.',
+} as const;
+
+export type WorkflowAiAgentStepConfigIssueCode =
+ keyof typeof WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES;
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index a47926cbd0e..6878f993a05 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -15,6 +15,9 @@ export { OBJECTS_SYNCED_FROM_CONNECTED_ACCOUNTS } from './constants/ObjectsSynce
export { STEP_RETRY_DELAYS_MS } from './constants/StepRetryDelaysMs';
export { TRIGGER_STEP_ID } from './constants/TriggerStepId';
export { WORKFLOW_ACTION_FEATURE_FLAGS } from './constants/WorkflowActionFeatureFlags';
+export { WORKFLOW_AI_AGENT_GENERATE_STEP_DEFAULT_NAME } from './constants/WorkflowAiAgentGenerateStepDefaultName';
+export type { WorkflowAiAgentStepConfigIssueCode } from './constants/WorkflowAiAgentStepConfigIssueMessages';
+export { WORKFLOW_AI_AGENT_STEP_CONFIG_ISSUE_MESSAGES } from './constants/WorkflowAiAgentStepConfigIssueMessages';
export { WORKFLOW_TRIGGER_DEFAULT_NAMES } from './constants/WorkflowTriggerDefaultNames';
export { WORKFLOW_TRIGGER_METADATA_KEY } from './constants/WorkflowTriggerMetadataKey';
export { WORKFLOW_TRIGGER_METADATA_LABEL } from './constants/WorkflowTriggerMetadataLabel';
@@ -35,6 +38,8 @@ export { computeWorkflowLayout } from './layout/utils/compute-workflow-layout.ut
export { agentResponseFormatSchema } from './schemas/agent-response-format-schema';
export { workflowAiAgentActionSchema } from './schemas/ai-agent-action-schema';
export { workflowAiAgentActionSettingsSchema } from './schemas/ai-agent-action-settings-schema';
+export { workflowAiAgentConversationConfigSchema } from './schemas/ai-agent-conversation-config-schema';
+export { workflowAiAgentInlineConfigSchema } from './schemas/ai-agent-inline-config-schema';
export { baseTriggerSchema } from './schemas/base-trigger-schema';
export { baseWorkflowActionSchema } from './schemas/base-workflow-action-schema';
export { baseWorkflowActionSettingsSchema } from './schemas/base-workflow-action-settings-schema';
@@ -161,9 +166,13 @@ export type { WorkflowStepWait } from './types/WorkflowStepWait';
export { canObjectBeManagedByAutomation } from './utils/canObjectBeManagedByAutomation';
export { extractRawVariableNamePart } from './utils/extractRawVariableNameParts';
export { getFunctionInputFromInputSchema } from './utils/getFunctionInputFromInputSchema';
+export { getWorkflowAiAgentStepConfigIssues } from './utils/getWorkflowAiAgentStepConfigIssues';
export { getWorkflowRunContext } from './utils/getWorkflowRunContext';
+export { hasWorkflowAiAgentConfig } from './utils/hasWorkflowAiAgentConfig';
+export { isAgentRunnableAsWorkflowStep } from './utils/isAgentRunnableAsWorkflowStep';
export { isObjectSyncedFromConnectedAccounts } from './utils/isObjectSyncedFromConnectedAccounts';
export { isStandaloneVariableString } from './utils/isStandaloneVariableString';
+export { isWorkflowAiAgentGenerateStep } from './utils/isWorkflowAiAgentGenerateStep';
export { parseBooleanFromStringValue } from './utils/parseBooleanFromStringValue';
export { parseDataFromContentType } from './utils/parseDataFromContentType';
export {
diff --git a/packages/twenty-shared/src/workflow/schemas/__tests__/ai-agent-action-settings-schema.test.ts b/packages/twenty-shared/src/workflow/schemas/__tests__/ai-agent-action-settings-schema.test.ts
new file mode 100644
index 00000000000..a585a3346ec
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/__tests__/ai-agent-action-settings-schema.test.ts
@@ -0,0 +1,25 @@
+import { workflowAiAgentActionSettingsSchema } from '../ai-agent-action-settings-schema';
+
+describe('workflowAiAgentActionSettingsSchema', () => {
+ it('should keep the native tool configuration of an inline step', () => {
+ const modelConfiguration = {
+ webSearch: { enabled: true, configuration: { maxUses: 3 } },
+ twitterSearch: { enabled: false, configuration: { region: 'FR' } },
+ };
+
+ const result = workflowAiAgentActionSettingsSchema.parse({
+ input: {
+ instructions: 'Summarize the company',
+ modelConfiguration,
+ prompt: 'Go',
+ },
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ });
+
+ expect(result.input.modelConfiguration).toEqual(modelConfiguration);
+ });
+});
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
index ed4cdcb31ac..dc309f6ad18 100644
--- a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
@@ -1,20 +1,20 @@
import { z } from 'zod';
import { agentResponseFormatSchema } from './agent-response-format-schema';
+import { workflowAiAgentConversationConfigSchema } from './ai-agent-conversation-config-schema';
+import { workflowAiAgentInlineConfigSchema } from './ai-agent-inline-config-schema';
import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
-import { workflowConversationSchema } from './workflow-conversation-schema';
export const workflowAiAgentActionSettingsSchema =
baseWorkflowActionSettingsSchema.extend({
input: z.object({
- agentId: z.string(),
+ // a reusable agent supplies the instructions, model and permissions; without one, the step does
+ agentId: z.string().optional(),
+ ...workflowAiAgentInlineConfigSchema.shape,
prompt: z.string().optional(),
responseFormat: agentResponseFormatSchema.optional(),
- // Empty by default: stopping for a person pauses the run, which existing workflows were not built to expect.
- humanInputInstructions: z.string().optional(),
// the member the agent's conversation is with, the workflow's creator when empty
workspaceMemberId: z.string().optional(),
- // a new conversation each time the step runs when unset
- conversation: workflowConversationSchema.optional(),
+ ...workflowAiAgentConversationConfigSchema.shape,
}),
});
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-conversation-config-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-conversation-config-schema.ts
new file mode 100644
index 00000000000..9b869980724
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-conversation-config-schema.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+
+import { workflowConversationSchema } from './workflow-conversation-schema';
+
+export const workflowAiAgentConversationConfigSchema = z.object({
+ // Empty by default: stopping for a person pauses the run, which existing workflows were not built to expect.
+ humanInputInstructions: z.string().optional(),
+ conversation: workflowConversationSchema.optional(),
+});
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-inline-config-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-inline-config-schema.ts
new file mode 100644
index 00000000000..82e553ce131
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-inline-config-schema.ts
@@ -0,0 +1,13 @@
+import { z } from 'zod';
+
+import { aiRunScopeSchema } from '@/ai/schemas/internal/ai-run-scope-schema';
+import { modelConfigurationSchema } from '@/ai/schemas/internal/model-configuration-schema';
+
+export const workflowAiAgentInlineConfigSchema = z.object({
+ instructions: z.string().optional(),
+ // the workspace's default model when unset
+ modelId: z.string().optional(),
+ modelConfiguration: modelConfigurationSchema.optional(),
+ // no data tools when unset
+ scope: aiRunScopeSchema.optional(),
+});
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
index 3ea2cd5025f..77e0cafbbac 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-import { agentRunSummarySchema } from '@/ai/schemas/agent-run-summary-schema';
+import { agentRunSummarySchema } from '@/ai/schemas/internal/agent-run-summary-schema';
const stepLogEntrySchema = z.object({
timestamp: z.string(),
diff --git a/packages/twenty-shared/src/workflow/utils/__tests__/getWorkflowAiAgentStepConfigIssues.test.ts b/packages/twenty-shared/src/workflow/utils/__tests__/getWorkflowAiAgentStepConfigIssues.test.ts
new file mode 100644
index 00000000000..1f26cade71e
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/__tests__/getWorkflowAiAgentStepConfigIssues.test.ts
@@ -0,0 +1,92 @@
+import { getWorkflowAiAgentStepConfigIssues } from '@/workflow/utils/getWorkflowAiAgentStepConfigIssues';
+
+describe('getWorkflowAiAgentStepConfigIssues', () => {
+ it('accepts a step running an agent with only a conversation', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({
+ agentId: 'agent-id',
+ humanInputInstructions: 'Ask before choosing a plan.',
+ conversation: { scope: 'RUN' },
+ }),
+ ).toEqual([]);
+ });
+
+ it('refuses a step running an agent with its own config', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({ agentId: 'agent-id', scope: {} }),
+ ).toEqual(['AGENT_STEP_HAS_INLINE_CONFIG']);
+ });
+
+ it('accepts a response format on a step running an agent', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({
+ agentId: 'agent-id',
+ responseFormat: { type: 'text' },
+ }),
+ ).toEqual([]);
+ });
+
+ it('refuses a step without an agent that keeps a conversation', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({
+ instructions: 'Qualify',
+ conversation: { scope: 'RUN' },
+ }),
+ ).toEqual(['GENERATE_STEP_HAS_CONVERSATION_CONFIG']);
+ });
+
+ it('ignores blank human input instructions on a step without an agent', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({
+ instructions: 'Qualify',
+ humanInputInstructions: ' ',
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores blank instructions on a step running an agent', () => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({
+ agentId: 'agent-id',
+ instructions: ' ',
+ modelId: '',
+ }),
+ ).toEqual([]);
+ });
+
+ it.each([
+ {
+ repeated: 'an object',
+ scope: {
+ objectPermissions: [
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: true },
+ { objectUniversalIdentifier: 'person', canReadObjectRecords: false },
+ ],
+ },
+ },
+ {
+ repeated: 'a field',
+ scope: {
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'person-email',
+ canReadFieldValue: true,
+ },
+ {
+ objectUniversalIdentifier: 'person',
+ fieldUniversalIdentifier: 'person-email',
+ canReadFieldValue: false,
+ },
+ ],
+ },
+ },
+ ])(
+ 'refuses a step without an agent whose permissions repeat $repeated',
+ ({ scope }) => {
+ expect(
+ getWorkflowAiAgentStepConfigIssues({ instructions: 'Qualify', scope }),
+ ).toEqual(['GENERATE_STEP_SCOPE_HAS_REPEATED_ENTRIES']);
+ },
+ );
+});
diff --git a/packages/twenty-shared/src/workflow/utils/getWorkflowAiAgentStepConfigIssues.ts b/packages/twenty-shared/src/workflow/utils/getWorkflowAiAgentStepConfigIssues.ts
new file mode 100644
index 00000000000..f0594d8753c
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/getWorkflowAiAgentStepConfigIssues.ts
@@ -0,0 +1,31 @@
+import { type z } from 'zod';
+
+import { type workflowAiAgentActionSettingsSchema } from '@/workflow/schemas/ai-agent-action-settings-schema';
+import { type WorkflowAiAgentStepConfigIssueCode } from '@/workflow/constants/WorkflowAiAgentStepConfigIssueMessages';
+import { hasAiRunScopeRepeatedEntries } from '@/ai/utils/has-ai-run-scope-repeated-entries.util';
+import { workflowAiAgentConversationConfigSchema } from '@/workflow/schemas/ai-agent-conversation-config-schema';
+import { workflowAiAgentInlineConfigSchema } from '@/workflow/schemas/ai-agent-inline-config-schema';
+import { hasWorkflowAiAgentConfig } from '@/workflow/utils/hasWorkflowAiAgentConfig';
+import { isWorkflowAiAgentGenerateStep } from '@/workflow/utils/isWorkflowAiAgentGenerateStep';
+
+export const getWorkflowAiAgentStepConfigIssues = (
+ input: Partial<z.infer<typeof workflowAiAgentActionSettingsSchema>['input']>,
+): WorkflowAiAgentStepConfigIssueCode[] => {
+ if (isWorkflowAiAgentGenerateStep(input)) {
+ return [
+ ...(hasWorkflowAiAgentConfig(
+ workflowAiAgentConversationConfigSchema,
+ input,
+ )
+ ? (['GENERATE_STEP_HAS_CONVERSATION_CONFIG'] as const)
+ : []),
+ ...(hasAiRunScopeRepeatedEntries(input.scope)
+ ? (['GENERATE_STEP_SCOPE_HAS_REPEATED_ENTRIES'] as const)
+ : []),
+ ];
+ }
+
+ return hasWorkflowAiAgentConfig(workflowAiAgentInlineConfigSchema, input)
+ ? ['AGENT_STEP_HAS_INLINE_CONFIG']
+ : [];
+};
diff --git a/packages/twenty-shared/src/workflow/utils/hasWorkflowAiAgentConfig.ts b/packages/twenty-shared/src/workflow/utils/hasWorkflowAiAgentConfig.ts
new file mode 100644
index 00000000000..0b1a6205822
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/hasWorkflowAiAgentConfig.ts
@@ -0,0 +1,15 @@
+import { isNonEmptyString, isString } from '@sniptt/guards';
+import { type z } from 'zod';
+
+import { isDefined } from '@/utils/validation/isDefined';
+
+// blank strings are what the builder stores when unset
+export const hasWorkflowAiAgentConfig = <TShape extends z.ZodRawShape>(
+ configSchema: z.ZodObject<TShape>,
+ input: Partial<Record<keyof TShape, unknown>>,
+): boolean =>
+ configSchema.keyof().options.some((key) => {
+ const value = input[key];
+
+ return isString(value) ? isNonEmptyString(value.trim()) : isDefined(value);
+ });
diff --git a/packages/twenty-shared/src/workflow/utils/isAgentRunnableAsWorkflowStep.ts b/packages/twenty-shared/src/workflow/utils/isAgentRunnableAsWorkflowStep.ts
new file mode 100644
index 00000000000..a5e0b64a279
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/isAgentRunnableAsWorkflowStep.ts
@@ -0,0 +1,5 @@
+// a system agent is the hidden agent an older step was built with, so no other step may run it
+export const isAgentRunnableAsWorkflowStep = (agent: {
+ isActive: boolean;
+ isSystem: boolean;
+}): boolean => agent.isActive && !agent.isSystem;
diff --git a/packages/twenty-shared/src/workflow/utils/isWorkflowAiAgentGenerateStep.ts b/packages/twenty-shared/src/workflow/utils/isWorkflowAiAgentGenerateStep.ts
new file mode 100644
index 00000000000..7739c38e536
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/utils/isWorkflowAiAgentGenerateStep.ts
@@ -0,0 +1,12 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type z } from 'zod';
+
+import { type workflowAiAgentActionSettingsSchema } from '@/workflow/schemas/ai-agent-action-settings-schema';
+
+// without an agent, the step is a single generation run as the caller: no conversation, no human input
+export const isWorkflowAiAgentGenerateStep = (
+ input: Pick<
+ z.infer<typeof workflowAiAgentActionSettingsSchema>['input'],
+ 'agentId'
+ >,
+): boolean => !isNonEmptyString(input.agentId);
diff --git a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
index f5837fd5562..0ecfa79fa99 100644
--- a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
+++ b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
@@ -11,7 +11,8 @@ export const NON_ACTIVABLE_WORKFLOW_VALIDATION_ISSUE_CODES: ReadonlySet<Workflow
'ITERATOR_MISSING_LOOP_BODY',
'INCOMPLETE_PICK_RECORD_CONFIG',
'INVALID_RECORD_FILTER_VALUE',
- 'AI_AGENT_MISSING_AGENT',
+ 'AI_AGENT_MISSING_PROMPT',
+ 'AI_AGENT_CONFLICTING_CONFIG',
'CONVERSATION_MISSING_KEY',
'CLASSIFY_MISSING_STATE',
'CLASSIFY_INCOMPLETE_QUESTION',
diff --git a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
index 296e265af5f..461b004df3b 100644
--- a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
+++ b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
@@ -35,7 +35,8 @@ export type WorkflowValidationIssueCode =
| 'VARIABLE_NOT_UPSTREAM'
| 'VARIABLE_MISSING_OUTPUT_SCHEMA'
| 'VARIABLE_PATH_NOT_FOUND'
- | 'AI_AGENT_MISSING_AGENT'
+ | 'AI_AGENT_MISSING_PROMPT'
+ | 'AI_AGENT_CONFLICTING_CONFIG'
| 'AI_AGENT_MISSING_OUTPUT_VARIABLE'
| 'CONVERSATION_MISSING_KEY'
| 'CLASSIFY_MISSING_STATE'