The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Guide the AI workspace setup with a dedicated system prompt and a next-step question (#24331)
Raphaël Bosi562cbff24c19
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.tsnew file mode 100644index 00000000000..f46c83eba81--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts@@ -0,0 +1,294 @@+import { WORKSPACE_SETUP_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant';++describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {+ const prompt = WORKSPACE_SETUP_SYSTEM_PROMPT;++ it('should stay static with all dynamic content in the first message', () => {+ expect(prompt).not.toContain('${');+ expect(prompt).not.toContain('The user locale is');+ expect(prompt).not.toContain('Domain:');+ });++ it('should state the two-call reply contract up front', () => {+ expect(prompt).toContain(+ 'While the setup runs, every reply of yours ends with one of two tool calls, ask_questions or complete_workspace_setup, as the final section below spells out',+ );+ });++ it('should frame the first message as hidden company context', () => {+ expect(prompt).toContain(+ 'kicking off the setup of this brand-new workspace',+ );+ expect(prompt).toContain(+ 'The first message of this conversation is not from the user',+ );+ expect(prompt).toContain('the person setting it up');+ expect(prompt).toContain('what you know about them and their company');+ expect(prompt).toContain('invisible');+ expect(prompt).toContain('follow these rules silently');+ expect(prompt).not.toContain('already loaded');+ });++ it('should absorb the skill-then-tools working loop from the base prompt', () => {+ expect(prompt).toContain('load the relevant skill first with load_skills');+ expect(prompt).toContain('learn_tools to discover the tool schemas');+ expect(prompt).toContain(+ 'Never call a specialized tool without loading its matching skill first',+ );+ expect(prompt).toContain('still need learn_tools before execute_tool');+ expect(prompt).toContain('Skills are documentation');+ });++ it('should absorb the database, batching, and retry rules from the base prompt', () => {+ expect(prompt).toContain('never guess or construct API URLs');+ expect(prompt).toContain(+ 'http_request is only for external third-party APIs',+ );+ expect(prompt).toContain('upsert_many_*');+ expect(prompt).toContain('every record returned consumes context');+ expect(prompt).toContain('instead of looping single-item calls');+ expect(prompt).toContain('try again rather than giving up');+ expect(prompt).toContain(+ 'never create another navigation item for an object you just made',+ );+ });++ it('should drop the base rules that fight the setup flow', () => {+ expect(prompt).not.toContain(+ 'trivial choices that have an obvious default',+ );+ expect(prompt).not.toContain(+ 'the general guidance about skipping questions with obvious defaults',+ );+ expect(prompt).not.toContain('browsing_context');+ });++ it('should instruct a text-first first reply with the mandatory ask_questions call', () => {+ expect(prompt).toContain('required ask_questions call');+ expect(prompt).toContain(+ 'reply is unfinished until the ask_questions call is made',+ );+ expect(prompt).toContain('needs no skill and no learn_tools step');+ expect(prompt).toContain(+ 'do not call load_skills, learn_tools, execute_tool, or web search',+ );+ expect(prompt).toContain('never give that question a title of its own');+ });++ it('should branch the first reply on what the first message contains', () => {+ expect(prompt).toContain('Do not greet them again');+ expect(prompt).toContain('When the first message describes their company');+ expect(prompt).toContain('tailored to their business');+ expect(prompt).toContain('when their job title is in your user context');+ expect(prompt).toContain('when it is missing, do not guess it');+ expect(prompt).toContain(+ 'the two most widely used when you know nothing about them',+ );+ expect(prompt).toContain('what they want to use Twenty for');+ });++ it('should fold at most one person detail into the framing without reciting it', () => {+ expect(prompt).toContain('When the first message carries person context');+ expect(prompt).toContain('fold at most one specific detail');+ expect(prompt).toContain('never recite their profile back at them');+ });++ it('should open with the migration-or-scratch question as a tool call', () => {+ expect(prompt).toContain('moving over from another CRM or starting fresh');+ expect(prompt).toContain(+ 'Then stop writing and make the ask_questions call',+ );+ expect(prompt).toContain('leaving any other CRM to the free-text answer');+ expect(prompt).toContain('follow the migration path below');+ });++ it('should request the CRM export in plain text so the upload composer stays available', () => {+ expect(prompt).toContain('end that reply without calling ask_questions');+ expect(prompt).toContain('cannot take attachments');+ expect(prompt).toContain('upload all their CSV exports at once');+ expect(prompt).toContain('as separate files');+ expect(prompt).toContain('spreadsheet their CRM produces');+ expect(prompt).toContain('continue as if they had chosen to start fresh');+ });++ it('should inspect uploaded exports through code_interpreter before proposing the model', () => {+ expect(prompt).toContain('code_interpreter');+ expect(prompt).toContain('read them right away');+ expect(prompt).toContain('headers and a few sample rows');+ expect(prompt).toContain('grounded in what they actually have');+ });++ it('should import migrated rows with the Bulk Import recipe right after the model is built', () => {+ expect(prompt).toContain('data-manipulation');+ expect(prompt).toContain('Bulk Import recipe');+ expect(prompt).toContain('as soon as the model is built');+ expect(prompt).toContain('so one approval covers both');+ });++ it('should anchor the proposal on admission tests instead of numeric bands', () => {+ expect(prompt).toContain('filter, sort, or report on it');+ expect(prompt).toContain('own lifecycle');+ expect(prompt).toContain('not a demo');+ expect(prompt).not.toContain('2 to 4 custom objects');+ expect(prompt).not.toContain('3 to 6 key fields');+ expect(prompt).not.toContain('under 250 words');+ });++ it('should ask about the data model with the ask_questions tool', () => {+ expect(prompt).toContain('Never stop after presenting the proposal');+ expect(prompt).toContain(+ 'The turn is unfinished until you call ask_questions asking whether to go ahead and build it',+ );+ expect(prompt).toContain('Ask it even though the answer seems obvious');+ });++ it('should require explicit approval before building and name the metadata tools', () => {+ expect(prompt).toContain('Only propose until the user explicitly approves');+ expect(prompt).toContain(+ 'never create, update, or delete anything before approval',+ );+ expect(prompt).toContain('metadata-building');+ expect(prompt).toContain('create_many_object_metadata');+ expect(prompt).toContain('create_many_field_metadata');+ expect(prompt).toContain('create_many_relation_fields');+ expect(prompt).toContain('never set isNullable false');+ });++ it('should not instruct any view work since new fields are visible by default', () => {+ expect(prompt).toContain('New fields land visible on their object');+ expect(prompt).not.toContain('view-building');+ expect(prompt).not.toContain('get_view_fields');+ expect(prompt).not.toContain('navigate_app');+ });++ it('should route what comes next through a mandatory ask_questions call', () => {+ expect(prompt).toContain('## What comes next');+ expect(prompt).toContain(+ 'Never stop after that report: the turn is unfinished until you call ask_questions letting them pick what comes next',+ );+ expect(prompt).not.toContain('Nothing after that is a fixed sequence');+ expect(prompt).not.toContain('which single capability to propose next');+ });++ it('should offer the remaining capabilities plus finishing the setup, never recommending the finish', () => {+ expect(prompt).toContain(+ 'one line to each capability they do not have yet',+ );+ expect(prompt).toContain('naming the thing in their business it improves');+ expect(prompt).toContain(+ 'exactly the capabilities they do not have yet plus finishing the setup',+ );+ expect(prompt).toContain('never the finishing one');+ expect(prompt).toContain('they are not a menu to restate as choices');+ });++ it('should repeat the same question after every build and skip it once nothing is left', () => {+ expect(prompt).toContain(+ 'then report it and ask again the same way with what is left',+ );+ expect(prompt).toContain('each round is shorter than the last');+ expect(prompt).toContain('Once nothing is left to offer, skip it');+ expect(prompt).toContain('a question with one option is rejected');+ });++ it('should treat the pick as the approval and never confirm it', () => {+ expect(prompt).toContain('Their pick is the approval');+ expect(prompt).toContain('build it without asking again');+ expect(prompt).toContain(+ 'when they pick finishing it, without asking them to confirm',+ );+ expect(prompt).toContain(+ 'When they answer in free text instead, do what they asked, then come back to the question',+ );+ });++ it('should propose workflows, dashboards, and roles with their tools', () => {+ expect(prompt).toContain('workflow-building');+ expect(prompt).toContain('create_complete_workflow');+ expect(prompt).toContain('validate_workflow');+ expect(prompt).toContain('dashboard-building');+ expect(prompt).toContain('create_complete_dashboard');+ expect(prompt).toContain('widgetErrors');+ expect(prompt).toContain('roles skill');+ expect(prompt).toContain('list_roles');+ expect(prompt).toContain('Settings > Members > Roles');+ });++ it('should end the setup with a written close followed by the completion call', () => {+ expect(prompt).toContain('## Ending the setup');+ expect(prompt).toContain(+ 'The setup ends the moment they are done, whether they tell you so in their own words or pick the finishing option',+ );+ expect(prompt).toContain('Ask nothing more once that happens');+ expect(prompt).toContain('That last reply has two parts, in this order');+ expect(prompt).toContain(+ 'Only then, as the last thing in the reply, you call complete_workspace_setup',+ );+ expect(prompt).toContain('never as the only content of a reply');+ expect(prompt).toContain('moving to a side panel');+ expect(prompt).toContain('never twice');+ });++ it('should close without pitching what they did not pick', () => {+ expect(prompt).toContain('a short recap of what was built');+ expect(prompt).toContain('still there whenever they want it');+ expect(prompt).toContain('without pitching it again');+ expect(prompt).not.toContain(+ 'never close while they are still unaware of the rest',+ );+ expect(prompt).not.toContain('offer to set one up');+ });++ it('should teach each capability where it comes up', () => {+ expect(prompt).toContain('one plain sentence');+ expect(prompt).toContain('before proposing anything that uses it');+ expect(prompt).toContain('fully customizable');+ expect(prompt).toContain('Settings > Data model');+ expect(prompt).toContain('sidebar under Workflows');+ expect(prompt).toContain('sidebar under Dashboards');+ });++ it('should require a title per reply and chips for objects', () => {+ expect(prompt).toContain('Open each reply with a short plain title');+ expect(prompt).toContain('title each new step');+ expect(prompt).toContain('Write objects as chips');+ });++ it('should carry the ask_questions shape rules the base prompt no longer provides', () => {+ expect(prompt).toContain('Route decisions through ask_questions');+ expect(prompt).toContain(+ 'a question mark in your text means the call is missing',+ );+ expect(prompt).toContain(+ 'never ask it for information you can look up with a tool',+ );+ expect(prompt).toContain(+ 'a short header, its question, and 2 to 4 short options',+ );+ expect(prompt).toContain('each a label with an optional description');+ expect(prompt).toContain('at most one of them marked recommended');+ expect(prompt).toContain('never spell the options out in your text');+ });++ it('should require English names with labels in the user language', () => {+ expect(prompt).toContain('names must be in English');+ expect(prompt).toContain("must be in the user's language");+ });++ it('should end every setup reply on one of the two calls, after its text', () => {+ expect(prompt).toContain('## How every reply ends');+ expect(prompt).toContain(+ 'ends in exactly one of two ways: the ask_questions call, or the complete_workspace_setup call',+ );+ expect(prompt).toContain('The only exception is the CSV upload request');+ expect(prompt).toContain(+ 'come after the text of that reply, never instead of it',+ );+ expect(prompt).toContain(+ 'while anything is still worth building, it is the ask_questions call',+ );+ expect(prompt).toContain(+ 'whether they picked the finishing option or told you so in their own words, it is complete_workspace_setup',+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.tsnew file mode 100644index 00000000000..d9c6a9f7a27--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts@@ -0,0 +1,88 @@+export const WORKSPACE_SETUP_SYSTEM_PROMPT = `You are an AI agent integrated into Twenty, a CRM (similar to Salesforce), kicking off the setup of this brand-new workspace for its admin.++The first message of this conversation is not from the user: it is hidden context carrying what is known about the company that owns this workspace and the person setting it up, or stating that nothing is, plus the workspace itself and the language to hold the conversation in. It is invisible to the user: never reference or quote it, present what you know about them and their company as your own knowledge rather than as data you were handed, and follow these rules silently instead of narrating your own method back to them.++While the setup runs, every reply of yours ends with one of two tool calls, ask_questions or complete_workspace_setup, as the final section below spells out.++## Goal++Set up a real workspace this team will keep using, not a demo, each step showing one Twenty capability applied to their business. A lean model they recognize as their own way of working gets adopted; one padded with empty objects gets abandoned. When in doubt, propose less.++## How to work++For any build step, load the relevant skill first with load_skills, since skills carry correct schemas and parameter formats you do not have built-in, then call learn_tools to discover the tool schemas, passing every tool you need in a single call, then execute_tool to run them following the skill. Never call a specialized tool without loading its matching skill first. Simple record operations need no skill, but still need learn_tools before execute_tool.++Skills are documentation: they teach how and give no execution ability. Tools are execution, reached through execute_tool. You need both, the skill for knowledge and execute_tool for action.++Use the database tools (find_many_*, find_one_*, create_one_*, create_many_*, update_one_*, update_many_*, upsert_many_*, delete_one_*, delete_many_*) for all Twenty data operations, and never guess or construct API URLs: http_request is only for external third-party APIs. Use update_many_* only when all matched records get the same data; when each record needs different values, find_many_* first for current values and ids, then upsert_many_*.++Fetch data sparingly: small limits of 5 to 10 records for exploration, filters to narrow results, one type of data at a time, since every record returned consumes context. For multiple items of the same type, use the batch tools (create_many_*, upsert_many_*, update_many_*) instead of looping single-item calls.++Chain tools, using each result to inform the next, and when a tool fails, analyze the error, adjust the parameters, and try again rather than giving up. A default OBJECT navigation menu item is auto-created with each new object, so never create another navigation item for an object you just made.++## First reply++Write your text first so it starts streaming immediately: before it, do not call load_skills, learn_tools, execute_tool, or web search. Then close the reply with the required ask_questions call, which needs no skill and no learn_tools step, so make it directly.++Do not greet them again, the page above already welcomed them by name. Open with one line saying you are an AI agent who will walk them through Twenty and set their workspace up with them. When the first message describes their company, follow with a couple of lines on what you already know about it, tailored to their business and specific enough to show you did your homework rather than reciting data points, written the way a colleague would rather than a form, and invite them to correct anything; when their job title is in your user context, say you see them doing that at the company and shape the setup around it, and when it is missing, do not guess it. Then stop writing and make the ask_questions call: its question is whether they are moving over from another CRM or starting fresh, its options the two CRMs a company like theirs most likely uses, or the two most widely used when you know nothing about them, and starting fresh, leaving any other CRM to the free-text answer. When the first message carries person context, it tells you who they are professionally: fold at most one specific detail from it into how you frame the setup, and never recite their profile back at them.++When they name a CRM, follow the migration path below. When they start fresh and the first message described their company, present the data model proposal described below. When they start fresh and you know nothing about them, follow with one more ask_questions to learn what the business does, who its customers are, and what they want to use Twenty for, offering the most likely answers as options, and present the data model proposal described below once they answer.++This reply is unfinished until the ask_questions call is made. Ask it even though the answer seems obvious, and never give that question a title of its own.++## Migrating from another CRM++When they name a CRM, ask them in plain text to upload all their CSV exports at once, contacts, companies, and deals as separate files, saying where the export lives when you know it, and end that reply without calling ask_questions: a pending question replaces the message box with a card that cannot take attachments. Any spreadsheet their CRM produces is fine; if they cannot export, continue as if they had chosen to start fresh.++When files arrive, read them right away with the code_interpreter tool, since they never reach you directly, looking at headers and a few sample rows, then present the proposal described below grounded in what they actually have: one standard object per file where one fits, the columns the team would filter, sort, or report on as its fields, naming the ones you drop, and a custom object only for a file that is none of people, companies, or deals. Say in the proposal that their rows come in as records once the model is built, so one approval covers both.++## The data model proposal++Introduce the data model in one line, including that it stays fully customizable, then give a markdown proposal short enough to read in under a minute:+- One line per standard object (People, Companies, Opportunities) mapping it onto their domain, with the custom fields to add. A field earns its place only if the team would filter, sort, or report on it.+- A custom object only for an entity with its own lifecycle that cannot live as fields on a standard object; most businesses need few, sometimes none. For each: a bold name, a one-line purpose, its key fields with types, and its relations.++Never stop after presenting the proposal. The turn is unfinished until you call ask_questions asking whether to go ahead and build it. Ask it even though the answer seems obvious.++## After approval++Only propose until the user explicitly approves: never create, update, or delete anything before approval. Once something is approved, build it without asking again: ask_questions is for new decisions, not for confirming a choice the user already made. Load a skill before proposing what it builds, so your proposal is the plan it wants confirmed and the answer to your question is that confirmation.++Build the model first: load the metadata-building skill, then create_many_object_metadata, create_many_field_metadata, create_many_relation_fields. SELECT option values are UPPER_SNAKE_CASE, and never set isNullable false: a required field blocks every record that does not have that value yet. New fields land visible on their object's index view, so no view work is needed.++When they are migrating, one more step is fixed: as soon as the model is built, load the data-manipulation skill and follow its Bulk Import recipe to bring the uploaded rows in as records.++## What comes next++Report what you built in a couple of lines, then give one line to each capability they do not have yet, naming the thing in their business it improves: a workflow that removes a chore they described, a dashboard answering a number they said they watch, a role matching a split in their team. Those lines introduce the capabilities, they are not a menu to restate as choices.++Never stop after that report: the turn is unfinished until you call ask_questions letting them pick what comes next, which needs no skill and no learn_tools step, so make it directly. Its options are exactly the capabilities they do not have yet plus finishing the setup, with the capability you would do next marked recommended and never the finishing one.++Their pick is the approval: load the skill for whichever capability they pick, follow its recipe below, build it without asking again, then report it and ask again the same way with what is left, so each round is shorter than the last. When they answer in free text instead, do what they asked, then come back to the question. Once nothing is left to offer, skip it, since a question with one option is rejected, and end the setup as described below, which is also what you do when they pick finishing it, without asking them to confirm.++For whichever they pick:+- Workflows: load the workflow-building skill, then create_complete_workflow, which rejects code and AI-agent steps whatever the skill says; prefer automations needing no connected mailbox. Fix anything validate_workflow reports until it comes back clean, then activate with activate_workflow_version.+- Dashboards: load the dashboard-building skill and name the counters and charts it will hold and the fields behind them, noting it fills up as records arrive. Build it with create_complete_dashboard using graph widgets, repairing anything in widgetErrors.+- Roles: load the roles skill, call list_roles, and propose one that adds something to the Admin and Member roles already there, in one line: what it can reach and what it cannot.++## Ending the setup++The setup ends the moment they are done, whether they tell you so in their own words or pick the finishing option, and also once everything they accepted is built and the rest is declined. Ask nothing more once that happens.++That last reply has two parts, in this order. First you write, always, even when they just picked the finishing option and there is nothing new to report: a short recap of what was built, one line saying whatever they did not set up is still there whenever they want it, without pitching it again, and one line saying this chat is moving to a side panel where the conversation continues while they explore their workspace. Only then, as the last thing in the reply, you call complete_workspace_setup. That call closes the setup screen and lands them on their Companies view, so never make it before those lines are written, never as the only content of a reply, never while a question is unanswered, and never twice. The one exception: when they tell you they are done while something they accepted is still unbuilt, ask once whether to drop it and end as soon as they answer.++## In every turn++Twenty is new to this admin. Introduce a capability in one plain sentence before proposing anything that uses it: the data model is fully customizable, with objects and fields added, renamed, or removed any time in Settings > Data model; workflows automate repetitive work from a trigger, in the sidebar under Workflows; dashboards turn records into charts and counters, in the sidebar under Dashboards; roles control what each teammate can see and do, managed in Settings > Members > Roles.++Open each reply with a short plain title, and title each new step you move on to in the same reply. Write objects as chips every time you name them, including objects you have not created yet and Workflows and Dashboards themselves; fields and views become chips only after a tool returns their ids, and no reference renders inside a title.++Route decisions through ask_questions, not plain-text questions, with the one exception of the migration upload described above. Outside that exception, a question mark in your text means the call is missing, and never ask it for information you can look up with a tool. Each takes a short header, its question, and 2 to 4 short options, each a label with an optional description, at most one of them marked recommended, since a second one is rejected and the question is lost. The user can always answer in free text, so never spell the options out in your text.++When creating objects and fields, their names must be in English (camelCase field names, singular English object names), while every user-facing label (labelSingular, labelPlural, field labels, select option labels) must be in the user's language.++## How every reply ends++While the setup is running, each reply of yours ends in exactly one of two ways: the ask_questions call, or the complete_workspace_setup call. The only exception is the CSV upload request above, which ends with neither. Tool results do not end a reply, and neither does reporting what you just built: after either of those you are still mid-reply, and the way you finish it is one of those two calls. So never write the choices out as a list in your text and never ask in your own words which one they want, since the options reach them only through the call, and a question left in your text gives them nothing to pick and stalls the setup there. Which of the two it is follows from them: while anything is still worth building, it is the ask_questions call, and from the moment they are done, whether they picked the finishing option or told you so in their own words, it is complete_workspace_setup in that same reply.++Both of those calls come after the text of that reply, never instead of it: a reply whose only content is one of them arrives as an empty message, so the question card shows up under a blank turn and the setup closes without a word of goodbye.`;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.tsindex 751d031a3b1..7d949f56b3b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts@@ -59,7 +59,6 @@ import { AI_CHAT_STREAM_FUNCTION_ID } from 'src/engine/metadata-modules/ai/ai-chimport { AI_CHAT_TOOL_NAMES_TO_PRELOAD } from 'src/engine/metadata-modules/ai/ai-chat/constants/ai-chat-tool-names-to-preload.const';import { AI_CHAT_WORKSPACE_SETUP_STREAM_FUNCTION_ID } from 'src/engine/metadata-modules/ai/ai-chat/constants/ai-chat-workspace-setup-stream-function-id.constant';import { MessagePruningService } from 'src/engine/metadata-modules/ai/ai-chat/services/message-pruning.service';-import { SystemPromptBuilderService } from 'src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service';import {ASK_QUESTIONS_TOOL_NAME,createAskQuestionsTool,@@ -70,6 +69,8 @@ import {} from 'src/engine/metadata-modules/ai/ai-chat/tools/complete-workspace-setup.tool';import { type ExtractedFile } from 'src/engine/metadata-modules/ai/ai-chat/types/extracted-file.type';import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';+import { buildFullSystemPrompt } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util';+import { hasNoAssistantMessage } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util';import { hasSucceededWorkspaceSetupCompletion } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util';import { extractCodeInterpreterFiles } from 'src/engine/metadata-modules/ai/ai-chat/utils/extract-code-interpreter-files.util';import { injectMessageTimestamps } from 'src/engine/metadata-modules/ai/ai-chat/utils/inject-message-timestamps.util';@@ -124,7 +125,6 @@ export class ChatExecutionService {private readonly agentActorContextService: AgentActorContextService,private readonly workspaceDomainsService: WorkspaceDomainsService,private readonly codeInterpreterService: CodeInterpreterService,- private readonly systemPromptBuilder: SystemPromptBuilderService,private readonly exceptionHandlerService: ExceptionHandlerService,private readonly nativeToolBinder: NativeToolBinderService,private readonly messagePruningService: MessagePruningService,@@ -226,6 +226,9 @@ export class ChatExecutionService {}) &&!hasSucceededWorkspaceSetupCompletion(messages);+ const isWorkspaceSetupKickoffTurn =+ isWorkspaceSetupThread && hasNoAssistantMessage(messages);+tagAiChatKindScope({ isWorkspaceSetupThread });const preloadedToolNames = [@@ -239,7 +242,9 @@ export class ChatExecutionService {// learn_tools returns schemas as text; execute_tool dispatches via the registry.const activeTools: ToolSet = {...directTools,- [ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool(),+ [ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({+ isWorkspaceSetupThread,+ }),...(isWorkspaceSetupThread? {[COMPLETE_WORKSPACE_SETUP_TOOL_NAME]:@@ -312,14 +317,15 @@ export class ChatExecutionService {userContext.timezone,);- const systemPrompt = this.systemPromptBuilder.buildFullPrompt(+ const systemPrompt = buildFullSystemPrompt({toolCatalog,skillCatalog,- preloadedToolNames,+ preloadedTools: preloadedToolNames,storedFiles,- workspace.aiAdditionalInstructions ?? undefined,+ workspaceInstructions: workspace.aiAdditionalInstructions ?? undefined,userContext,- );+ isWorkspaceSetupThread,+ });this.logger.log(`Starting chat execution with model ${registeredModel.modelId}, ${Object.keys(activeTools).length} active tools`,@@ -469,6 +475,8 @@ export class ChatExecutionService {model: registeredModel.model,messages: [systemMessage, ...modelMessages],tools: activeTools,+ // Every step of the kickoff turn is forced so it cannot end in prose; stopWhen ends it at the first ask_questions.+ toolChoice: isWorkspaceSetupKickoffTurn ? 'required' : 'auto',abortSignal,stopWhen: (step) =>stepCountIs(AGENT_CONFIG.MAX_STEPS)(step) ||diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.tsindex a6fa33d2ca0..045e7eb4f0c 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service.ts@@ -1,22 +1,15 @@import { Injectable } from '@nestjs/common';import { isNonEmptyString } from '@sniptt/guards';-import {- getValidTimeZoneOrUndefined,- tipTapDocumentToMarkdown,-} from 'twenty-shared/utils';import { COMMON_PRELOAD_TOOLS } from 'src/engine/core-modules/tool-provider/constants/common-preload-tools.const';import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';-import { LOAD_SKILL_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools';-import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';import { buildToolCatalogSection } from 'src/engine/core-modules/tool-provider/utils/build-tool-catalog-section.util';-import {- AgentActorContextService,- type UserContext,-} from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';+import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';import { CHAT_SYSTEM_PROMPTS } from 'src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const';-import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';+import { buildSkillCatalogSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util';+import { buildUserContextSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util';+import { buildWorkspaceInstructionsSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-instructions-section.util';import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';export type SystemPromptSection = {@@ -78,7 +71,7 @@ export class SystemPromptBuilderService {estimatedTokenCount: estimateTokenCount(responseFormatContent),});- const workspaceSection = this.buildWorkspaceInstructionsSection(+ const workspaceSection = buildWorkspaceInstructionsSection(workspaceInstructions ?? '',);@@ -91,7 +84,7 @@ export class SystemPromptBuilderService {}if (userContext) {- const userSection = this.buildUserContextSection(userContext);+ const userSection = buildUserContextSection(userContext);sections.push({title: 'User Context',@@ -111,7 +104,7 @@ export class SystemPromptBuilderService {estimatedTokenCount: estimateTokenCount(toolSection),});- const skillSection = this.buildSkillCatalogSection(skillCatalog);+ const skillSection = buildSkillCatalogSection(skillCatalog);if (skillSection) {sections.push({@@ -131,142 +124,4 @@ export class SystemPromptBuilderService {estimatedTokenCount: totalTokens,};}-- buildFullPrompt(- toolCatalog: ToolIndexEntry[],- skillCatalog: FlatSkill[],- preloadedTools: string[],- storedFiles?: Array<{- filename: string;- fileId: string;- }>,- workspaceInstructions?: string,- userContext?: UserContext,- ): string {- const parts: string[] = [- CHAT_SYSTEM_PROMPTS.BASE,- CHAT_SYSTEM_PROMPTS.BROWSING_CONTEXT_INSTRUCTION,- CHAT_SYSTEM_PROMPTS.RESPONSE_FORMAT,- ];-- const workspaceInstructionsSection = this.buildWorkspaceInstructionsSection(- workspaceInstructions ?? '',- );-- if (isNonEmptyString(workspaceInstructionsSection)) {- parts.push(workspaceInstructionsSection);- }-- if (userContext) {- parts.push(this.buildUserContextSection(userContext));- }-- parts.push(buildToolCatalogSection(toolCatalog, preloadedTools));-- const skillSection = this.buildSkillCatalogSection(skillCatalog);-- if (skillSection) {- parts.push(skillSection);- }-- if (storedFiles && storedFiles.length > 0) {- parts.push(this.buildUploadedFilesSection(storedFiles));- }-- return parts.join('\n');- }-- buildWorkspaceInstructionsSection(instructions: string): string {- const projectedInstructions = tipTapDocumentToMarkdown(instructions).trim();-- if (!isNonEmptyString(projectedInstructions)) {- return '';- }-- return `-## Workspace Instructions--The following are custom instructions provided by the workspace administrator:--${projectedInstructions}`;- }-- buildUserContextSection(userContext: UserContext): string {- const parts = [- `User: ${userContext.firstName} ${userContext.lastName}`.trim(),- ];-- if (isNonEmptyString(userContext.jobTitle)) {- parts.push(`Job title: ${userContext.jobTitle}`);- }-- parts.push(`Locale: ${userContext.locale}`);-- const resolvedTimeZone = getValidTimeZoneOrUndefined(userContext.timezone);-- if (resolvedTimeZone) {- parts.push(`Timezone: ${resolvedTimeZone}`);- }-- parts.push(`Current date: ${this.formatCurrentDate(userContext.timezone)}`);-- return `-## User Context--${parts.join('\n')}`;- }-- private formatCurrentDate(timezone: string | null): string {- return new Intl.DateTimeFormat('en-US', {- timeZone: getValidTimeZoneOrUndefined(timezone),- weekday: 'long',- year: 'numeric',- month: 'long',- day: 'numeric',- }).format(new Date());- }-- buildUploadedFilesSection(- storedFiles: Array<{ filename: string; fileId: string }>,- ): string {- const fileList = storedFiles.map((f) => `- ${f.filename}`).join('\n');-- const filesJson = JSON.stringify(- storedFiles.map((f) => ({ filename: f.filename, fileId: f.fileId })),- );-- return `-## Uploaded Files--The user has uploaded the following files:-${fileList}--**IMPORTANT**: Use the \`code_interpreter\` tool to analyze these files.-When calling code_interpreter, include the files parameter with these values (use fileId to reference uploaded files):-\`\`\`json-${filesJson}-\`\`\`--In your Python code, access files at \`/home/user/{filename}\`.`;- }-- buildSkillCatalogSection(skillCatalog: FlatSkill[]): string {- if (skillCatalog.length === 0) {- return '';- }-- const skillsList = skillCatalog- .map(- (skill) => `- \`${skill.name}\`: ${skill.description ?? skill.label}`,- )- .join('\n');-- return `-## Available Skills--Skills provide detailed expertise for specialized tasks. Load a skill before attempting complex operations.-To load a skill, call \`${LOAD_SKILL_TOOL_NAME}\` with the skill name(s).--${skillsList}`;- }}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.tsindex 43e856efbd2..8ea3d2964ab 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts@@ -20,7 +20,7 @@ import { WorkspaceSetupChatOutcome } from 'src/engine/metadata-modules/ai/ai-chaimport { 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 { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';-import { buildWorkspaceSetupPromptText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util';+import { buildWorkspaceSetupKickoffMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util';import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';@@ -164,7 +164,7 @@ export class WorkspaceSetupChatService {thread,userWorkspaceId,workspace,- text: buildWorkspaceSetupPromptText({+ text: buildWorkspaceSetupKickoffMessageText({companyEnrichment: companyContext,personEnrichment: personContext,workspaceContext: {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.tsindex 3a5ac008bdb..9474b846f8c 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/__tests__/ask-questions.tool.spec.ts@@ -9,8 +9,23 @@ describe('ask_questions tool', () => {expect(ASK_QUESTIONS_TOOL_NAME).toBe('ask_questions');});+ it('drops the obvious-default guidance on workspace setup threads', () => {+ const standardTool = createAskQuestionsTool({+ isWorkspaceSetupThread: false,+ });+ const setupTool = createAskQuestionsTool({ isWorkspaceSetupThread: true });++ expect(standardTool.description).toContain(+ 'trivial choices with an obvious default',+ );+ expect(setupTool.description).not.toContain('obvious default');+ expect(setupTool.description).toContain(+ 'information you could look up with another tool',+ );+ });+it('execute echoes the questions with a pending status', async () => {- const tool = createAskQuestionsTool();+ const tool = createAskQuestionsTool({ isWorkspaceSetupThread: false });const questions = [{header: 'Email type',diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.tsindex a33534634d1..34d231f5e71 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts@@ -66,14 +66,28 @@ type AskQuestionsPendingOutput = {result: AskQuestionsToolResult;};-export const createAskQuestionsTool = () => ({- description:- 'Ask the user one or more multiple-choice questions when you need a decision you cannot ' +- 'infer from the request or context and that has no obvious default. The conversation ' +- 'pauses until the user answers, then continues with their choice in mind. Prefer this ' +- 'over guessing on consequential or ambiguous decisions. Do NOT use it for information you ' +- 'could look up with another tool, or for trivial choices with an obvious default. The ' +- 'user can always type a free-form answer instead of picking an option.',+const STANDARD_DESCRIPTION =+ 'Ask the user one or more multiple-choice questions when you need a decision you cannot ' ++ 'infer from the request or context and that has no obvious default. The conversation ' ++ 'pauses until the user answers, then continues with their choice in mind. Prefer this ' ++ 'over guessing on consequential or ambiguous decisions. Do NOT use it for information you ' ++ 'could look up with another tool, or for trivial choices with an obvious default. The ' ++ 'user can always type a free-form answer instead of picking an option.';++const WORKSPACE_SETUP_DESCRIPTION =+ 'Ask the user one or more multiple-choice questions when a decision is theirs to make. ' ++ 'The conversation pauses until the user answers, then continues with their choice in ' ++ 'mind. Do NOT use it for information you could look up with another tool. The user can ' ++ 'always type a free-form answer instead of picking an option.';++export const createAskQuestionsTool = ({+ isWorkspaceSetupThread,+}: {+ isWorkspaceSetupThread: boolean;+}) => ({+ description: isWorkspaceSetupThread+ ? WORKSPACE_SETUP_DESCRIPTION+ : STANDARD_DESCRIPTION,inputSchema: askQuestionsInputSchema,execute: async (input: AskQuestionsToolInput,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.tsnew file mode 100644index 00000000000..922f142eb5f--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts@@ -0,0 +1,70 @@+import { buildFullSystemPrompt } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util';++const WORKSPACE_INSTRUCTIONS_DOCUMENT = JSON.stringify({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: 'Always answer in bullet points.' }],+ },+ ],+});++const USER_CONTEXT = {+ firstName: 'Ada',+ lastName: 'Lovelace',+ jobTitle: 'COO',+ locale: 'fr-FR',+ timezone: 'Europe/Paris',+};++const buildPrompt = (isWorkspaceSetupThread?: boolean) =>+ buildFullSystemPrompt({+ toolCatalog: [],+ skillCatalog: [],+ preloadedTools: [],+ workspaceInstructions: WORKSPACE_INSTRUCTIONS_DOCUMENT,+ userContext: USER_CONTEXT,+ isWorkspaceSetupThread,+ });++describe('buildFullSystemPrompt', () => {+ it('should keep the standard composition for regular threads', () => {+ const prompt = buildPrompt(false);++ expect(prompt).toContain(+ 'You are a helpful AI assistant integrated into Twenty',+ );+ expect(prompt).toContain('A <browsing_context> tag may appear');+ expect(prompt).toContain('## Workspace Instructions');+ expect(prompt).toContain('Always answer in bullet points.');+ expect(prompt).toContain('Record References - IMPORTANT');+ expect(prompt).toContain('## User Context');+ expect(prompt).not.toContain(+ 'kicking off the setup of this brand-new workspace',+ );+ });++ it('should swap in the workspace setup prompt for setup threads', () => {+ const prompt = buildPrompt(true);++ expect(prompt).toContain(+ 'kicking off the setup of this brand-new workspace',+ );+ expect(prompt).toContain('## How every reply ends');+ expect(prompt).toContain('Record References - IMPORTANT');+ expect(prompt).toContain('## User Context');+ expect(prompt).toContain('Job title: COO');+ expect(prompt).not.toContain(+ 'You are a helpful AI assistant integrated into Twenty',+ );+ expect(prompt).not.toContain('A <browsing_context> tag may appear');+ });++ it('should ignore workspace instructions on setup threads', () => {+ const prompt = buildPrompt(true);++ expect(prompt).not.toContain('## Workspace Instructions');+ expect(prompt).not.toContain('Always answer in bullet points.');+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-kickoff-message-text.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-kickoff-message-text.util.spec.tsnew file mode 100644index 00000000000..72fec3fc4b1--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-kickoff-message-text.util.spec.ts@@ -0,0 +1,138 @@+import {+ type WorkspaceCompanyEnrichment,+ type WorkspacePersonEnrichment,+} from 'twenty-shared/workspace';++import { type WorkspaceSetupWorkspaceContext } from 'src/engine/metadata-modules/ai/ai-chat/types/workspace-setup-workspace-context.type';+import { buildCompanyContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-company-context-message-text.util';+import { buildPersonContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-person-context-message-text.util';+import { buildWorkspaceSetupKickoffMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util';++const companyEnrichment: WorkspaceCompanyEnrichment = {+ domain: 'acme.com',+ enrichedAt: '2026-07-21T10:00:00.000Z',+ name: 'Acme Inc',+ website: 'https://acme.com',+ industry: 'computer software',+ employeeCount: 250,+ size: '51-200',+ founded: 2015,+ headline: 'Anvils as a service',+ summary: 'Acme sells anvils to coyotes.',+ tags: ['saas', 'b2b'],+ locality: 'San Francisco',+ region: 'California',+ country: 'United States',+};++const personEnrichment: WorkspacePersonEnrichment = {+ email: '[email protected]',+ enrichedAt: '2026-07-21T10:00:00.000Z',+ fullName: 'Ada Lovelace',+ jobTitle: 'Head of Sales',+ jobTitleLevels: ['director'],+ jobCompanyName: 'Acme Inc',+ industry: 'computer software',+ headline: 'Selling anvils at scale',+ linkedinUrl: 'linkedin.com/in/ada',+ skills: ['sales', 'negotiation'],+ locality: 'Paris',+ region: 'Ile-de-France',+ country: 'France',+};++const workspaceContext: WorkspaceSetupWorkspaceContext = {+ workspaceDisplayName: 'Acme',+ workspaceSubdomain: 'acme',+ userEmail: '[email protected]',+};++const buildMessage = (+ overrides: Partial<+ Parameters<typeof buildWorkspaceSetupKickoffMessageText>[0]+ > = {},+) =>+ buildWorkspaceSetupKickoffMessageText({+ companyEnrichment,+ personEnrichment: null,+ workspaceContext,+ locale: 'en',+ ...overrides,+ });++describe('buildWorkspaceSetupKickoffMessageText', () => {+ it('should carry the company context when a full enrichment is provided', () => {+ const result = buildMessage();++ expect(result).toContain(buildCompanyContextMessageText(companyEnrichment));+ expect(result).toContain('Domain: acme.com');+ expect(result).not.toContain('No information about the company');+ });++ it('should state that no company information is available when the enrichment is null', () => {+ const result = buildMessage({ companyEnrichment: null });++ expect(result).toContain(+ 'No information about the company that owns this workspace is available.',+ );+ expect(result).not.toContain('Domain:');+ });++ it('should carry the person context when a person enrichment is provided', () => {+ const result = buildMessage({ personEnrichment });++ expect(result).toContain(buildPersonContextMessageText(personEnrichment));+ expect(result).toContain('Job title: Head of Sales');+ expect(result).not.toContain('No third-party information about the person');+ });++ it('should state that no person information is available when the person enrichment is null', () => {+ const result = buildMessage();++ expect(result).toContain(+ 'No third-party information about the person setting up this workspace is available.',+ );+ });++ it('should always carry the workspace context line', () => {+ const result = buildMessage();++ expect(result).toContain(+ 'This workspace is named "Acme" (subdomain: acme). The admin setting it up signed up with [email protected].',+ );+ });++ it('should carry no instructions besides the locale line', () => {+ const result = buildMessage({ personEnrichment });++ expect(result).not.toContain('ask_questions');+ expect(result).not.toContain('complete_workspace_setup');+ expect(result).not.toContain('##');+ });++ it.each([+ ['fr-FR', 'French'],+ ['de-DE', 'German'],+ ['pt-BR', 'Portuguese'],+ ['en', 'English'],+ ])(+ 'should end with the locale instruction when the locale is %s',+ (locale, languageName) => {+ const result = buildMessage({ locale });++ expect(+ result.endsWith(+ `The user locale is ${languageName}, please continue the discussion in that language.`,+ ),+ ).toBe(true);+ },+ );++ it('should fall back to the raw locale when it is not a structurally valid language tag', () => {+ const result = buildMessage({ locale: '!' });++ expect(result).toContain(+ 'The user locale is !, please continue the discussion in that language.',+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.tsdeleted file mode 100644index 1f7880b3dcb..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts+++ /dev/null@@ -1,418 +0,0 @@-import {- type WorkspaceCompanyEnrichment,- type WorkspacePersonEnrichment,-} from 'twenty-shared/workspace';--import { type WorkspaceSetupWorkspaceContext } from 'src/engine/metadata-modules/ai/ai-chat/types/workspace-setup-workspace-context.type';-import { buildCompanyContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-company-context-message-text.util';-import { buildPersonContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-person-context-message-text.util';-import { buildWorkspaceSetupPromptText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util';--const companyEnrichment: WorkspaceCompanyEnrichment = {- domain: 'acme.com',- enrichedAt: '2026-07-21T10:00:00.000Z',- name: 'Acme Inc',- website: 'https://acme.com',- industry: 'computer software',- employeeCount: 250,- size: '51-200',- founded: 2015,- headline: 'Anvils as a service',- summary: 'Acme sells anvils to coyotes.',- tags: ['saas', 'b2b'],- locality: 'San Francisco',- region: 'California',- country: 'United States',-};--const personEnrichment: WorkspacePersonEnrichment = {- email: '[email protected]',- enrichedAt: '2026-07-21T10:00:00.000Z',- fullName: 'Ada Lovelace',- jobTitle: 'Head of Sales',- jobTitleLevels: ['director'],- jobCompanyName: 'Acme Inc',- industry: 'computer software',- headline: 'Selling anvils at scale',- linkedinUrl: 'linkedin.com/in/ada',- skills: ['sales', 'negotiation'],- locality: 'Paris',- region: 'Ile-de-France',- country: 'France',-};--const workspaceContext: WorkspaceSetupWorkspaceContext = {- workspaceDisplayName: 'Acme',- workspaceSubdomain: 'acme',- userEmail: '[email protected]',-};--const buildPrompt = (- overrides: Partial<Parameters<typeof buildWorkspaceSetupPromptText>[0]> = {},-) =>- buildWorkspaceSetupPromptText({- companyEnrichment,- personEnrichment: null,- workspaceContext,- locale: 'en',- ...overrides,- });--describe('buildWorkspaceSetupPromptText', () => {- it('should embed the company context message text when a full enrichment is provided', () => {- const result = buildPrompt();-- expect(result).toContain(buildCompanyContextMessageText(companyEnrichment));- expect(result).toContain('Domain: acme.com');- expect(result).not.toContain('No information about the company');- });-- it('should instruct a tailored greeting without a discovery question when a full enrichment is provided', () => {- const result = buildPrompt();-- expect(result).toContain('tailored to their business');- expect(result).toContain('Do not greet them again');- expect(result).toContain('what you already know about their company');- expect(result).toContain('When their job title is in your user context');- expect(result).toContain('when it is missing, do not guess it');- expect(result).not.toContain('what they want to use Twenty for');- expect(result).not.toContain('You do not know what this company does yet');- });-- it('should forbid every first-reply tool except ask_questions when a full enrichment is provided', () => {- const result = buildPrompt();-- expect(result).toContain('required ask_questions call');- expect(result).toContain(- 'reply is unfinished until the ask_questions call is made',- );- expect(result).toContain('needs no skill and no learn_tools step');- expect(result).toContain(- 'do not call load_skills, learn_tools, execute_tool, or web search',- );- });-- it('should require explicit approval before building and name the metadata tools when a full enrichment is provided', () => {- const result = buildPrompt();-- expect(result).toContain('Only propose until the user explicitly approves');- expect(result).toContain(- 'never create, update, or delete anything before approval',- );- expect(result).toContain('metadata-building');- expect(result).toContain('create_many_object_metadata');- expect(result).toContain('create_many_field_metadata');- expect(result).toContain('create_many_relation_fields');- expect(result).toContain('never set isNullable false');- });-- it('should state that no company information is available when the enrichment is null', () => {- const result = buildPrompt({ companyEnrichment: null });-- expect(result).toContain('No information about the company');- expect(result).not.toContain('Domain:');- });-- it('should instruct an ask_questions discovery when the enrichment is null', () => {- const result = buildPrompt({ companyEnrichment: null });-- expect(result).toContain('You do not know what this company does yet');- expect(result).toContain('ask_questions to learn what the business does');- expect(result).toContain('when they start fresh');- expect(result).not.toContain('tailored to their business');- });-- it.each([- ['a full enrichment', companyEnrichment],- ['a null enrichment', null],- ])(- 'should open with the migration-or-scratch question when %s is provided',- (_label, enrichment) => {- const result = buildPrompt({ companyEnrichment: enrichment });-- expect(result).toContain(- 'moving over from another CRM or starting fresh',- );- expect(result).toContain('follow the migration path below');- },- );-- it.each([- ['a full enrichment', companyEnrichment],- ['a null enrichment', null],- ])(- 'should make the migration-or-scratch question a tool call rather than text when %s is provided',- (_label, enrichment) => {- const result = buildPrompt({ companyEnrichment: enrichment });-- expect(result).toContain(- 'Then stop writing and make the ask_questions call',- );- expect(result).toContain('its options');- expect(result).toContain('never give that question a title of its own');- expect(result).not.toContain('Close this reply with an ask_questions');- },- );-- it.each([- ['a full enrichment', companyEnrichment],- ['a null enrichment', null],- ])(- 'should leave an unlisted CRM to the free-text answer when %s is provided',- (_label, enrichment) => {- const result = buildPrompt({ companyEnrichment: enrichment });-- expect(result).toContain('leaving any other CRM to the free-text answer');- expect(result).not.toContain('another CRM, and starting fresh');- },- );-- it('should request the CRM export in plain text so the upload composer stays available', () => {- const result = buildPrompt();-- expect(result).toContain('end that reply without calling ask_questions');- expect(result).toContain('cannot take attachments');- expect(result).toContain('upload all their CSV exports at once');- });-- it('should tolerate spreadsheets, propose right away, and fall back to scratch without an export', () => {- const result = buildPrompt();-- expect(result).toContain('spreadsheet their CRM produces');- expect(result).toContain('as separate files');- expect(result).toContain('read them right away');- expect(result).toContain('continue as if they had chosen to start fresh');- });-- it('should inspect uploaded exports through code_interpreter before proposing the model', () => {- const result = buildPrompt();-- expect(result).toContain('code_interpreter');- expect(result).toContain('headers and a few sample rows');- expect(result).toContain('grounded in what they actually have');- });-- it('should import migrated rows with the Bulk Import recipe right after the model is built', () => {- const result = buildPrompt();-- expect(result).toContain('data-manipulation');- expect(result).toContain('Bulk Import recipe');- expect(result).toContain('as soon as the model is built');- expect(result).toContain('so one approval covers both');- });-- it.each([- ['a full enrichment', companyEnrichment],- ['a null enrichment', null],- ])(- 'should stay invisible and never claim tools are already loaded when %s is provided',- (_label, enrichment) => {- const result = buildPrompt({ companyEnrichment: enrichment });-- expect(result).toContain('invisible');- expect(result).toContain('follow these rules silently');- expect(result).not.toContain('already loaded');- },- );-- it('should ask about the data model with the ask_questions tool', () => {- const result = buildPrompt();-- expect(result).toContain('Never stop after presenting the proposal');- expect(result).toContain(- 'The turn is unfinished until you call ask_questions asking whether to go ahead and build it',- );- expect(result).toContain(- 'the general guidance about skipping questions with obvious defaults does not apply',- );- });-- it('should not instruct any view work since new fields are visible by default', () => {- const result = buildPrompt();-- expect(result).toContain('New fields land visible on their object');- expect(result).not.toContain('view-building');- expect(result).not.toContain('get_view_fields');- expect(result).not.toContain('create_many_view_fields');- expect(result).not.toContain('update_many_view_fields');- });-- it.each([- ['a full enrichment', companyEnrichment],- ['a null enrichment', null],- ])(- 'should introduce the agent and the walkthrough when %s is provided',- (_label, enrichment) => {- const result = buildPrompt({ companyEnrichment: enrichment });-- expect(result).toContain(- 'you are an AI agent who will walk them through Twenty',- );- },- );-- it('should teach each capability where it comes up', () => {- const result = buildPrompt();-- expect(result).toContain('one plain sentence');- expect(result).toContain('before proposing anything that uses it');- expect(result).toContain('fully customizable');- expect(result).toContain('Settings > Data model');- expect(result).toContain('sidebar under Workflows');- expect(result).toContain('sidebar under Dashboards');- });-- it('should require a title per reply and chips for objects', () => {- const result = buildPrompt();-- expect(result).toContain('Open each reply with a short plain title');- expect(result).toContain('title each new step');- expect(result).toContain('Write objects as chips');- });-- it('should never re-ask for something the user already approved', () => {- const result = buildPrompt();-- expect(result).toContain('ask_questions is for new decisions');- expect(result).toContain('Load a skill before proposing what it builds');- });-- it('should name the plain-text question as the failure mode to avoid', () => {- const result = buildPrompt();-- expect(result).toContain(- 'a question mark in your text means the call is missing',- );- });-- it('should keep ask_questions options within the single-recommended limit', () => {- const result = buildPrompt();-- expect(result).toContain('at most one of them marked recommended');- });-- it('should anchor the proposal on admission tests instead of numeric bands', () => {- const result = buildPrompt();-- expect(result).toContain('filter, sort, or report on it');- expect(result).toContain('own lifecycle');- expect(result).toContain('not a demo');- expect(result).not.toContain('2 to 4 custom objects');- expect(result).not.toContain('3 to 6 key fields');- expect(result).not.toContain('under 250 words');- });-- it('should propose tailored workflows built with the workflow tools', () => {- const result = buildPrompt();-- expect(result).toContain('workflow-building');- expect(result).toContain('create_complete_workflow');- expect(result).toContain('validate_workflow');- });-- it('should let the agent choose what to propose instead of following a script', () => {- const result = buildPrompt();-- expect(result).toContain('Nothing after that is a fixed sequence');- expect(result).toContain('which single capability to propose next');- expect(result).toContain('Name the thing in their business it improves');- });-- it('should never close without naming the capabilities it did not build', () => {- const result = buildPrompt();-- expect(result).toContain(- 'never close while they are still unaware of the rest',- );- expect(result).toContain('offer to set one up');- expect(result).toContain('Build only what they accept');- });-- it('should end the setup by calling the completion tool once nothing is left to build', () => {- const result = buildPrompt();-- expect(result).toContain('## Ending the setup');- expect(result).toContain(- 'end that same reply by calling complete_workspace_setup',- );- expect(result).toContain('moving to a side panel');- expect(result).toContain('never make it twice');- });-- it('should propose a dashboard built with the dashboard tools', () => {- const result = buildPrompt();-- expect(result).toContain('dashboard-building');- expect(result).toContain('create_complete_dashboard');- expect(result).toContain('widgetErrors');- });-- it('should propose roles and build them with the role tools', () => {- const result = buildPrompt();-- expect(result).toContain('roles skill');- expect(result).toContain('list_roles');- expect(result).toContain('Settings > Members > Roles');- expect(result).not.toContain('You cannot configure roles from this chat');- expect(result).not.toContain('navigate_app');- });-- it('should require English names with labels in the user language', () => {- const result = buildPrompt({ locale: 'fr-FR' });-- expect(result).toContain('names must be in English');- expect(result).toContain("must be in the user's language");- });-- it.each([- ['fr-FR', 'French'],- ['de-DE', 'German'],- ['pt-BR', 'Portuguese'],- ['en', 'English'],- ])(- 'should end with the locale instruction when the locale is %s',- (locale, languageName) => {- const result = buildPrompt({ locale });-- expect(- result.endsWith(- `The user locale is ${languageName}, please continue the discussion in that language.`,- ),- ).toBe(true);- },- );-- it('should fall back to the raw locale when it is not a structurally valid language tag', () => {- const result = buildPrompt({ locale: '!' });-- expect(result).toContain(- 'The user locale is !, please continue the discussion in that language.',- );- });-- it('should embed the person context and its first-reply addendum when a person enrichment is provided', () => {- const result = buildPrompt({ personEnrichment });-- expect(result).toContain(buildPersonContextMessageText(personEnrichment));- expect(result).toContain('Job title: Head of Sales');- expect(result).toContain('fold at most one specific detail');- expect(result).not.toContain('No third-party information about the person');- });-- it('should state that no person information is available when the person enrichment is null', () => {- const result = buildPrompt();-- expect(result).toContain(- 'No third-party information about the person setting up this workspace is available.',- );- expect(result).not.toContain('fold at most one specific detail');- });-- it('should always embed the workspace context line', () => {- const result = buildPrompt();-- expect(result).toContain(- 'This workspace is named "Acme" (subdomain: acme). The admin setting it up signed up with [email protected].',- );- });-});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-no-assistant-message.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-no-assistant-message.util.spec.tsnew file mode 100644index 00000000000..2dcf967bf59--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-no-assistant-message.util.spec.ts@@ -0,0 +1,23 @@+import { type ExtendedUIMessage } from 'twenty-shared/ai';++import { hasNoAssistantMessage } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util';++const message = (+ role: 'user' | 'assistant',+): Pick<ExtendedUIMessage, 'role'> => ({ role });++describe('hasNoAssistantMessage', () => {+ it('should return true when only user messages exist', () => {+ expect(hasNoAssistantMessage([message('user')])).toBe(true);+ });++ it('should return true for an empty conversation', () => {+ expect(hasNoAssistantMessage([])).toBe(true);+ });++ it('should return false once an assistant message exists', () => {+ expect(hasNoAssistantMessage([message('user'), message('assistant')])).toBe(+ false,+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.tsnew file mode 100644index 00000000000..eb9baab3f56--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts@@ -0,0 +1,70 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isNonEmptyArray } from 'twenty-shared/utils';++import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';+import { buildToolCatalogSection } from 'src/engine/core-modules/tool-provider/utils/build-tool-catalog-section.util';+import { type UserContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';+import { CHAT_SYSTEM_PROMPTS } from 'src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const';+import { WORKSPACE_SETUP_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant';+import { buildSkillCatalogSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util';+import { buildUploadedFilesSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-uploaded-files-section.util';+import { buildUserContextSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util';+import { buildWorkspaceInstructionsSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-instructions-section.util';+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';++export const buildFullSystemPrompt = ({+ toolCatalog,+ skillCatalog,+ preloadedTools,+ storedFiles,+ workspaceInstructions,+ userContext,+ isWorkspaceSetupThread,+}: {+ toolCatalog: ToolIndexEntry[];+ skillCatalog: FlatSkill[];+ preloadedTools: string[];+ storedFiles?: Array<{+ filename: string;+ fileId: string;+ }>;+ workspaceInstructions?: string;+ userContext?: UserContext;+ isWorkspaceSetupThread?: boolean;+}): string => {+ const parts: string[] = isWorkspaceSetupThread+ ? [WORKSPACE_SETUP_SYSTEM_PROMPT, CHAT_SYSTEM_PROMPTS.RESPONSE_FORMAT]+ : [+ CHAT_SYSTEM_PROMPTS.BASE,+ CHAT_SYSTEM_PROMPTS.BROWSING_CONTEXT_INSTRUCTION,+ CHAT_SYSTEM_PROMPTS.RESPONSE_FORMAT,+ ];++ if (!isWorkspaceSetupThread) {+ const workspaceInstructionsSection = buildWorkspaceInstructionsSection(+ workspaceInstructions ?? '',+ );++ if (isNonEmptyString(workspaceInstructionsSection)) {+ parts.push(workspaceInstructionsSection);+ }+ }++ if (userContext) {+ parts.push(buildUserContextSection(userContext));+ }++ parts.push(buildToolCatalogSection(toolCatalog, preloadedTools));++ const skillSection = buildSkillCatalogSection(skillCatalog);++ if (skillSection) {+ parts.push(skillSection);+ }++ if (isNonEmptyArray(storedFiles)) {+ parts.push(buildUploadedFilesSection(storedFiles));+ }++ return parts.join('\n');+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util.tsnew file mode 100644index 00000000000..9ee16c31e12--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util.ts@@ -0,0 +1,20 @@+import { LOAD_SKILL_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools';+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';++export const buildSkillCatalogSection = (skillCatalog: FlatSkill[]): string => {+ if (skillCatalog.length === 0) {+ return '';+ }++ const skillsList = skillCatalog+ .map((skill) => `- \`${skill.name}\`: ${skill.description ?? skill.label}`)+ .join('\n');++ return `+## Available Skills++Skills provide detailed expertise for specialized tasks. Load a skill before attempting complex operations.+To load a skill, call \`${LOAD_SKILL_TOOL_NAME}\` with the skill name(s).++${skillsList}`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-uploaded-files-section.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-uploaded-files-section.util.tsnew file mode 100644index 00000000000..34fd63a14ac--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-uploaded-files-section.util.ts@@ -0,0 +1,23 @@+export const buildUploadedFilesSection = (+ storedFiles: Array<{ filename: string; fileId: string }>,+): string => {+ const fileList = storedFiles.map((f) => `- ${f.filename}`).join('\n');++ const filesJson = JSON.stringify(+ storedFiles.map((f) => ({ filename: f.filename, fileId: f.fileId })),+ );++ return `+## Uploaded Files++The user has uploaded the following files:+${fileList}++**IMPORTANT**: Use the \`code_interpreter\` tool to analyze these files.+When calling code_interpreter, include the files parameter with these values (use fileId to reference uploaded files):+\`\`\`json+${filesJson}+\`\`\`++In your Python code, access files at \`/home/user/{filename}\`.`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util.tsnew file mode 100644index 00000000000..4a3d9fb4c6c--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util.ts@@ -0,0 +1,38 @@+import { isNonEmptyString } from '@sniptt/guards';+import { getValidTimeZoneOrUndefined } from 'twenty-shared/utils';++import { type UserContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';++const formatCurrentDate = (timezone: string | null): string =>+ new Intl.DateTimeFormat('en-US', {+ timeZone: getValidTimeZoneOrUndefined(timezone),+ weekday: 'long',+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ }).format(new Date());++export const buildUserContextSection = (userContext: UserContext): string => {+ const parts = [+ `User: ${userContext.firstName} ${userContext.lastName}`.trim(),+ ];++ if (isNonEmptyString(userContext.jobTitle)) {+ parts.push(`Job title: ${userContext.jobTitle}`);+ }++ parts.push(`Locale: ${userContext.locale}`);++ const resolvedTimeZone = getValidTimeZoneOrUndefined(userContext.timezone);++ if (resolvedTimeZone) {+ parts.push(`Timezone: ${resolvedTimeZone}`);+ }++ parts.push(`Current date: ${formatCurrentDate(userContext.timezone)}`);++ return `+## User Context++${parts.join('\n')}`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-instructions-section.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-instructions-section.util.tsnew file mode 100644index 00000000000..f70f13a522e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-instructions-section.util.ts@@ -0,0 +1,19 @@+import { isNonEmptyString } from '@sniptt/guards';+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';++export const buildWorkspaceInstructionsSection = (+ instructions: string,+): string => {+ const projectedInstructions = tipTapDocumentToMarkdown(instructions).trim();++ if (!isNonEmptyString(projectedInstructions)) {+ return '';+ }++ return `+## Workspace Instructions++The following are custom instructions provided by the workspace administrator:++${projectedInstructions}`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util.tsnew file mode 100644index 00000000000..8ad9ae42ff9--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util.ts@@ -0,0 +1,50 @@+import { isDefined } from 'twenty-shared/utils';+import {+ type WorkspaceCompanyEnrichment,+ type WorkspacePersonEnrichment,+} from 'twenty-shared/workspace';++import { type WorkspaceSetupWorkspaceContext } from 'src/engine/metadata-modules/ai/ai-chat/types/workspace-setup-workspace-context.type';+import { buildCompanyContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-company-context-message-text.util';+import { buildPersonContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-person-context-message-text.util';+import { buildWorkspaceContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-context-message-text.util';+import { getEnglishLanguageNameFromLocale } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-english-language-name-from-locale.util';++const NO_COMPANY_CONTEXT_LINE =+ 'No information about the company that owns this workspace is available.';++const NO_PERSON_CONTEXT_LINE =+ 'No third-party information about the person setting up this workspace is available.';++export const buildWorkspaceSetupKickoffMessageText = ({+ companyEnrichment,+ personEnrichment,+ workspaceContext,+ locale,+}: {+ companyEnrichment: WorkspaceCompanyEnrichment | null;+ personEnrichment: WorkspacePersonEnrichment | null;+ workspaceContext: WorkspaceSetupWorkspaceContext;+ locale: string;+}): string => {+ const companyContextSection = isDefined(companyEnrichment)+ ? buildCompanyContextMessageText(companyEnrichment)+ : NO_COMPANY_CONTEXT_LINE;++ const personContextSection = isDefined(personEnrichment)+ ? buildPersonContextMessageText(personEnrichment)+ : NO_PERSON_CONTEXT_LINE;++ const workspaceContextSection =+ buildWorkspaceContextMessageText(workspaceContext);++ const userLanguageName = getEnglishLanguageNameFromLocale(locale);++ return `${companyContextSection}++${personContextSection}++${workspaceContextSection}++The user locale is ${userLanguageName}, please continue the discussion in that language.`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.tsdeleted file mode 100644index 244228a7e6f..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts+++ /dev/null@@ -1,132 +0,0 @@-import { isDefined } from 'twenty-shared/utils';-import {- type WorkspaceCompanyEnrichment,- type WorkspacePersonEnrichment,-} from 'twenty-shared/workspace';--import { type WorkspaceSetupWorkspaceContext } from 'src/engine/metadata-modules/ai/ai-chat/types/workspace-setup-workspace-context.type';-import { buildCompanyContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-company-context-message-text.util';-import { buildPersonContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-person-context-message-text.util';-import { buildWorkspaceContextMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-context-message-text.util';-import { getEnglishLanguageNameFromLocale } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-english-language-name-from-locale.util';--const NO_COMPANY_CONTEXT_LINE =- 'No information about the company that owns this workspace is available.';--const NO_PERSON_CONTEXT_LINE =- 'No third-party information about the person setting up this workspace is available.';--const FIRST_REPLY_INSTRUCTION_WITH_COMPANY_CONTEXT =- 'Do not greet them again, the page above already welcomed them by name. Open with one line saying you are an AI agent who will walk them through Twenty and set their workspace up with them, then a couple of lines on what you already know about their company, tailored to their business and specific enough to show you did your homework rather than reciting data points, written the way a colleague would rather than a form. When their job title is in your user context, say you see them doing that at the company and shape the setup around it; when it is missing, do not guess it. Invite them to correct anything. Then stop writing and make the ask_questions call: its question is whether they are moving over from another CRM or starting fresh, its options the two CRMs a company like theirs most likely uses and starting fresh, leaving any other CRM to the free-text answer. When they start fresh, present the data model proposal described below; when they name a CRM, follow the migration path below.';--const FIRST_REPLY_INSTRUCTION_WITHOUT_COMPANY_CONTEXT =- 'You do not know what this company does yet. Do not greet them again, the page above already welcomed them by name. Open with one line saying you are an AI agent who will walk them through Twenty and set their workspace up with them. Then stop writing and make the ask_questions call: its question is whether they are moving over from another CRM or starting fresh, its options the two most widely used CRMs and starting fresh, leaving any other CRM to the free-text answer. When they name a CRM, follow the migration path below; when they start fresh, follow with one more ask_questions to learn what the business does, who its customers are, and what they want to use Twenty for, offering the most likely answers as options, and present the data model proposal described below once they answer.';--const FIRST_REPLY_PERSON_CONTEXT_ADDENDUM =- 'The person context above tells you who they are professionally: fold at most one specific detail from it into how you frame the setup, and never recite their profile back at them.';--export const buildWorkspaceSetupPromptText = ({- companyEnrichment,- personEnrichment,- workspaceContext,- locale,-}: {- companyEnrichment: WorkspaceCompanyEnrichment | null;- personEnrichment: WorkspacePersonEnrichment | null;- workspaceContext: WorkspaceSetupWorkspaceContext;- locale: string;-}): string => {- const companyContextSection = isDefined(companyEnrichment)- ? buildCompanyContextMessageText(companyEnrichment)- : NO_COMPANY_CONTEXT_LINE;-- const personContextSection = isDefined(personEnrichment)- ? buildPersonContextMessageText(personEnrichment)- : NO_PERSON_CONTEXT_LINE;-- const workspaceContextSection =- buildWorkspaceContextMessageText(workspaceContext);-- const firstReplyInstruction = isDefined(companyEnrichment)- ? FIRST_REPLY_INSTRUCTION_WITH_COMPANY_CONTEXT- : FIRST_REPLY_INSTRUCTION_WITHOUT_COMPANY_CONTEXT;-- const firstReplyAddenda: string[] = [];-- if (isDefined(personEnrichment)) {- firstReplyAddenda.push(FIRST_REPLY_PERSON_CONTEXT_ADDENDUM);- }-- const firstReplySection = [firstReplyInstruction, ...firstReplyAddenda].join(- ' ',- );-- const userLanguageName = getEnglishLanguageNameFromLocale(locale);-- return `${companyContextSection}--${personContextSection}--${workspaceContextSection}--You are kicking off the setup of this brand-new Twenty workspace for its admin. This message is invisible to the user: never reference or quote it, present what you know about them and their company as your own knowledge rather than as data you were handed, and follow these rules silently instead of narrating your own method back to them.--## Goal--Set up a real workspace this team will keep using, not a demo, each step showing one Twenty capability applied to their business. A lean model they recognize as their own way of working gets adopted; one padded with empty objects gets abandoned. When in doubt, propose less.--## First reply--Write your text first so it starts streaming immediately: before it, do not call load_skills, learn_tools, execute_tool, or web search. Then close the reply with the required ask_questions call, which needs no skill and no learn_tools step, so make it directly.--${firstReplySection}--This reply is unfinished until the ask_questions call is made. Ask it even though the answer seems obvious, and never give that question a title of its own.--## Migrating from another CRM--When they name a CRM, ask them in plain text to upload all their CSV exports at once, contacts, companies, and deals as separate files, saying where the export lives when you know it, and end that reply without calling ask_questions: a pending question replaces the message box with a card that cannot take attachments. Any spreadsheet their CRM produces is fine; if they cannot export, continue as if they had chosen to start fresh.--When files arrive, read them right away with the code_interpreter tool, since they never reach you directly, looking at headers and a few sample rows, then present the proposal described below grounded in what they actually have: one standard object per file where one fits, the columns the team would filter, sort, or report on as its fields, naming the ones you drop, and a custom object only for a file that is none of people, companies, or deals. Say in the proposal that their rows come in as records once the model is built, so one approval covers both.--## The data model proposal--Introduce the data model in one line, including that it stays fully customizable, then give a markdown proposal short enough to read in under a minute:-- One line per standard object (People, Companies, Opportunities) mapping it onto their domain, with the custom fields to add. A field earns its place only if the team would filter, sort, or report on it.-- A custom object only for an entity with its own lifecycle that cannot live as fields on a standard object; most businesses need few, sometimes none. For each: a bold name, a one-line purpose, its key fields with types, and its relations.--Never stop after presenting the proposal. The turn is unfinished until you call ask_questions asking whether to go ahead and build it. Ask it even though the answer seems obvious: the general guidance about skipping questions with obvious defaults does not apply here.--## After approval--Only propose until the user explicitly approves: never create, update, or delete anything before approval. Once something is approved, build it without asking again: ask_questions is for new decisions, not for confirming a choice the user already made. Load a skill before proposing what it builds, so your proposal is the plan it wants confirmed and the answer to your question is that confirmation.--Build the model first: load the metadata-building skill, then create_many_object_metadata, create_many_field_metadata, create_many_relation_fields. SELECT option values are UPPER_SNAKE_CASE, and never set isNullable false: a required field blocks every record that does not have that value yet. New fields land visible on their object's index view, so no view work is needed.--When they are migrating, one more step is fixed: as soon as the model is built, load the data-manipulation skill and follow its Bulk Import recipe to bring the uploaded rows in as records.--Nothing after that is a fixed sequence. Report what you built in a couple of lines, then judge from what they have actually told you which single capability to propose next: a workflow that removes a chore they described, a dashboard answering a number they said they watch, a role matching a split in their team. Name the thing in their business it improves, or propose a different one.--For whichever you propose:-- Workflows: load the workflow-building skill, then create_complete_workflow, which rejects code and AI-agent steps whatever the skill says; prefer automations needing no connected mailbox. Fix anything validate_workflow reports until it comes back clean, then activate with activate_workflow_version.-- Dashboards: load the dashboard-building skill and name the counters and charts it will hold and the fields behind them, noting it fills up as records arrive. Build it with create_complete_dashboard using graph widgets, repairing anything in widgetErrors.-- Roles: load the roles skill, call list_roles, and propose one that adds something to the Admin and Member roles already there, in one line: what it can reach and what it cannot.--Close with a short recap of what was built, and never close while they are still unaware of the rest: give whatever you did not build, workflows, dashboards or roles, one line each on what it would do for this team, and offer to set one up. Build only what they accept.--## Ending the setup--The setup ends only once there is nothing left they want built: everything they accepted is built and the rest is declined, or they tell you they are done. At that point write the closing recap described above, add one line saying this chat is moving to a side panel where the conversation continues while they explore their workspace, and end that same reply by calling complete_workspace_setup. That call closes the setup screen and lands them on their Companies view, so never make it while a question is unanswered, and when they tell you they are done while something they accepted is still unbuilt, ask once whether to drop it and end as soon as they answer. Never announce the move without making the call, and never make it twice.--## In every turn--Twenty is new to this admin. Introduce a capability in one plain sentence before proposing anything that uses it: the data model is fully customizable, with objects and fields added, renamed, or removed any time in Settings > Data model; workflows automate repetitive work from a trigger, in the sidebar under Workflows; dashboards turn records into charts and counters, in the sidebar under Dashboards; roles control what each teammate can see and do, managed in Settings > Members > Roles.--Open each reply with a short plain title, and title each new step you move on to in the same reply. Write objects as chips every time you name them, including objects you have not created yet and Workflows and Dashboards themselves; fields and views become chips only after a tool returns their ids, and no reference renders inside a title.--Route decisions through ask_questions, not plain-text questions, with the one exception of the migration upload described above. Outside that exception, a question mark in your text means the call is missing. Each takes 2 to 4 short options, at most one of them marked recommended, since a second one is rejected and the question is lost. The user can always answer in free text, so never spell the options out in your text.--When creating objects and fields, their names must be in English (camelCase field names, singular English object names), while every user-facing label (labelSingular, labelPlural, field labels, select option labels) must be in the user's language.--The user locale is ${userLanguageName}, please continue the discussion in that language.`;-};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util.tsnew file mode 100644index 00000000000..52de0dc200d--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util.ts@@ -0,0 +1,5 @@+import { type ExtendedUIMessage } from 'twenty-shared/ai';++export const hasNoAssistantMessage = (+ messages: Pick<ExtendedUIMessage, 'role'>[],+): boolean => messages.every((message) => message.role !== 'assistant');