Skip to content

The open alternative to Salesforce, designed for AI.

Sync agent modelConfiguration and make isSystem display only (#29045)

Félix Malfaite0725c7ff6f6
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 21890f5c8c1..fa1a8875899 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
@@ -69,6 +69,8 @@ Key points:
- `modelId` (optional) overrides the default AI model used by the agent.
- `responseFormat` (optional) sets the agent's default output shape. Defaults to `{ type: 'text' }` for free-form text. Use `{ type: 'json', schema }` to force structured JSON output. A `runAgent()` call or a workflow AI step can ask for a different shape, which takes precedence.
- `roleUniversalIdentifier` (optional) binds the agent to a role your app defines. That role must not grant more than the application role, or the build fails; see [Agent roles](/developers/extend/apps/config/roles#agent-roles).
+- `modelConfiguration` (optional) turns on the model's native tools, as the agent settings page does: `{ webSearch: { enabled: true }, twitterSearch: { enabled: true } }`. Each tool only works on models that support it. Leave it out to keep them off.
+- `isSystem` (optional, defaults to `false`) hides the agent from agent lists, like the agents Twenty creates for workflow AI steps. It only changes what is displayed: an app's agents can only be changed through the app, whatever this flag says.
By default an agent returns free-form text. To get structured output, set `responseFormat` to `{ type: 'json' }` and provide a `schema`:
diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
index 3c3e3d42090..5dcf96f3377 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
@@ -71,6 +71,7 @@ Key points:
- `nextStepIds` wires the graph. The trigger points to the first steps, and each step points to the steps that run after it.
- A step reads earlier output with `{{trigger.<path>}}` or `{{<step universalIdentifier>.<path>}}`.
- The build validates the whole definition: unsupported trigger or step types, broken step links and references to unknown steps fail it.
+- `isSystem` (optional, defaults to `false`) hides the workflow from the lists that leave out system workflows. It only changes what is displayed.
## Referencing other entities
diff --git a/packages/twenty-sdk/src/sdk/define/agents/__tests__/define-agent.spec.ts b/packages/twenty-sdk/src/sdk/define/agents/__tests__/define-agent.spec.ts
index c556362d4b5..562d6238c39 100644
--- a/packages/twenty-sdk/src/sdk/define/agents/__tests__/define-agent.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/agents/__tests__/define-agent.spec.ts
@@ -42,6 +42,58 @@ describe('defineAgent', () => {
);
});
+ it('should accept a modelConfiguration and isSystem', () => {
+ const result = defineAgent({
+ ...VALID_AGENT_CONFIG,
+ isSystem: true,
+ modelConfiguration: {
+ webSearch: { enabled: true, configuration: { maxResults: 5 } },
+ twitterSearch: { enabled: false },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+ expect(result.config?.modelConfiguration?.webSearch?.enabled).toBe(true);
+ expect(result.config?.isSystem).toBe(true);
+ });
+
+ it('should error on an unknown or malformed modelConfiguration capability', () => {
+ const result = defineAgent({
+ ...VALID_AGENT_CONFIG,
+ modelConfiguration: {
+ // @ts-expect-error apps written in JavaScript can pass any shape
+ webSearch: { enabled: 'yes' },
+ // @ts-expect-error apps written in JavaScript can pass any shape
+ twitterSearch: { enabled: true, configuration: 'fast' },
+ websearch: { enabled: true },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toEqual([
+ `Agent 'sales-assistant' modelConfiguration.webSearch.enabled must be a boolean`,
+ `Agent 'sales-assistant' modelConfiguration.twitterSearch.configuration must be an object`,
+ `Agent 'sales-assistant' modelConfiguration.websearch is not supported, use one of: webSearch, twitterSearch`,
+ ]);
+ });
+
+ it('should error when modelConfiguration or isSystem have the wrong type', () => {
+ const result = defineAgent({
+ ...VALID_AGENT_CONFIG,
+ // @ts-expect-error apps written in JavaScript can pass any shape
+ modelConfiguration: [],
+ // @ts-expect-error apps written in JavaScript can pass any shape
+ isSystem: 'true',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toEqual([
+ `Agent 'sales-assistant' isSystem must be a boolean`,
+ `Agent 'sales-assistant' modelConfiguration must be an object`,
+ ]);
+ });
+
it('should accept triggers', () => {
const result = defineAgent({
...VALID_AGENT_CONFIG,
diff --git a/packages/twenty-sdk/src/sdk/define/agents/define-agent.ts b/packages/twenty-sdk/src/sdk/define/agents/define-agent.ts
index b93d9ccec65..ede9bbf8071 100644
--- a/packages/twenty-sdk/src/sdk/define/agents/define-agent.ts
+++ b/packages/twenty-sdk/src/sdk/define/agents/define-agent.ts
@@ -1,15 +1,25 @@
-import { isNonEmptyString } from '@sniptt/guards';
+import { isBoolean, isNonEmptyString } from '@sniptt/guards';
+import { type ModelConfiguration } from 'twenty-shared/ai';
import {
AGENT_TRIGGER_EVENT_NAME_PATTERN,
AGENT_TRIGGER_LIMITS,
AGENT_TRIGGER_TYPES,
type AgentManifest,
} from 'twenty-shared/application';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
import { validate as uuidValidate } from 'uuid';
import { type DefineEntity } from '@/sdk/define/common/types/define-entity.type';
import { createValidationResult } from '@/sdk/define/common/utils/create-validation-result';
+// Keyed by every ModelConfiguration key so a new capability fails to compile until listed
+const MODEL_CAPABILITIES: Record<keyof ModelConfiguration, true> = {
+ webSearch: true,
+ twitterSearch: true,
+};
+
+const MODEL_CAPABILITY_NAMES = new Set(Object.keys(MODEL_CAPABILITIES));
+
export const defineAgent: DefineEntity<AgentManifest> = (config) => {
const errors: string[] = [];
const warnings: string[] = [];
@@ -36,6 +46,47 @@ export const defineAgent: DefineEntity<AgentManifest> = (config) => {
);
}
+ if (isDefined(config.isSystem) && !isBoolean(config.isSystem)) {
+ errors.push(`Agent '${config.name}' isSystem must be a boolean`);
+ }
+
+ if (
+ isDefined(config.modelConfiguration) &&
+ !isPlainObject(config.modelConfiguration)
+ ) {
+ errors.push(`Agent '${config.name}' modelConfiguration must be an object`);
+ }
+
+ for (const [capability, capabilityConfiguration] of Object.entries(
+ isPlainObject(config.modelConfiguration) ? config.modelConfiguration : {},
+ )) {
+ if (!MODEL_CAPABILITY_NAMES.has(capability)) {
+ errors.push(
+ `Agent '${config.name}' modelConfiguration.${capability} is not supported, use one of: ${[...MODEL_CAPABILITY_NAMES].join(', ')}`,
+ );
+ continue;
+ }
+
+ if (
+ !isPlainObject(capabilityConfiguration) ||
+ !isBoolean(capabilityConfiguration.enabled)
+ ) {
+ errors.push(
+ `Agent '${config.name}' modelConfiguration.${capability}.enabled must be a boolean`,
+ );
+ continue;
+ }
+
+ if (
+ isDefined(capabilityConfiguration.configuration) &&
+ !isPlainObject(capabilityConfiguration.configuration)
+ ) {
+ errors.push(
+ `Agent '${config.name}' modelConfiguration.${capability}.configuration must be an object`,
+ );
+ }
+ }
+
if (
isNonEmptyString(config.roleUniversalIdentifier) &&
!uuidValidate(config.roleUniversalIdentifier)
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 bc87f456cbb..c27091c80ad 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
@@ -45,6 +45,15 @@ describe('defineWorkflow', () => {
});
});
+ it('accepts a workflow flagged as system', () => {
+ const systemWorkflow = { ...workflow, isSystem: true };
+
+ expect(defineWorkflow(systemWorkflow)).toMatchObject({
+ success: true,
+ config: systemWorkflow,
+ });
+ });
+
it.each([
{
problem: 'a step type applications cannot use',
@@ -63,6 +72,11 @@ describe('defineWorkflow', () => {
},
error: expect.stringMatching(/^version\.trigger\.type: .*MANUAL/),
},
+ {
+ problem: 'an isSystem that is not a boolean',
+ definition: { ...workflow, isSystem: 'true' },
+ error: 'isSystem: Invalid input: expected boolean, received string',
+ },
{
problem: 'a cycle',
definition: withStep({ nextStepIds: [STEP_ID] }),
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts
index 50c95c2998e..345564f381d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts
@@ -13,7 +13,9 @@ const CRON_TRIGGER_UID = '44444444-4444-4444-8444-444444444444';
const DATABASE_EVENT_TRIGGER_UID = '55555555-5555-4555-8555-555555555555';
const NOW = '2026-09-14T10:00:00.000Z';
-const AGENT_MANIFEST: Required<AgentManifest> = {
+const AGENT_MANIFEST: Required<
+ Omit<AgentManifest, 'modelConfiguration' | 'isSystem'>
+> = {
universalIdentifier: AGENT_UID,
name: 'lead-scorer',
label: 'Lead Scorer',
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
index 8e85cfba49c..87fc5f27183 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
@@ -78,6 +78,15 @@ describe('application workflow definitions', () => {
});
});
+ it('keeps the isSystem flag of the definition', () => {
+ const { workflow } = convert({
+ ...options,
+ manifest: { ...manifest, isSystem: true },
+ });
+
+ expect(workflow.isSystem).toBe(true);
+ });
+
it('updates the same version and keeps graph identity across updates', () => {
const before = convert(options);
const existingWorkflow: FlatWorkflow = {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts
index 97a2ae0cd73..3b4f17838b3 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts
@@ -83,7 +83,7 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
universalIdentifier: definition.universalIdentifier,
applicationUniversalIdentifier,
name: definition.name,
- isSystem: false,
+ isSystem: definition.isSystem ?? false,
visibility: WorkflowVisibility.WORKSPACE,
createdByUserWorkspaceId: null,
workspaceWorkflowId: null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/from-agent-manifest-to-universal-flat-agent.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/from-agent-manifest-to-universal-flat-agent.util.spec.ts
new file mode 100644
index 00000000000..63cc5f3bd55
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/from-agent-manifest-to-universal-flat-agent.util.spec.ts
@@ -0,0 +1,73 @@
+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';
+import { type AgentManifest } from 'twenty-shared/application';
+
+import { fromAgentManifestToUniversalFlatAgent } from 'src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util';
+
+const APPLICATION_UNIVERSAL_IDENTIFIER = '66666666-6666-4666-8666-666666666666';
+const NOW = '2026-10-27T10:00:00.000Z';
+
+const AGENT_MANIFEST: AgentManifest = {
+ universalIdentifier: '11111111-1111-4111-8111-111111111111',
+ name: 'sales-assistant',
+ label: 'Sales Assistant',
+ prompt: 'Help the sales team.',
+};
+
+const convert = (agentManifest: AgentManifest) =>
+ fromAgentManifestToUniversalFlatAgent({
+ agentManifest,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ now: NOW,
+ });
+
+describe('fromAgentManifestToUniversalFlatAgent', () => {
+ it('defaults the optional properties', () => {
+ expect(convert(AGENT_MANIFEST)).toMatchObject({
+ universalIdentifier: AGENT_MANIFEST.universalIdentifier,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ icon: null,
+ description: null,
+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ responseFormat: { type: 'text' },
+ modelConfiguration: null,
+ triggers: [],
+ isSystem: false,
+ });
+ });
+
+ it('keeps the model configuration and isSystem of the definition', () => {
+ const modelConfiguration = {
+ webSearch: { enabled: true, configuration: { maxResults: 5 } },
+ twitterSearch: { enabled: false },
+ };
+
+ expect(
+ convert({ ...AGENT_MANIFEST, modelConfiguration, isSystem: true }),
+ ).toMatchObject({ modelConfiguration, isSystem: true });
+ });
+
+ it('gives the triggers their universal identifier as id', () => {
+ const triggerUniversalIdentifier = '22222222-2222-4222-8222-222222222222';
+
+ expect(
+ convert({
+ ...AGENT_MANIFEST,
+ triggers: [
+ {
+ universalIdentifier: triggerUniversalIdentifier,
+ type: 'CRON',
+ settings: { pattern: '0 9 * * 1' },
+ },
+ ],
+ }).triggers,
+ ).toEqual([
+ {
+ id: triggerUniversalIdentifier,
+ type: 'CRON',
+ settings: { pattern: '0 9 * * 1' },
+ isActive: true,
+ instructions: null,
+ },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util.ts
index d0475ff92fa..53e5fcd3700 100644
--- a/packages/twenty-server/src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util.ts
@@ -26,7 +26,7 @@ export const fromAgentManifestToUniversalFlatAgent = ({
(agentManifest.modelId as ModelId) ??
AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
responseFormat: agentManifest.responseFormat ?? { type: 'text' },
- modelConfiguration: null,
+ modelConfiguration: agentManifest.modelConfiguration ?? null,
triggers: (agentManifest.triggers ?? []).map(
({ universalIdentifier, isActive, instructions, ...trigger }) => ({
...trigger,
@@ -36,7 +36,7 @@ export const fromAgentManifestToUniversalFlatAgent = ({
}),
),
isCustom: false,
- isSystem: true,
+ isSystem: agentManifest.isSystem ?? false,
createdAt: now,
updatedAt: now,
deletedAt: null,
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 7c3f6f866c7..0dcc63809e8 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
@@ -2,7 +2,9 @@ import { type DiscoveryService } from '@nestjs/core';
import { PermissionFlagType } from 'twenty-shared/constants';
import { FeatureFlagKey, FieldActorSource } from 'twenty-shared/types';
+import { WorkflowActionType } from 'twenty-shared/workflow';
+import { type ApplicationService } from 'src/engine/core-modules/application/application.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
@@ -11,16 +13,19 @@ import { type AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent
import { CreateAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/create-agent.tool';
import { DeleteAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool';
import { ListAgentsTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool';
+import { ManageableAgentService } from 'src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service';
import { UpdateAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/update-agent.tool';
import { type AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { type PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
const workspaceId = 'workspace-id';
const agentId = '20202020-0000-4000-8000-000000000001';
const roleId = '20202020-0000-4000-8000-000000000002';
const existingTriggerId = '20202020-0000-4000-8000-000000000003';
+const workspaceCustomApplicationId = 'application-id';
const buildAgent = (overrides: Record<string, unknown> = {}) => ({
id: agentId,
@@ -32,7 +37,7 @@ const buildAgent = (overrides: Record<string, unknown> = {}) => ({
modelId: 'workspace-default-model',
roleId,
triggers: [],
- applicationId: 'application-id',
+ applicationId: workspaceCustomApplicationId,
isCustom: true,
isSystem: false,
...overrides,
@@ -76,6 +81,18 @@ const buildAgentTools = (options?: {
const aiModelRegistryService = {
validateModelAvailability: jest.fn(),
};
+ const applicationService = {
+ findWorkspaceTwentyStandardAndCustomApplicationOrThrow: jest
+ .fn()
+ .mockResolvedValue({
+ workspaceCustomFlatApplication: { id: workspaceCustomApplicationId },
+ }),
+ };
+ const workspaceCacheService = {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ flatWorkflowVersionMaps: { byUniversalIdentifier: {} },
+ }),
+ };
const permissionsService = {
checkRolesPermissions: jest
.fn()
@@ -88,6 +105,12 @@ const buildAgentTools = (options?: {
}),
};
+ const manageableAgentService = new ManageableAgentService(
+ agentService as unknown as AgentService,
+ applicationService as unknown as ApplicationService,
+ workspaceCacheService as unknown as WorkspaceCacheService,
+ );
+
const tools = [
new ListAgentsTool(agentService as unknown as AgentService),
new CreateAgentTool(
@@ -97,8 +120,12 @@ const buildAgentTools = (options?: {
new UpdateAgentTool(
agentService as unknown as AgentService,
aiModelRegistryService as unknown as AiModelRegistryService,
+ manageableAgentService,
+ ),
+ new DeleteAgentTool(
+ agentService as unknown as AgentService,
+ manageableAgentService,
),
- new DeleteAgentTool(agentService as unknown as AgentService),
];
const definedToolRegistryService = new DefinedToolRegistryService(
@@ -145,9 +172,25 @@ const buildAgentTools = (options?: {
agentService,
aiModelRegistryService,
permissionsService,
+ workspaceCacheService,
};
};
+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 () => {
@@ -379,10 +422,11 @@ describe('Agent tools', () => {
});
it('refuses to change an agent backing a workflow step', async () => {
- const { executeTool, agentService } = buildAgentTools();
+ const { executeTool, agentService, workspaceCacheService } =
+ buildAgentTools();
- agentService.findOneAgentById.mockResolvedValue(
- buildAgent({ isSystem: true }),
+ workspaceCacheService.getOrRecompute.mockResolvedValue(
+ workflowVersionsWithAgentStep,
);
await expect(
@@ -413,10 +457,11 @@ describe('Agent tools', () => {
});
it('refuses to delete an agent backing a workflow step', async () => {
- const { executeTool, agentService } = buildAgentTools();
+ const { executeTool, agentService, workspaceCacheService } =
+ buildAgentTools();
- agentService.findOneAgentById.mockResolvedValue(
- buildAgent({ isSystem: true }),
+ workspaceCacheService.getOrRecompute.mockResolvedValue(
+ workflowVersionsWithAgentStep,
);
await expect(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/agent-tools.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/agent-tools.module.ts
index 22793be9bce..5a9a481ef96 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/agent-tools.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/agent-tools.module.ts
@@ -1,14 +1,18 @@
import { Module } from '@nestjs/common';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { CreateAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/create-agent.tool';
import { DeleteAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/delete-agent.tool';
+import { ManageableAgentService } from 'src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service';
import { ListAgentsTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool';
import { UpdateAgentTool } from 'src/engine/metadata-modules/ai/ai-agent/tools/update-agent.tool';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
- imports: [AiAgentModule],
+ imports: [AiAgentModule, ApplicationModule, WorkspaceCacheModule],
providers: [
+ ManageableAgentService,
ListAgentsTool,
CreateAgentTool,
UpdateAgentTool,
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 9592586b24e..3dfa1e2aceb 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
@@ -8,7 +8,7 @@ import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-
import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/types/tool-execute-args.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 { findManageableAgentOrThrow } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/find-manageable-agent-or-throw.util';
+import { ManageableAgentService } from 'src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service';
const deleteAgentInputSchema = z.object({
id: z.uuid().describe('Id of the agent to delete'),
@@ -24,7 +24,10 @@ const deleteAgentInputSchema = z.object({
export class DeleteAgentTool extends BaseTool<typeof deleteAgentInputSchema> {
readonly inputSchema = deleteAgentInputSchema;
- constructor(private readonly agentService: AgentService) {
+ constructor(
+ private readonly agentService: AgentService,
+ private readonly manageableAgentService: ManageableAgentService,
+ ) {
super();
}
@@ -32,9 +35,8 @@ export class DeleteAgentTool extends BaseTool<typeof deleteAgentInputSchema> {
input,
context,
}: ToolExecuteArgs<typeof deleteAgentInputSchema>): Promise<ToolOutput> {
- await findManageableAgentOrThrow({
+ await this.manageableAgentService.findManageableAgentOrThrow({
agentId: input.id,
- agentService: this.agentService,
context,
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
index ef5b4dba792..a96dedf6e58 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
@@ -18,7 +18,7 @@ const listAgentsInputSchema = z.object({});
category: ToolCategory.AGENT,
requiredPermissionFlags: [PermissionFlagType.AI_SETTINGS],
requiredFeatureFlags: [FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED],
- description: `List the AI agents of the workspace with their prompt, model, role and triggers. System agents (those backing workflow AI steps or installed by an application) are not included.`,
+ description: `List the AI agents of the workspace with their prompt, model, role and triggers. System agents, such as those backing workflow AI steps, are not included. Agents installed by an application are listed, but only that application can change them.`,
})
export class ListAgentsTool extends BaseTool<typeof listAgentsInputSchema> {
readonly inputSchema = listAgentsInputSchema;
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
new file mode 100644
index 00000000000..a254c3f2f0b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
@@ -0,0 +1,79 @@
+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({
+ agentId,
+ context,
+ }: {
+ agentId: string;
+ context: ToolProviderContext;
+ }): Promise<FlatAgentWithRoleId> {
+ const agent = await this.agentService.findOneAgentById({
+ id: agentId,
+ workspaceId: context.workspaceId,
+ });
+
+ if (
+ !canCallerReachApplication({
+ callingApplication: context.application,
+ applicationId: agent.applicationId,
+ })
+ ) {
+ throw new AiException('Agent not found', AiExceptionCode.AGENT_NOT_FOUND);
+ }
+
+ const { workspaceCustomFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId: context.workspaceId },
+ );
+
+ if (agent.applicationId !== workspaceCustomFlatApplication.id) {
+ throw new AiException(
+ 'This agent is defined by an installed application: change it in that application',
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+ }
+
+ 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-agent/tools/update-agent.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/update-agent.tool.ts
index fb591679003..daad5ce7d57 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/update-agent.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/update-agent.tool.ts
@@ -10,7 +10,7 @@ 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 { agentTriggersSchema } from 'src/engine/metadata-modules/ai/ai-agent/tools/schemas/agent-trigger.schema';
-import { findManageableAgentOrThrow } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/find-manageable-agent-or-throw.util';
+import { ManageableAgentService } from 'src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service';
import { toAgentSummary } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/to-agent-summary.util';
import { toAgentTriggers } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/to-agent-triggers.util';
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
@@ -49,6 +49,7 @@ export class UpdateAgentTool extends BaseTool<typeof updateAgentInputSchema> {
constructor(
private readonly agentService: AgentService,
private readonly aiModelRegistryService: AiModelRegistryService,
+ private readonly manageableAgentService: ManageableAgentService,
) {
super();
}
@@ -57,9 +58,8 @@ export class UpdateAgentTool extends BaseTool<typeof updateAgentInputSchema> {
input: { triggers, ...parameters },
context,
}: ToolExecuteArgs<typeof updateAgentInputSchema>): Promise<ToolOutput> {
- await findManageableAgentOrThrow({
+ await this.manageableAgentService.findManageableAgentOrThrow({
agentId: parameters.id,
- agentService: this.agentService,
context,
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/__tests__/is-agent-backing-workflow-step.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/__tests__/is-agent-backing-workflow-step.util.spec.ts
new file mode 100644
index 00000000000..703cffc563f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/__tests__/is-agent-backing-workflow-step.util.spec.ts
@@ -0,0 +1,55 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { isAgentBackingWorkflowStep } from 'src/engine/metadata-modules/ai/ai-agent/tools/utils/is-agent-backing-workflow-step.util';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const agentId = '20202020-0000-4000-8000-000000000001';
+
+const buildStep = ({
+ type,
+ agentId,
+}: {
+ type: WorkflowActionType;
+ agentId: string;
+}) => ({ type, settings: { input: { agentId } } }) as WorkflowAction;
+
+describe('isAgentBackingWorkflowStep', () => {
+ it('returns true when an AI agent step references the agent', () => {
+ expect(
+ isAgentBackingWorkflowStep({
+ agentId,
+ flatWorkflowVersions: [
+ { steps: null },
+ {
+ steps: [buildStep({ type: WorkflowActionType.AI_AGENT, agentId })],
+ },
+ ],
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false when only another agent or another step type matches', () => {
+ expect(
+ isAgentBackingWorkflowStep({
+ agentId,
+ flatWorkflowVersions: [
+ {
+ steps: [
+ buildStep({
+ type: WorkflowActionType.AI_AGENT,
+ agentId: 'other-agent-id',
+ }),
+ buildStep({ type: WorkflowActionType.CODE, agentId }),
+ ],
+ },
+ ],
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false without workflow versions', () => {
+ expect(
+ isAgentBackingWorkflowStep({ agentId, flatWorkflowVersions: [] }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/find-manageable-agent-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/find-manageable-agent-or-throw.util.ts
deleted file mode 100644
index 3a50127a737..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/find-manageable-agent-or-throw.util.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-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 { type 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';
-
-export const findManageableAgentOrThrow = async ({
- agentId,
- agentService,
- context,
-}: {
- agentId: string;
- agentService: AgentService;
- context: ToolProviderContext;
-}): Promise<FlatAgentWithRoleId> => {
- const agent = await agentService.findOneAgentById({
- id: agentId,
- workspaceId: context.workspaceId,
- });
-
- if (
- !canCallerReachApplication({
- callingApplication: context.application,
- applicationId: agent.applicationId,
- })
- ) {
- throw new AiException('Agent not found', AiExceptionCode.AGENT_NOT_FOUND);
- }
-
- if (agent.isSystem) {
- throw new AiException(
- 'This agent is managed by a workflow AI step or an installed application: configure a workflow step agent 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-agent/tools/utils/is-agent-backing-workflow-step.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/is-agent-backing-workflow-step.util.ts
new file mode 100644
index 00000000000..46e863c66ef
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/utils/is-agent-backing-workflow-step.util.ts
@@ -0,0 +1,18 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+
+export const isAgentBackingWorkflowStep = ({
+ agentId,
+ flatWorkflowVersions,
+}: {
+ agentId: string;
+ flatWorkflowVersions: Pick<FlatWorkflowVersion, 'steps'>[];
+}): boolean =>
+ flatWorkflowVersions.some((flatWorkflowVersion) =>
+ (flatWorkflowVersion.steps ?? []).some(
+ (step) =>
+ step.type === WorkflowActionType.AI_AGENT &&
+ step.settings?.input?.agentId === agentId,
+ ),
+ );
diff --git a/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-agent-tools.integration-spec.ts.snap b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-agent-tools.integration-spec.ts.snap
index 7568ce265ab..2520857db08 100644
--- a/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-agent-tools.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-agent-tools.integration-spec.ts.snap
@@ -3,7 +3,7 @@
exports[`MCP agent tools (integration) should describe the agent tools to the model 1`] = `
[
{
- "description": "List the AI agents of the workspace with their prompt, model, role and triggers. System agents (those backing workflow AI steps or installed by an application) are not included.",
+ "description": "List the AI agents of the workspace with their prompt, model, role and triggers. System agents, such as those backing workflow AI steps, are not included. Agents installed by an application are listed, but only that application can change them.",
"inputSchema": {
"properties": {},
"type": "object",
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-agent.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-agent.integration-spec.ts
index 4a0cd151ad6..fce11529eb1 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-agent.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-agent.integration-spec.ts
@@ -12,7 +12,7 @@ const TEST_AGENT_ID = uuidv4();
const TEST_SECOND_AGENT_ID = uuidv4();
const AGENT_GQL_FIELDS =
- 'id name label description prompt icon applicationId modelId';
+ 'id name label description prompt icon applicationId modelId modelConfiguration isSystem';
const buildManifest = (overrides?: Partial<Pick<Manifest, 'agents'>>) =>
buildBaseManifest({ appId: TEST_APP_ID, roleId: TEST_ROLE_ID, overrides });
@@ -140,6 +140,62 @@ describe('Manifest update - agents', () => {
});
}, 60000);
+ it('should sync the model configuration and isSystem of an agent', async () => {
+ const salesAssistant = {
+ universalIdentifier: TEST_AGENT_ID,
+ name: 'sales-assistant',
+ label: 'Sales Assistant',
+ prompt: 'You are a sales assistant.',
+ };
+
+ await syncApplication({
+ manifest: buildManifest({
+ agents: [
+ {
+ ...salesAssistant,
+ modelConfiguration: { webSearch: { enabled: true } },
+ },
+ ],
+ }),
+ expectToFail: false,
+ });
+
+ const agentsAfterFirstSync = await findAppAgents();
+
+ expect(agentsAfterFirstSync).toHaveLength(1);
+ expect(agentsAfterFirstSync[0]).toMatchObject({
+ modelConfiguration: { webSearch: { enabled: true } },
+ isSystem: false,
+ });
+
+ await syncApplication({
+ manifest: buildManifest({
+ agents: [
+ {
+ ...salesAssistant,
+ modelConfiguration: {
+ webSearch: { enabled: false },
+ twitterSearch: { enabled: true },
+ },
+ isSystem: true,
+ },
+ ],
+ }),
+ expectToFail: false,
+ });
+
+ const agentsAfterSecondSync = await findAppAgents();
+
+ expect(agentsAfterSecondSync).toHaveLength(1);
+ expect(agentsAfterSecondSync[0]).toMatchObject({
+ modelConfiguration: {
+ webSearch: { enabled: false },
+ twitterSearch: { enabled: true },
+ },
+ isSystem: true,
+ });
+ }, 60000);
+
it('should delete an agent when removed from manifest on second sync', async () => {
await syncApplication({
manifest: buildManifest({
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
index 47ba9108320..dd7eed77dcb 100644
--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -521,3 +521,18 @@ describe('workflow manifest database event trigger', () => {
]);
});
});
+
+describe('workflow manifest isSystem', () => {
+ it('accepts a workflow flagged as system', () => {
+ expect(
+ workflowManifestSchema.safeParse({ ...workflow, isSystem: true }).success,
+ ).toBe(true);
+ });
+
+ it('rejects an isSystem that is not a boolean', () => {
+ expect(
+ workflowManifestSchema.safeParse({ ...workflow, isSystem: 'true' })
+ .success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-shared/src/application/agentManifestType.ts b/packages/twenty-shared/src/application/agentManifestType.ts
index 47c21033f1f..7e205b5564f 100644
--- a/packages/twenty-shared/src/application/agentManifestType.ts
+++ b/packages/twenty-shared/src/application/agentManifestType.ts
@@ -1,4 +1,5 @@
import { type AgentResponseFormat } from '@/ai/types/AgentResponseFormat';
+import { type ModelConfiguration } from '@/ai/types/ModelConfiguration';
import { type AgentTriggerManifest } from '@/application/agentTriggerType';
import { type SyncableEntityOptions } from '@/application/syncableEntityOptionsType';
@@ -10,6 +11,8 @@ export type AgentManifest = SyncableEntityOptions & {
prompt: string;
modelId?: string;
responseFormat?: AgentResponseFormat;
+ modelConfiguration?: ModelConfiguration;
+ isSystem?: boolean;
roleUniversalIdentifier?: string;
triggers?: AgentTriggerManifest[];
};
diff --git a/packages/twenty-shared/src/application/workflowManifestType.ts b/packages/twenty-shared/src/application/workflowManifestType.ts
index 5bcdc1e26e5..949b6d43812 100644
--- a/packages/twenty-shared/src/application/workflowManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowManifestType.ts
@@ -12,6 +12,7 @@ export const workflowManifestSchema = z
.strictObject({
universalIdentifier: z.uuid(),
name: z.string().min(1),
+ isSystem: z.boolean().optional(),
version: z.strictObject({
trigger: workflowTriggerManifestSchema,
steps: z.array(workflowStepManifestSchema).min(1),