Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): give agents pipeline tools in CRM terms (#7936)
teo58826c5def38
diff --git a/Cargo.lock b/Cargo.lockindex 107ac8f89f..008a18d5d9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4484,6 +4484,7 @@ dependencies = ["async-graphql","async-stream","axum",+ "bot_id","bots","calendar_events","chrono",@@ -5038,6 +5039,7 @@ dependencies = ["anyhow","async-trait","axum",+ "bot_id","call","chrono","databases",diff --git a/apps/docs/AI/mcp/tools/add-to-pipeline.mdx b/apps/docs/AI/mcp/tools/add-to-pipeline.mdxnew file mode 100644index 0000000000..9f34df12de--- /dev/null+++ b/apps/docs/AI/mcp/tools/add-to-pipeline.mdx@@ -0,0 +1,18 @@+---+title: AddToPipeline+description: >-+ Add companies or contacts to a CRM pipeline as new deals (entries), optionally+ setting their stage, owner, revenue or other fields.+---++# AddToPipeline++Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `pipelineId` | string | Yes | The pipeline's id from ListPipelines. |+| `entries` | ToolNewEntry[] | Yes | The companies or contacts to add, each with its starting fields. |+| `allowDuplicates` | boolean | No | Add a record again even if it already has an entry in this pipeline. Only for a genuinely separate second deal. Defaults to false. |diff --git a/apps/docs/AI/mcp/tools/create-pipeline.mdx b/apps/docs/AI/mcp/tools/create-pipeline.mdxnew file mode 100644index 0000000000..b7ef3fdef7--- /dev/null+++ b/apps/docs/AI/mcp/tools/create-pipeline.mdx@@ -0,0 +1,20 @@+---+title: CreatePipeline+description: >-+ Create a CRM pipeline: a board of deals that move through stages, such as a+ sales, renewals, fundraising, hiring or partnership pipeline.+---++# CreatePipeline++Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `name` | string | Yes | The pipeline's name, e.g. "Q4 Renewals". |+| `tracks` | `"company"` \| `"contact"` | Yes | What a pipeline's entries track. Documented on the fields that use it: a doc comment on a variant would turn the schema into `oneOf`. |+| `sharedWithTeam` | boolean | No | Let the user's team see and edit it. Defaults to false: only the user can see it. |+| `stages` | string[] | No | The stages, first to last, e.g. ["Sourced", "Screen", "Interview", "Offer", "Hired"]. Leave empty for the team's default stages. |+| `fields` | ToolNewField[] | No | Fields to add after Company/Contact, Stage, Owner and Revenue. |diff --git a/apps/docs/AI/mcp/tools/edit-pipeline.mdx b/apps/docs/AI/mcp/tools/edit-pipeline.mdxnew file mode 100644index 0000000000..7d2269217f--- /dev/null+++ b/apps/docs/AI/mcp/tools/edit-pipeline.mdx@@ -0,0 +1,25 @@+---+title: EditPipeline+description: >-+ Change a CRM pipeline itself: rename it, share it with the team or make it+ private (owner only), add, rename or remove fields, and add, rename or remove+ stages and other select options.+---++# EditPipeline++Change a CRM pipeline itself: rename it, share it with the team or make it private (owner only), add, rename or remove fields, and add, rename or remove stages and other select options. Stages are the options of the Stage field: to add a stage use addOptions on "Stage"; to rename one use renameOptions. Removing a field deletes its values from every entry, and removing a stage or option empties it on the entries holding it, so do that only when the user asked. New options go after the existing ones. Field changes apply together, all or nothing. Returns the pipeline with its fields as they are now.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `pipelineId` | string | Yes | The pipeline's id from ListPipelines. |+| `name` | string | No | A new name for the pipeline. |+| `sharedWithTeam` | boolean | No | true lets the user's team see and edit it; false makes it private to its owner. Only the owner can change this. |+| `addFields` | ToolNewField[] | No | Fields to add after the existing ones. |+| `renameFields` | ToolRename[] | No | Fields to rename. |+| `removeFields` | string[] | No | Names of fields to delete with their values. The Company or Contact field cannot be removed. |+| `addOptions` | ToolAddOptions[] | No | Stages or other select options to add. |+| `renameOptions` | ToolRenameOption[] | No | Stages or other select options to relabel. |+| `removeOptions` | ToolRemoveOption[] | No | Stages or other select options to delete. |diff --git a/apps/docs/AI/mcp/tools/find-pipeline-entries.mdx b/apps/docs/AI/mcp/tools/find-pipeline-entries.mdxnew file mode 100644index 0000000000..c88be5286a--- /dev/null+++ b/apps/docs/AI/mcp/tools/find-pipeline-entries.mdx@@ -0,0 +1,22 @@+---+title: FindPipelineEntries+description: >-+ Find deals (entries) in a CRM pipeline: which companies or contacts are in+ which stage, who owns them, their revenue and other fields.+---++# FindPipelineEntries++Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `pipelineId` | string | No | The pipeline's id from ListPipelines. Leave it out to look in every pipeline by `search` or `recordIds`; filters and sorting need a pipelineId. |+| `filters` | ToolFieldValue[] | No | Only entries whose fields hold these values; all filters must match. Options and people match exactly (labels ignore case), text matches a substring, dates match the day. Example: [\{"field": "Stage", "values": ["Demo", "Trial"]}, \{"field": "Owner", "value": "me"}]. |+| `recordIds` | string[] | No | Only entries tracking these CRM company or contact ids. |+| `search` | string | No | Text the tracked company's name or domain, or the contact's name or email, must contain, ignoring case (e.g. "acme"). |+| `sortBy` | string | No | A field name to order entries by, e.g. "Revenue" or "Stage". Empty fields come last. |+| `descending` | boolean | No | Sort largest, latest or furthest stage first. Defaults to false. |+| `limit` | integer | No | Most entries to return. Defaults to 50; max 200. |diff --git a/apps/docs/AI/mcp/tools/get-company.mdx b/apps/docs/AI/mcp/tools/get-company.mdxindex 11da949102..fbf7f50fb2 100644--- a/apps/docs/AI/mcp/tools/get-company.mdx+++ b/apps/docs/AI/mcp/tools/get-company.mdx@@ -1,14 +1,15 @@---title: GetCompanydescription: >-- Fetch one of the team's CRM companies by id, with its domains, contacts,- pipeline Stage / Owner / Revenue, and all attached property values (including- custom properties and the valid stage options).+ Fetch one of the team's CRM companies by id, with its domains, contacts, its+ own Stage / Owner / Revenue properties (not a pipeline deal's), and all+ attached property values (including custom properties and the valid stage+ options).---# GetCompany-Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response.+Fetch one of the team's CRM companies by id, with its domains, contacts, its own Stage / Owner / Revenue properties (not a pipeline deal's), and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change one of the company's own properties (its Stage, Owner, Revenue or a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response. Deals in a pipeline have their own stage and fields: find them with FindPipelineEntries (recordIds = this company's id) and change them with UpdatePipelineEntries.## Parametersdiff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex d4e60d9a4a..cbec923614 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -9,6 +9,7 @@ These pages are generated from Macro's Rust MCP tool registry.## Tools+- [AddToPipeline](/AI/mcp/tools/add-to-pipeline)- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)@@ -28,6 +29,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [CreateForm](/AI/mcp/tools/create-form)- [CreateImportEntity](/AI/mcp/tools/create-import-entity)- [CreateInitiative](/AI/mcp/tools/create-initiative)+- [CreatePipeline](/AI/mcp/tools/create-pipeline)- [CreateProject](/AI/mcp/tools/create-project)- [CreateRoutine](/AI/mcp/tools/create-routine)- [CreateSkill](/AI/mcp/tools/create-skill)@@ -52,10 +54,12 @@ These pages are generated from Macro's Rust MCP tool registry.- [EditDocument](/AI/mcp/tools/edit-document)- [EditDocumentComment](/AI/mcp/tools/edit-document-comment)- [EditForm](/AI/mcp/tools/edit-form)+- [EditPipeline](/AI/mcp/tools/edit-pipeline)- [EditPresentation](/AI/mcp/tools/edit-presentation)- [EditSpreadsheet](/AI/mcp/tools/edit-spreadsheet)- [EditTag](/AI/mcp/tools/edit-tag)- [EditWordDocument](/AI/mcp/tools/edit-word-document)+- [FindPipelineEntries](/AI/mcp/tools/find-pipeline-entries)- [GenerateImage](/AI/mcp/tools/generate-image)- [GetBookingInsights](/AI/mcp/tools/get-booking-insights)- [GetBookingRescheduleSlots](/AI/mcp/tools/get-booking-reschedule-slots)@@ -82,6 +86,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ListInitiatives](/AI/mcp/tools/list-initiatives)- [ListLabels](/AI/mcp/tools/list-labels)- [ListNotifications](/AI/mcp/tools/list-notifications)+- [ListPipelines](/AI/mcp/tools/list-pipelines)- [ListRoutines](/AI/mcp/tools/list-routines)- [ListSkills](/AI/mcp/tools/list-skills)- [ListTags](/AI/mcp/tools/list-tags)@@ -120,6 +125,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadSpreadsheet](/AI/mcp/tools/read-spreadsheet)- [ReadThread](/AI/mcp/tools/read-thread)- [ReadWordDocument](/AI/mcp/tools/read-word-document)+- [RemoveFromPipeline](/AI/mcp/tools/remove-from-pipeline)- [RenameChannel](/AI/mcp/tools/rename-channel)- [RenameDocument](/AI/mcp/tools/rename-document)- [RenameItem](/AI/mcp/tools/rename-item)@@ -145,6 +151,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [UpdateCallRecord](/AI/mcp/tools/update-call-record)- [UpdateInitiative](/AI/mcp/tools/update-initiative)- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)+- [UpdatePipelineEntries](/AI/mcp/tools/update-pipeline-entries)- [UpdateRoutine](/AI/mcp/tools/update-routine)- [UpdateSharing](/AI/mcp/tools/update-sharing)- [UpdateThreadLabels](/AI/mcp/tools/update-thread-labels)diff --git a/apps/docs/AI/mcp/tools/list-companies.mdx b/apps/docs/AI/mcp/tools/list-companies.mdxindex 0975694abb..eacf73850e 100644--- a/apps/docs/AI/mcp/tools/list-companies.mdx+++ b/apps/docs/AI/mcp/tools/list-companies.mdx@@ -7,14 +7,14 @@ description: >-# ListCompanies-List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties.+List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and the company's own Stage / Owner / Revenue properties when set (not a pipeline deal's). Use the filters to narrow results: `search` for name/domain text, `stage` for the company's own Stage property, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to change the company's own Stage / Owner / Revenue or custom properties. Deals in a pipeline have their own stage and fields, separate from these: use FindPipelineEntries and UpdatePipelineEntries for them.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- || `search` | string | No | Case-insensitive substring matched against company names and domains (e.g. "acme" matches "Acme Corp" and "acme.com"). |-| `stage` | string | No | Filter to companies in this pipeline stage. Accepts a stage label matched case-insensitively (e.g. "lead", "Customer" — teams may have custom stage names) or a stage option UUID. |+| `stage` | string | No | Filter to companies whose own Stage property (not a pipeline deal's stage) is this. Accepts a stage label matched case-insensitively (e.g. "lead", "Customer" — teams may have custom stage names) or a stage option UUID. || `owner_user_id` | string | No | Filter to companies whose Owner property is this Macro user id (e.g. "macro\|[email protected]"). Use ListTeamMembers to find user ids. || `include_hidden` | boolean | No | Also include companies hidden from the CRM. Defaults to false. Requires team admin or owner role. || `limit` | integer | No | Maximum number of companies to return. Defaults to 50; max 200. |diff --git a/apps/docs/AI/mcp/tools/list-pipelines.mdx b/apps/docs/AI/mcp/tools/list-pipelines.mdxnew file mode 100644index 0000000000..5dccda5a8f--- /dev/null+++ b/apps/docs/AI/mcp/tools/list-pipelines.mdx@@ -0,0 +1,10 @@+---+title: ListPipelines+description: >-+ List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or+ partner pipelines) with their stages and fields.+---++# ListPipelines++List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.diff --git a/apps/docs/AI/mcp/tools/remove-from-pipeline.mdx b/apps/docs/AI/mcp/tools/remove-from-pipeline.mdxnew file mode 100644index 0000000000..cdf9499f1d--- /dev/null+++ b/apps/docs/AI/mcp/tools/remove-from-pipeline.mdx@@ -0,0 +1,18 @@+---+title: RemoveFromPipeline+description: >-+ Remove deals (entries) from a CRM pipeline, deleting their stage and other+ pipeline fields.+---++# RemoveFromPipeline++Remove deals (entries) from a CRM pipeline, deleting their stage and other pipeline fields. The companies and contacts themselves stay in the CRM and in other pipelines. Address entries by entryId, or by the company or contact id they track (which removes every entry of that record in this pipeline). Only when the user asked to remove them.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `pipelineId` | string | Yes | The pipeline's id from ListPipelines. |+| `entryIds` | string[] | No | Entry ids from FindPipelineEntries. |+| `recordIds` | string[] | No | CRM company or contact ids whose entries to remove. |diff --git a/apps/docs/AI/mcp/tools/set-entity-property.mdx b/apps/docs/AI/mcp/tools/set-entity-property.mdxindex f0b44923aa..ea08274d13 100644--- a/apps/docs/AI/mcp/tools/set-entity-property.mdx+++ b/apps/docs/AI/mcp/tools/set-entity-property.mdx@@ -23,7 +23,7 @@ A task can belong to one project:- Project (00000001-0000-0000-0000-000000000014): entity, single. Use entity_ref with entity_type='initiative' and the project UUID; send no value field to remove the task from its project. Setting it requires edit access to the task and the project, and the project's agents are assigned to the task.CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties:-- Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids.+- Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. This is the company's own Stage, not a deal's stage in a CRM pipeline: move pipeline deals with UpdatePipelineEntries.- Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'.- Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars).Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only.diff --git a/apps/docs/AI/mcp/tools/update-pipeline-entries.mdx b/apps/docs/AI/mcp/tools/update-pipeline-entries.mdxnew file mode 100644index 0000000000..ba2c116fa7--- /dev/null+++ b/apps/docs/AI/mcp/tools/update-pipeline-entries.mdx@@ -0,0 +1,19 @@+---+title: UpdatePipelineEntries+description: >-+ Move deals to another stage or change their fields in a CRM pipeline: "move+ Acme to Negotiation", "set the revenue on the Globex deal", "assign these+ deals to Sam".+---++# UpdatePipelineEntries++Move deals to another stage or change their fields in a CRM pipeline: "move Acme to Negotiation", "set the revenue on the Globex deal", "assign these deals to Sam". Address each entry by entryId (from FindPipelineEntries) or by the company or contact id it tracks, and set fields by name with text values: stages and other options by label, people as "me", an email or a macro| user id, numbers, true/false, or dates. Several entries change in one call, all or nothing. Returns each field before and after. This changes the entry in the pipeline, not the company's own properties.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `pipelineId` | string | Yes | The pipeline's id from ListPipelines. |+| `updates` | ToolEntryUpdate[] | Yes | The entries to change, each with its fields to set. |+| `baseVersion` | integer | No | Optional: the pipeline version from the FindPipelineEntries read these changes are based on. The update is refused if the pipeline changed since; leave out for a direct change. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex b3c789e5c8..30c854c670 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -1,5 +1,6 @@["AI/mcp/tools/index",+ "AI/mcp/tools/add-to-pipeline","AI/mcp/tools/bash-code-execution","AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet",@@ -19,6 +20,7 @@"AI/mcp/tools/create-form","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-initiative",+ "AI/mcp/tools/create-pipeline","AI/mcp/tools/create-project","AI/mcp/tools/create-routine","AI/mcp/tools/create-skill",@@ -43,10 +45,12 @@"AI/mcp/tools/edit-document","AI/mcp/tools/edit-document-comment","AI/mcp/tools/edit-form",+ "AI/mcp/tools/edit-pipeline","AI/mcp/tools/edit-presentation","AI/mcp/tools/edit-spreadsheet","AI/mcp/tools/edit-tag","AI/mcp/tools/edit-word-document",+ "AI/mcp/tools/find-pipeline-entries","AI/mcp/tools/generate-image","AI/mcp/tools/get-booking-insights","AI/mcp/tools/get-booking-reschedule-slots",@@ -73,6 +77,7 @@"AI/mcp/tools/list-initiatives","AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications",+ "AI/mcp/tools/list-pipelines","AI/mcp/tools/list-routines","AI/mcp/tools/list-skills","AI/mcp/tools/list-tags",@@ -111,6 +116,7 @@"AI/mcp/tools/read-spreadsheet","AI/mcp/tools/read-thread","AI/mcp/tools/read-word-document",+ "AI/mcp/tools/remove-from-pipeline","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document","AI/mcp/tools/rename-item",@@ -136,6 +142,7 @@"AI/mcp/tools/update-call-record","AI/mcp/tools/update-initiative","AI/mcp/tools/update-initiative-sharing",+ "AI/mcp/tools/update-pipeline-entries","AI/mcp/tools/update-routine","AI/mcp/tools/update-sharing","AI/mcp/tools/update-thread-labels",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex d61dc19e0c..5095c656f9 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -71,6 +71,7 @@"icon": "wrench","pages": ["AI/mcp/tools/index",+ "AI/mcp/tools/add-to-pipeline","AI/mcp/tools/bash-code-execution","AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet",@@ -90,6 +91,7 @@"AI/mcp/tools/create-form","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-initiative",+ "AI/mcp/tools/create-pipeline","AI/mcp/tools/create-project","AI/mcp/tools/create-routine","AI/mcp/tools/create-skill",@@ -114,10 +116,12 @@"AI/mcp/tools/edit-document","AI/mcp/tools/edit-document-comment","AI/mcp/tools/edit-form",+ "AI/mcp/tools/edit-pipeline","AI/mcp/tools/edit-presentation","AI/mcp/tools/edit-spreadsheet","AI/mcp/tools/edit-tag","AI/mcp/tools/edit-word-document",+ "AI/mcp/tools/find-pipeline-entries","AI/mcp/tools/generate-image","AI/mcp/tools/get-booking-insights","AI/mcp/tools/get-booking-reschedule-slots",@@ -144,6 +148,7 @@"AI/mcp/tools/list-initiatives","AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications",+ "AI/mcp/tools/list-pipelines","AI/mcp/tools/list-routines","AI/mcp/tools/list-skills","AI/mcp/tools/list-tags",@@ -182,6 +187,7 @@"AI/mcp/tools/read-spreadsheet","AI/mcp/tools/read-thread","AI/mcp/tools/read-word-document",+ "AI/mcp/tools/remove-from-pipeline","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document","AI/mcp/tools/rename-item",@@ -207,6 +213,7 @@"AI/mcp/tools/update-call-record","AI/mcp/tools/update-initiative","AI/mcp/tools/update-initiative-sharing",+ "AI/mcp/tools/update-pipeline-entries","AI/mcp/tools/update-routine","AI/mcp/tools/update-sharing","AI/mcp/tools/update-thread-labels",diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.tsindex 14615d6989..97485115dd 100644--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts@@ -13,6 +13,7 @@ type Wording = (whose: string) => string;* `null` for the tools that use nobody's access and so are never held.*/const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {+ AddToPipeline: (whose) => `add deals to ${whose} pipelines`,BashCodeExecution: (whose) => `run code with ${whose} access`,BulkSetEntityPropertyOptions: (whose) =>`change property options in ${whose} workspace`,@@ -33,6 +34,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {CreateForm: (whose) => `create a form in ${whose} workspace`,CreateImportEntity: (whose) => `import into ${whose} workspace`,CreateInitiative: (whose) => `create an initiative in ${whose} workspace`,+ CreatePipeline: (whose) => `create a pipeline in ${whose} CRM`,CreateProject: (whose) => `create a project in ${whose} workspace`,CreateRoutine: (whose) => `create a routine for ${whose} account`,CreateSkill: (whose) => `create a skill in ${whose} workspace`,@@ -57,10 +59,12 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {EditDocument: (whose) => `edit ${whose} documents`,EditDocumentComment: (whose) => `edit comments on ${whose} documents`,EditForm: (whose) => `edit ${whose} forms`,+ EditPipeline: (whose) => `change ${whose} pipelines`,EditPresentation: (whose) => `edit ${whose} presentations`,EditSpreadsheet: (whose) => `edit ${whose} spreadsheets`,EditTag: (whose) => `edit tags in ${whose} workspace`,EditWordDocument: (whose) => `edit ${whose} documents`,+ FindPipelineEntries: (whose) => `read ${whose} pipelines`,GenerateImage: (whose) => `generate an image with ${whose} account`,GetBookingInsights: (whose) => `read ${whose} booking statistics`,GetBookingRescheduleSlots: (whose) =>@@ -88,6 +92,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {ListInitiatives: (whose) => `list ${whose} initiatives`,ListLabels: (whose) => `read ${whose} email labels`,ListNotifications: (whose) => `read ${whose} notifications`,+ ListPipelines: (whose) => `list ${whose} pipelines`,ListRoutines: (whose) => `list ${whose} routines`,ListSkills: (whose) => `list ${whose} skills`,ListTags: (whose) => `list tags in ${whose} workspace`,@@ -127,6 +132,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {ReadSpreadsheet: (whose) => `read ${whose} spreadsheets`,ReadThread: (whose) => `read ${whose} email`,ReadWordDocument: (whose) => `read ${whose} documents`,+ RemoveFromPipeline: (whose) => `remove deals from ${whose} pipelines`,RenameChannel: (whose) => `rename ${whose} channels`,RenameDocument: (whose) => `rename ${whose} documents`,RenameItem: (whose) => `rename items in ${whose} workspace`,@@ -153,6 +159,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {UpdateCallRecord: (whose) => `change ${whose} calls`,UpdateInitiative: (whose) => `change ${whose} initiatives`,UpdateInitiativeSharing: (whose) => `change who can see ${whose} initiatives`,+ UpdatePipelineEntries: (whose) => `update deals in ${whose} pipelines`,UpdateRoutine: (whose) => `change ${whose} routines`,UpdateSharing: (whose) => `change sharing in ${whose} workspace`,UpdateThreadLabels: (whose) => `relabel ${whose} email`,diff --git a/apps/web/src/features/crm/components/tool-pipelines.test.ts b/apps/web/src/features/crm/components/tool-pipelines.test.tsnew file mode 100644index 0000000000..424a6289a2--- /dev/null+++ b/apps/web/src/features/crm/components/tool-pipelines.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';+import { formatFieldValue, recordName } from './tool-pipelines';++describe('pipeline tool values', () => {+ it('shows people by email and lists joined', () => {+ expect(formatFieldValue('macro|[email protected]')).toBe('[email protected]');+ expect(formatFieldValue(['macro|[email protected]', 'macro|[email protected]'])).toBe(+ );+ expect(formatFieldValue(null)).toBe('empty');+ expect(formatFieldValue(true)).toBe('true');+ });++ it('names a record by name, then detail, then id', () => {+ expect(recordName({ id: '1', name: 'Acme', detail: 'acme.com' })).toBe(+ 'Acme'+ );+ expect(recordName({ id: '1', detail: 'acme.com' })).toBe('acme.com');+ expect(recordName({ id: '1' })).toBe('1');+ });+});diff --git a/apps/web/src/features/crm/components/tool-pipelines.tsx b/apps/web/src/features/crm/components/tool-pipelines.tsxnew file mode 100644index 0000000000..b62bfe8fac--- /dev/null+++ b/apps/web/src/features/crm/components/tool-pipelines.tsx@@ -0,0 +1,149 @@+import { Tool } from '@core/component/AI/component/tool/Tool';+import Buildings from '@phosphor-icons/core/regular/buildings.svg';+import Kanban from '@phosphor-icons/core/regular/kanban.svg';+import User from '@phosphor-icons/core/regular/user.svg';+import { For, Show } from 'solid-js';++type Pipeline = {+ name: string;+ tracks: string;+ fields: { name: string; options?: string[] | null }[];+};+type TrackedRecord = {+ id: string;+ name?: string | null;+ detail?: string | null;+};+type Entry = { record: TrackedRecord; fields: { [field: string]: unknown } };+type UpdatedEntry = {+ record: TrackedRecord;+ changes: { field: string; before: unknown; after: unknown }[];+};++/** A field value as one line: people by email, lists joined. */+export function formatFieldValue(value: unknown): string {+ if (value === null || value === undefined) return 'empty';+ if (Array.isArray(value)) return value.map(formatFieldValue).join(', ');+ if (typeof value === 'string') return value.replace(/^macro\|/, '');+ if (typeof value === 'number') return value.toLocaleString();+ return String(value);+}++export function recordName(record: TrackedRecord) {+ return record.name ?? record.detail ?? record.id;+}++function entrySummary(entry: Entry) {+ return Object.entries(entry.fields)+ .slice(0, 3)+ .map(([name, value]) => `${name}: ${formatFieldValue(value)}`)+ .join(' · ');+}++function RecordIcon(props: { record: TrackedRecord }) {+ const isContact = () => props.record.detail?.includes('@') === true;+ return (+ <Show when={isContact()} fallback={<Buildings class="size-4" />}>+ <User class="size-4" />+ </Show>+ );+}++function Line(props: { title: string; subtitle?: string }) {+ return (+ <div class="min-w-0 flex-1">+ <div class="truncate text-xs text-ink">{props.title}</div>+ <Show when={props.subtitle}>+ {(subtitle) => (+ <div class="truncate text-xs text-ink-placeholder">{subtitle()}</div>+ )}+ </Show>+ </div>+ );+}++export function PipelinesToolResponse(props: { pipelines: Pipeline[] }) {+ return (+ <Tool.List>+ <Show+ when={props.pipelines.length > 0}+ fallback={<Tool.ListItem>No pipelines.</Tool.ListItem>}+ >+ <For each={props.pipelines}>+ {(pipeline) => (+ <Tool.ListItem icon={<Kanban class="size-4" />}>+ <Line+ title={pipeline.name}+ subtitle={+ pipeline.fields+ .find((field) => field.name === 'Stage')+ ?.options?.join(' → ') ?? `Tracks ${pipeline.tracks}s`+ }+ />+ </Tool.ListItem>+ )}+ </For>+ </Show>+ </Tool.List>+ );+}++export function PipelineEntriesToolResponse(props: {+ entries: Entry[];+ empty: string;+ /** Entries listed after `entries`, each subtitled with this note. */+ noted?: { entries: Entry[]; note: string };+}) {+ const noted = () => props.noted?.entries ?? [];+ return (+ <Tool.List>+ <Show when={props.entries.length === 0 && noted().length === 0}>+ <Tool.ListItem>{props.empty}</Tool.ListItem>+ </Show>+ <For each={props.entries}>+ {(entry) => (+ <Tool.ListItem icon={<RecordIcon record={entry.record} />}>+ <Line+ title={recordName(entry.record)}+ subtitle={entrySummary(entry)}+ />+ </Tool.ListItem>+ )}+ </For>+ <For each={noted()}>+ {(entry) => (+ <Tool.ListItem icon={<RecordIcon record={entry.record} />}>+ <Line+ title={recordName(entry.record)}+ subtitle={[props.noted?.note, entrySummary(entry)]+ .filter(Boolean)+ .join(' · ')}+ />+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+ );+}++export function UpdatedEntriesToolResponse(props: { updated: UpdatedEntry[] }) {+ return (+ <Tool.List>+ <For each={props.updated}>+ {(entry) => (+ <Tool.ListItem icon={<RecordIcon record={entry.record} />}>+ <Line+ title={recordName(entry.record)}+ subtitle={entry.changes+ .map(+ (change) =>+ `${change.field}: ${formatFieldValue(change.before)} → ${formatFieldValue(change.after)}`+ )+ .join(' · ')}+ />+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+ );+}diff --git a/apps/web/src/features/crm/pipeline-tool-renderers.tsx b/apps/web/src/features/crm/pipeline-tool-renderers.tsxnew file mode 100644index 0000000000..51e608ac3f--- /dev/null+++ b/apps/web/src/features/crm/pipeline-tool-renderers.tsx@@ -0,0 +1,252 @@+import { BaseTool } from '@core/component/AI/component/tool/BaseTool';+import { createToolRenderer } from '@core/component/AI/component/tool/ToolRenderer';+import Kanban from '@phosphor-icons/core/regular/kanban.svg';+import { queryClient } from '@queries/client';+import { Show } from 'solid-js';+import { pluralize } from './components/tool-companies';+import {+ PipelineEntriesToolResponse,+ PipelinesToolResponse,+ recordName,+ UpdatedEntriesToolResponse,+} from './components/tool-pipelines';+import { crmKeys } from './queries/keys';++/** New, renamed, re-shared or reshaped pipelines show in the sidebar now. */+async function refreshPipelines() {+ await queryClient.invalidateQueries({ queryKey: crmKeys.pipelines._def });+}++function Status(props: { text?: string }) {+ return (+ <Show when={props.text}>+ {(text) => (+ <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ );+}++function Label(props: { children: string; status?: string }) {+ return (+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">{props.children}</span>+ <Status text={props.status} />+ </div>+ );+}++const listPipelinesHandler = createToolRenderer({+ name: 'ListPipelines',+ render: (ctx) => (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelinesToolResponse pipelines={ctx.response.data.pipelines} />+ ) : undefined+ }+ >+ <Label+ status={+ ctx.response+ ? pluralize(ctx.response.data.pipelines.length, 'pipeline')+ : undefined+ }+ >+ List CRM pipelines+ </Label>+ </BaseTool>+ ),+});++const findPipelineEntriesHandler = createToolRenderer({+ name: 'FindPipelineEntries',+ render: (ctx) => {+ const groups = () => ctx.response?.data.pipelines ?? [];+ const target = () =>+ groups().length === 1 ? ` in ${groups()[0]?.pipelineName}` : '';+ return (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelineEntriesToolResponse+ entries={groups().flatMap((group) => group.entries)}+ empty="No matching entries."+ />+ ) : undefined+ }+ >+ <Label+ status={+ ctx.response+ ? pluralize(ctx.response.data.matched, 'entry', 'entries')+ : undefined+ }+ >+ {`Find pipeline entries${target()}${+ ctx.tool.data.search ? ` matching "${ctx.tool.data.search}"` : ''+ }`}+ </Label>+ </BaseTool>+ );+ },+});++const addToPipelineHandler = createToolRenderer({+ name: 'AddToPipeline',+ render: (ctx) => {+ const added = () => ctx.response?.data.added ?? [];+ return (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelineEntriesToolResponse+ entries={added()}+ empty="Nothing added."+ noted={{+ entries: ctx.response.data.alreadyPresent ?? [],+ note: 'Already in pipeline',+ }}+ />+ ) : undefined+ }+ >+ <Label+ status={+ ctx.response+ ? `${pluralize(added().length, 'entry', 'entries')} added`+ : undefined+ }+ >+ {ctx.response+ ? `Added ${+ added()+ .map((entry) => recordName(entry.record))+ .join(', ') || 'nothing'+ } to pipeline`+ : `Add ${pluralize(ctx.tool.data.entries.length, 'record')} to pipeline`}+ </Label>+ </BaseTool>+ );+ },+});++const updatePipelineEntriesHandler = createToolRenderer({+ name: 'UpdatePipelineEntries',+ render: (ctx) => (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <UpdatedEntriesToolResponse updated={ctx.response.data.updated} />+ ) : undefined+ }+ >+ <Label+ status={+ ctx.response+ ? pluralize(ctx.response.data.updated.length, 'entry', 'entries')+ : undefined+ }+ >+ {ctx.response ? 'Updated pipeline entries' : 'Update pipeline entries'}+ </Label>+ </BaseTool>+ ),+});++const removeFromPipelineHandler = createToolRenderer({+ name: 'RemoveFromPipeline',+ render: (ctx) => (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelineEntriesToolResponse+ entries={ctx.response.data.removed}+ empty="Nothing removed."+ />+ ) : undefined+ }+ >+ <Label+ status={+ ctx.response+ ? `${pluralize(ctx.response.data.removed.length, 'entry', 'entries')} removed`+ : undefined+ }+ >+ {ctx.response ? 'Removed from pipeline' : 'Remove from pipeline'}+ </Label>+ </BaseTool>+ ),+});++const createPipelineHandler = createToolRenderer({+ name: 'CreatePipeline',+ handleResponse: refreshPipelines,+ render: (ctx) => (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelinesToolResponse pipelines={[ctx.response.data.pipeline]} />+ ) : undefined+ }+ >+ <Label>+ {`${ctx.response ? 'Created' : 'Create'} pipeline ${ctx.tool.data.name}`}+ </Label>+ </BaseTool>+ ),+});++const editPipelineHandler = createToolRenderer({+ name: 'EditPipeline',+ handleResponse: refreshPipelines,+ render: (ctx) => (+ <BaseTool+ icon={Kanban}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <PipelinesToolResponse pipelines={[ctx.response.data.pipeline]} />+ ) : undefined+ }+ >+ <Label>+ {ctx.response+ ? `Updated pipeline ${ctx.response.data.pipeline.name}`+ : 'Edit pipeline'}+ </Label>+ </BaseTool>+ ),+});++export const pipelineToolHandlers = {+ ListPipelines: listPipelinesHandler,+ FindPipelineEntries: findPipelineEntriesHandler,+ AddToPipeline: addToPipelineHandler,+ UpdatePipelineEntries: updatePipelineEntriesHandler,+ RemoveFromPipeline: removeFromPipelineHandler,+ CreatePipeline: createPipelineHandler,+ EditPipeline: editPipelineHandler,+};diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex eba9a4fc53..d7d487208b 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -4,6 +4,7 @@ import {getCompanyHandler,listCompaniesHandler,} from '@app/features/crm/crm-tool-renderers';+import { pipelineToolHandlers } from '@app/features/crm/pipeline-tool-renderers';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableDatabases } from '@core/constant/featureFlags';import {@@ -237,6 +238,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {CreateContact: createContactHandler,GetEntityProperties: getEntityPropertiesHandler,ListCompanies: listCompaniesHandler,+ ...pipelineToolHandlers,ListImportEntities: listImportEntitiesHandler,...lazyDatabaseToolHandlers,ListEntities: listEntitiesHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex ab192f4b25..afe2dd9e54 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -3,6 +3,53 @@*/import { z } from 'zod/v3';+export const AddToPipeline = z.object({+ pipelineId: z.string().uuid(),+ entries: z.array(+ z.object({+ recordId: z.union([z.string().uuid(), z.null()]).optional(),+ email: z.union([z.string(), z.null()]).optional(),+ set: z+ .array(+ z.object({+ field: z.string(),+ value: z.union([z.string(), z.null()]).optional(),+ values: z.union([z.array(z.string()), z.null()]).optional(),+ })+ )+ .optional(),+ })+ ),+ allowDuplicates: z.union([z.boolean(), z.null()]).optional(),+});++export const AddToPipelineResponse = z.object({+ added: z.array(+ z.object({+ entryId: z.string().uuid(),+ record: z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ fields: z.record(z.any()),+ })+ ),+ alreadyPresent: z.array(+ z.object({+ entryId: z.string().uuid(),+ record: z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ fields: z.record(z.any()),+ })+ ),+ version: z.union([z.number().int(), z.null()]).optional(),+ summary: z.string(),+});+export const BashCodeExecution = z.object({ input: z.string() });export const BashCodeExecutionResponse = z.object({@@ -3828,6 +3875,106 @@ export const ProjectDetails = z.object({),});+export const CreatePipeline = z.object({+ name: z.string(),+ tracks: z.enum(['company', 'contact']),+ sharedWithTeam: z.union([z.boolean(), z.null()]).optional(),+ stages: z.array(z.string()).optional(),+ fields: z+ .array(+ z.object({+ name: z.string(),+ type: z.enum([+ 'text',+ 'number',+ 'checkbox',+ 'date',+ 'link',+ 'select',+ 'multi_select',+ 'person',+ 'people',+ ]),+ options: z.array(z.string()).optional(),+ })+ )+ .optional(),+});++export const CreatePipelineResponse = z.object({+ pipeline: z.object({+ id: z.string().uuid(),+ name: z.string(),+ tracks: z.enum(['company', 'contact']),+ access: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('view'),+ z.literal('edit'),+ z.literal('owner'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ sharedWithTeam: z.boolean(),+ fields: z.array(+ z.object({+ name: z.string(),+ type: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('company'),+ z.literal('contact'),+ z.literal('text'),+ z.literal('number'),+ z.literal('checkbox'),+ z.literal('date'),+ z.literal('link'),+ z.literal('select'),+ z.literal('tags'),+ z.literal('person'),+ z.literal('item'),+ z.literal('relation'),+ z.literal('formula'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ multiple: z.boolean(),+ options: z.array(z.string()),+ required: z.boolean(),+ readOnly: z.boolean(),+ })+ ),+ version: z.number().int(),+ }),+ summary: z.string(),+});+export const CreateProject = z.object({projectName: z.string(),parentProjectId: z.union([z.string().uuid(), z.null()]).optional(),@@ -5437,6 +5584,118 @@ export const EditForm = z.object({confirmationMessage: z.union([z.string(), z.null()]).optional(),});+export const EditPipeline = z.object({+ pipelineId: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ sharedWithTeam: z.union([z.boolean(), z.null()]).optional(),+ addFields: z+ .array(+ z.object({+ name: z.string(),+ type: z.enum([+ 'text',+ 'number',+ 'checkbox',+ 'date',+ 'link',+ 'select',+ 'multi_select',+ 'person',+ 'people',+ ]),+ options: z.array(z.string()).optional(),+ })+ )+ .optional(),+ renameFields: z+ .array(z.object({ from: z.string(), to: z.string() }))+ .optional(),+ removeFields: z.array(z.string()).optional(),+ addOptions: z+ .array(z.object({ field: z.string(), labels: z.array(z.string()) }))+ .optional(),+ renameOptions: z+ .array(z.object({ field: z.string(), from: z.string(), to: z.string() }))+ .optional(),+ removeOptions: z+ .array(z.object({ field: z.string(), label: z.string() }))+ .optional(),+});++export const EditPipelineResponse = z.object({+ pipeline: z.object({+ id: z.string().uuid(),+ name: z.string(),+ tracks: z.enum(['company', 'contact']),+ access: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('view'),+ z.literal('edit'),+ z.literal('owner'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ sharedWithTeam: z.boolean(),+ fields: z.array(+ z.object({+ name: z.string(),+ type: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('company'),+ z.literal('contact'),+ z.literal('text'),+ z.literal('number'),+ z.literal('checkbox'),+ z.literal('date'),+ z.literal('link'),+ z.literal('select'),+ z.literal('tags'),+ z.literal('person'),+ z.literal('item'),+ z.literal('relation'),+ z.literal('formula'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ multiple: z.boolean(),+ options: z.array(z.string()),+ required: z.boolean(),+ readOnly: z.boolean(),+ })+ ),+ version: z.number().int(),+ }),+ summary: z.string(),+});+export const EditPresentation = z.object({documentId: z.string(),operations: z@@ -8012,6 +8271,58 @@ export const EditWordDocument = z.object({export const WordDocumentResponse = z.object({ content: z.string() });+export const FindPipelineEntries = z.object({+ pipelineId: z.union([z.string().uuid(), z.null()]).optional(),+ filters: z+ .array(+ z.object({+ field: z.string(),+ value: z.union([z.string(), z.null()]).optional(),+ values: z.union([z.array(z.string()), z.null()]).optional(),+ })+ )+ .optional(),+ recordIds: z.array(z.string().uuid()).optional(),+ search: z.union([z.string(), z.null()]).optional(),+ sortBy: z.union([z.string(), z.null()]).optional(),+ descending: z.union([z.boolean(), z.null()]).optional(),+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),+});++export const FindPipelineEntriesResponse = z.object({+ pipelines: z.array(+ z.object({+ pipelineId: z.string().uuid(),+ pipelineName: z.string(),+ version: z.union([z.number().int(), z.null()]).optional(),+ entries: z.array(+ z.object({+ entryId: z.string().uuid(),+ record: z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ fields: z.record(z.any()),+ })+ ),+ })+ ),+ matched: z.number().int().gte(0),+ complete: z.boolean(),+ counts: z.array(+ z.object({+ field: z.string(),+ counts: z.array(+ z.object({ label: z.string(), count: z.number().int().gte(0) })+ ),+ empty: z.number().int().gte(0),+ })+ ),+ totals: z.array(z.object({ field: z.string(), sum: z.number() })),+ summary: z.string(),+});+export const GenerateImage = z.object({prompt: z.string(),aspectRatio: z@@ -9763,6 +10074,85 @@ export const ListNotificationsResponse = z.object({hasMore: z.boolean(),});+export const ListPipelines = z.record(z.any());++export const ListPipelinesResponse = z.object({+ pipelines: z.array(+ z.object({+ id: z.string().uuid(),+ name: z.string(),+ tracks: z.enum(['company', 'contact']),+ access: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('view'),+ z.literal('edit'),+ z.literal('owner'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ sharedWithTeam: z.boolean(),+ fields: z.array(+ z.object({+ name: z.string(),+ type: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('company'),+ z.literal('contact'),+ z.literal('text'),+ z.literal('number'),+ z.literal('checkbox'),+ z.literal('date'),+ z.literal('link'),+ z.literal('select'),+ z.literal('tags'),+ z.literal('person'),+ z.literal('item'),+ z.literal('relation'),+ z.literal('formula'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ multiple: z.boolean(),+ options: z.array(z.string()),+ required: z.boolean(),+ readOnly: z.boolean(),+ })+ ),+ version: z.number().int(),+ })+ ),+ summary: z.string(),+});+export const ListRoutines = z.object({query: z.union([z.string(), z.null()]).optional(),enabled: z.union([z.boolean(), z.null()]).optional(),@@ -13102,6 +13492,28 @@ export const ReadWordDocument = z.object({count: z.union([z.number().int().gte(0), z.null()]).optional(),});+export const RemoveFromPipeline = z.object({+ pipelineId: z.string().uuid(),+ entryIds: z.array(z.string().uuid()).optional(),+ recordIds: z.array(z.string().uuid()).optional(),+});++export const RemoveFromPipelineResponse = z.object({+ removed: z.array(+ z.object({+ entryId: z.string().uuid(),+ record: z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ fields: z.record(z.any()),+ })+ ),+ version: z.union([z.number().int(), z.null()]).optional(),+ summary: z.string(),+});+export const RenameChannel = z.object({channelId: z.string().uuid(),name: z.string(),@@ -14657,6 +15069,42 @@ export const UpdateInitiativeSharing = z.object({.optional(),});+export const UpdatePipelineEntries = z.object({+ pipelineId: z.string().uuid(),+ updates: z.array(+ z.object({+ entryId: z.union([z.string().uuid(), z.null()]).optional(),+ recordId: z.union([z.string().uuid(), z.null()]).optional(),+ set: z.array(+ z.object({+ field: z.string(),+ value: z.union([z.string(), z.null()]).optional(),+ values: z.union([z.array(z.string()), z.null()]).optional(),+ })+ ),+ })+ ),+ baseVersion: z.union([z.number().int(), z.null()]).optional(),+});++export const UpdatePipelineEntriesResponse = z.object({+ updated: z.array(+ z.object({+ entryId: z.string().uuid(),+ record: z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ changes: z.array(+ z.object({ field: z.string(), before: z.any(), after: z.any() })+ ),+ })+ ),+ version: z.union([z.number().int(), z.null()]).optional(),+ summary: z.string(),+});+export const UpdateRoutine = z.object({routineId: z.string().uuid(),change: z.any().superRefine((x, ctx) => {diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex 6fc80dda96..2aaf790785 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -9,6 +9,10 @@ import * as schemas from './schemas';import type * as types from './types';type ToolParserMap = {+ AddToPipeline: {+ call: types.AddToPipeline;+ response: types.AddToPipelineResponse;+ };BashCodeExecution: {call: types.BashCodeExecution;response: types.BashCodeExecutionResponse;@@ -76,6 +80,10 @@ type ToolParserMap = {call: types.CreateInitiative;response: types.ProjectDetails;};+ CreatePipeline: {+ call: types.CreatePipeline;+ response: types.CreatePipelineResponse;+ };CreateProject: {call: types.CreateProject;response: types.CreateProjectResponse;@@ -151,6 +159,10 @@ type ToolParserMap = {response: types.EditDocumentCommentResponse;};EditForm: { call: types.EditForm; response: types.MutationResult };+ EditPipeline: {+ call: types.EditPipeline;+ response: types.EditPipelineResponse;+ };EditPresentation: {call: types.EditPresentation;response: types.PresentationEditOutcome;@@ -164,6 +176,10 @@ type ToolParserMap = {call: types.EditWordDocument;response: types.WordDocumentResponse;};+ FindPipelineEntries: {+ call: types.FindPipelineEntries;+ response: types.FindPipelineEntriesResponse;+ };GenerateImage: {call: types.GenerateImage;response: types.GenerateImageResponse;@@ -244,6 +260,10 @@ type ToolParserMap = {call: types.ListNotifications;response: types.ListNotificationsResponse;};+ ListPipelines: {+ call: types.ListPipelines;+ response: types.ListPipelinesResponse;+ };ListRoutines: { call: types.ListRoutines; response: types.RoutineList };ListSkills: { call: types.ListSkills; response: types.ListSkillsResponse };ListTags: { call: types.ListTags; response: types.ListTagsResponse };@@ -354,6 +374,10 @@ type ToolParserMap = {call: types.ReadWordDocument;response: types.WordDocumentResponse;};+ RemoveFromPipeline: {+ call: types.RemoveFromPipeline;+ response: types.RemoveFromPipelineResponse;+ };RenameChannel: {call: types.RenameChannel;response: types.RenameChannelResponse;@@ -436,6 +460,10 @@ type ToolParserMap = {call: types.UpdateInitiativeSharing;response: types.ProjectDetails;};+ UpdatePipelineEntries: {+ call: types.UpdatePipelineEntries;+ response: types.UpdatePipelineEntriesResponse;+ };UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };UpdateSharing: {call: types.UpdateSharing;@@ -451,6 +479,10 @@ type ToolParserMap = {};const toolParserMap = {+ AddToPipeline: {+ call: schemas.AddToPipeline,+ response: schemas.AddToPipelineResponse,+ },BashCodeExecution: {call: schemas.BashCodeExecution,response: schemas.BashCodeExecutionResponse,@@ -518,6 +550,10 @@ const toolParserMap = {call: schemas.CreateInitiative,response: schemas.ProjectDetails,},+ CreatePipeline: {+ call: schemas.CreatePipeline,+ response: schemas.CreatePipelineResponse,+ },CreateProject: {call: schemas.CreateProject,response: schemas.CreateProjectResponse,@@ -599,6 +635,10 @@ const toolParserMap = {response: schemas.EditDocumentCommentResponse,},EditForm: { call: schemas.EditForm, response: schemas.MutationResult },+ EditPipeline: {+ call: schemas.EditPipeline,+ response: schemas.EditPipelineResponse,+ },EditPresentation: {call: schemas.EditPresentation,response: schemas.PresentationEditOutcome,@@ -612,6 +652,10 @@ const toolParserMap = {call: schemas.EditWordDocument,response: schemas.WordDocumentResponse,},+ FindPipelineEntries: {+ call: schemas.FindPipelineEntries,+ response: schemas.FindPipelineEntriesResponse,+ },GenerateImage: {call: schemas.GenerateImage,response: schemas.GenerateImageResponse,@@ -707,6 +751,10 @@ const toolParserMap = {call: schemas.ListNotifications,response: schemas.ListNotificationsResponse,},+ ListPipelines: {+ call: schemas.ListPipelines,+ response: schemas.ListPipelinesResponse,+ },ListRoutines: { call: schemas.ListRoutines, response: schemas.RoutineList },ListSkills: {call: schemas.ListSkills,@@ -835,6 +883,10 @@ const toolParserMap = {call: schemas.ReadWordDocument,response: schemas.WordDocumentResponse,},+ RemoveFromPipeline: {+ call: schemas.RemoveFromPipeline,+ response: schemas.RemoveFromPipelineResponse,+ },RenameChannel: {call: schemas.RenameChannel,response: schemas.RenameChannelResponse,@@ -929,6 +981,10 @@ const toolParserMap = {call: schemas.UpdateInitiativeSharing,response: schemas.ProjectDetails,},+ UpdatePipelineEntries: {+ call: schemas.UpdatePipelineEntries,+ response: schemas.UpdatePipelineEntriesResponse,+ },UpdateRoutine: { call: schemas.UpdateRoutine, response: schemas.RoutineInfo },UpdateSharing: {call: schemas.UpdateSharing,@@ -955,6 +1011,10 @@ type NamedRawTool = {};type ToolDataMap = {+ AddToPipeline: {+ call: types.AddToPipeline;+ response: types.AddToPipelineResponse;+ };BashCodeExecution: {call: types.BashCodeExecution;response: types.BashCodeExecutionResponse;@@ -1022,6 +1082,10 @@ type ToolDataMap = {call: types.CreateInitiative;response: types.ProjectDetails;};+ CreatePipeline: {+ call: types.CreatePipeline;+ response: types.CreatePipelineResponse;+ };CreateProject: {call: types.CreateProject;response: types.CreateProjectResponse;@@ -1097,6 +1161,10 @@ type ToolDataMap = {response: types.EditDocumentCommentResponse;};EditForm: { call: types.EditForm; response: types.MutationResult };+ EditPipeline: {+ call: types.EditPipeline;+ response: types.EditPipelineResponse;+ };EditPresentation: {call: types.EditPresentation;response: types.PresentationEditOutcome;@@ -1110,6 +1178,10 @@ type ToolDataMap = {call: types.EditWordDocument;response: types.WordDocumentResponse;};+ FindPipelineEntries: {+ call: types.FindPipelineEntries;+ response: types.FindPipelineEntriesResponse;+ };GenerateImage: {call: types.GenerateImage;response: types.GenerateImageResponse;@@ -1190,6 +1262,10 @@ type ToolDataMap = {call: types.ListNotifications;response: types.ListNotificationsResponse;};+ ListPipelines: {+ call: types.ListPipelines;+ response: types.ListPipelinesResponse;+ };ListRoutines: { call: types.ListRoutines; response: types.RoutineList };ListSkills: { call: types.ListSkills; response: types.ListSkillsResponse };ListTags: { call: types.ListTags; response: types.ListTagsResponse };@@ -1300,6 +1376,10 @@ type ToolDataMap = {call: types.ReadWordDocument;response: types.WordDocumentResponse;};+ RemoveFromPipeline: {+ call: types.RemoveFromPipeline;+ response: types.RemoveFromPipelineResponse;+ };RenameChannel: {call: types.RenameChannel;response: types.RenameChannelResponse;@@ -1382,6 +1462,10 @@ type ToolDataMap = {call: types.UpdateInitiativeSharing;response: types.ProjectDetails;};+ UpdatePipelineEntries: {+ call: types.UpdatePipelineEntries;+ response: types.UpdatePipelineEntriesResponse;+ };UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };UpdateSharing: {call: types.UpdateSharing;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 9612e62219..0304790c12 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -909,6 +909,45 @@ export type CreateImportStatus = 'staged' | 'imported';* Lifecycle of one import entity.*/export type ImportStatus = 'staged' | 'importing' | 'imported' | 'discarded';+/**+ * What a pipeline's entries track. Documented on the fields that use it: a+ * doc comment on a variant would turn the schema into `oneOf`.+ */+export type ToolRecordType = 'company' | 'contact';+/**+ * The type of a field to add. Documented on the fields that use it.+ */+export type ToolNewFieldType =+ | 'text'+ | 'number'+ | 'checkbox'+ | 'date'+ | 'link'+ | 'select'+ | 'multi_select'+ | 'person'+ | 'people';+/**+ * What the user may do with a pipeline.+ */+export type ToolPipelineAccess = 'view' | 'edit' | 'owner';+/**+ * What a field holds, as the model reads it.+ */+export type ToolFieldType =+ | 'company'+ | 'contact'+ | 'text'+ | 'number'+ | 'checkbox'+ | 'date'+ | 'link'+ | 'select'+ | 'tags'+ | 'person'+ | 'item'+ | 'relation'+ | 'formula';/*** Who executes the routine. Agent IDs refer to personas, never conversation IDs.*/@@ -4556,6 +4595,112 @@ export type ReadThreadReadContent =type: 'itemPreviews';};+/**+ * Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.+ */+export interface AddToPipeline {+ /**+ * The pipeline's id from ListPipelines.+ */+ pipelineId: string;+ /**+ * The companies or contacts to add, each with its starting fields.+ */+ entries: ToolNewEntry[];+ /**+ * Add a record again even if it already has an entry in this pipeline. Only for a genuinely separate second deal. Defaults to false.+ */+ allowDuplicates?: boolean | null;+}+/**+ * One company or contact to add.+ */+export interface ToolNewEntry {+ /**+ * The CRM company or contact id to add (company ids come from ListCompanies). Give this or email.+ */+ recordId?: string | null;+ /**+ * A contact's email address instead of an id: adds that contact, or in a company pipeline the contact's company.+ */+ email?: string | null;+ /**+ * Fields to fill in on the new entry, e.g. [{"field": "Stage", "value": "Lead"}, {"field": "Owner", "value": "me"}].+ */+ set?: ToolFieldValue[];+}+/**+ * A field and the value to write or match, as text.+ */+export interface ToolFieldValue {+ /**+ * The field's name exactly as ListPipelines shows it, e.g. "Stage", "Owner", "Revenue".+ */+ field: string;+ /**+ * The value as text: a stage or other option label ("Negotiation"), a person as "me", an email or a macro| user id, a number ("48000"), true/false, or a date ("2026-10-12"). Omit both value and values to empty the field (or, in a filter, to match empty fields).+ */+ value?: string | null;+ /**+ * Several values, for a field that holds several (tags, people). In a filter, an entry matches if it holds any of them, e.g. ["Demo", "Trial"] for either stage.+ */+ values?: string[] | null;+}+/**+ * The entries added.+ */+export interface AddToPipelineResponse {+ /**+ * The new entries, as saved.+ */+ added: ToolEntry[];+ /**+ * Existing entries of requested records that were not added again.+ */+ alreadyPresent: ToolEntry[];+ /**+ * The pipeline's version after the change.+ */+ version?: number | null;+ /**+ * What changed.+ */+ summary: string;+}+/**+ * One pipeline entry.+ */+export interface ToolEntry {+ /**+ * Pass as `entryId`.+ */+ entryId: string;+ record: ToolRecord;+ /**+ * Its filled-in fields by name: text, a number, true/false, a date, or a+ * list when a field holds several values. People are macro| user ids.+ */+ fields: {+ [k: string]: unknown;+ };+}+/**+ * The company or contact an entry tracks.+ */+export interface ToolRecord {+ /**+ * The CRM company or contact id.+ */+ id: string;+ /**+ * Its name; missing when the user cannot see the record.+ */+ name?: string | null;+ /**+ * A company's domain or a contact's email.+ */+ detail?: string | null;+}/*** Execute a bash command in a sandboxed environment using Claude's built-in code execution tool.*/@@ -7240,6 +7385,107 @@ export interface ProjectChannelShare {*/access: string;}+/**+ * Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.+ */+export interface CreatePipeline {+ /**+ * The pipeline's name, e.g. "Q4 Renewals".+ */+ name: string;+ tracks: ToolRecordType;+ /**+ * Let the user's team see and edit it. Defaults to false: only the user can see it.+ */+ sharedWithTeam?: boolean | null;+ /**+ * The stages, first to last, e.g. ["Sourced", "Screen", "Interview", "Offer", "Hired"]. Leave empty for the team's default stages.+ */+ stages?: string[];+ /**+ * Fields to add after Company/Contact, Stage, Owner and Revenue.+ */+ fields?: ToolNewField[];+}+/**+ * A field to add to a pipeline.+ */+export interface ToolNewField {+ /**+ * The new field's name, unique in the pipeline.+ */+ name: string;+ type: ToolNewFieldType;+ /**+ * For select and multi_select: the labels to choose from, in order.+ */+ options?: string[];+}+/**+ * The pipeline created.+ */+export interface CreatePipelineResponse {+ pipeline: ToolPipeline;+ /**+ * What changed.+ */+ summary: string;+}+/**+ * A pipeline as the model sees it.+ */+export interface ToolPipeline {+ /**+ * Pass as `pipelineId`.+ */+ id: string;+ /**+ * Its name.+ */+ name: string;+ tracks: ToolRecordType;+ access: ToolPipelineAccess;+ /**+ * Whether the owner's team may edit it; otherwise it is private.+ */+ sharedWithTeam: boolean;+ /**+ * Its fields in column order; the first names the tracked record.+ */+ fields: ToolField[];+ /**+ * Its version now; pass as `baseVersion` to refuse an update if the+ * pipeline changed in between.+ */+ version: number;+}+/**+ * One field of a pipeline.+ */+export interface ToolField {+ /**+ * The name to use in `field`.+ */+ name: string;+ type: ToolFieldType;+ /**+ * Whether it holds several values.+ */+ multiple: boolean;+ /**+ * For a select field, its labels in order: for Stage, the pipeline's+ * stages from first to last.+ */+ options: string[];+ /**+ * Whether every entry must have a value.+ */+ required: boolean;+ /**+ * Whether the user cannot write it.+ */+ readOnly: boolean;+}/*** Create a project — shown as a folder in the app UI. Documents, AI chats, email threads, and other projects can be placed inside it.*/@@ -8065,6 +8311,113 @@ export interface NewColumnDraft {*/options?: QuestionOption[];}+/**+ * Change a CRM pipeline itself: rename it, share it with the team or make it private (owner only), add, rename or remove fields, and add, rename or remove stages and other select options. Stages are the options of the Stage field: to add a stage use addOptions on "Stage"; to rename one use renameOptions. Removing a field deletes its values from every entry, and removing a stage or option empties it on the entries holding it, so do that only when the user asked. New options go after the existing ones. Field changes apply together, all or nothing. Returns the pipeline with its fields as they are now.+ */+export interface EditPipeline {+ /**+ * The pipeline's id from ListPipelines.+ */+ pipelineId: string;+ /**+ * A new name for the pipeline.+ */+ name?: string | null;+ /**+ * true lets the user's team see and edit it; false makes it private to its owner. Only the owner can change this.+ */+ sharedWithTeam?: boolean | null;+ /**+ * Fields to add after the existing ones.+ */+ addFields?: ToolNewField[];+ /**+ * Fields to rename.+ */+ renameFields?: ToolRename[];+ /**+ * Names of fields to delete with their values. The Company or Contact field cannot be removed.+ */+ removeFields?: string[];+ /**+ * Stages or other select options to add.+ */+ addOptions?: ToolAddOptions[];+ /**+ * Stages or other select options to relabel.+ */+ renameOptions?: ToolRenameOption[];+ /**+ * Stages or other select options to delete.+ */+ removeOptions?: ToolRemoveOption[];+}+/**+ * A field to rename.+ */+export interface ToolRename {+ /**+ * The current name.+ */+ from: string;+ /**+ * The new name.+ */+ to: string;+}+/**+ * Options to add to a select field.+ */+export interface ToolAddOptions {+ /**+ * The select field, e.g. "Stage".+ */+ field: string;+ /**+ * Labels to add after the existing ones.+ */+ labels: string[];+}+/**+ * An option to relabel.+ */+export interface ToolRenameOption {+ /**+ * The select field, e.g. "Stage".+ */+ field: string;+ /**+ * The option's current label.+ */+ from: string;+ /**+ * Its new label; entries holding it keep it.+ */+ to: string;+}+/**+ * An option to delete.+ */+export interface ToolRemoveOption {+ /**+ * The select field, e.g. "Stage".+ */+ field: string;+ /**+ * The option to delete.+ */+ label: string;+}+/**+ * The pipeline after the change.+ */+export interface EditPipelineResponse {+ pipeline: ToolPipeline;+ /**+ * What changed.+ */+ summary: string;+}/*** Edit a PowerPoint (.pptx) presentation: an ordered batch of operations applied atomically and saved as a new version, so if any operation fails nothing is saved. To make a new deck from an existing one instead (a translation, a variant, a copy to rework), pass saveAs: the edited deck is created as a new presentation, whose documentId is returned for further batches, and the original is left unchanged; operations may then be empty for a plain copy. ReadPresentation first; address slides and shapes by the ids it reports (slide ids are not slide numbers). Positions and sizes are in points from the slide's top-left corner. Text offsets count characters within a paragraph; \n separates paragraphs. Colors are RRGGBB hex or theme names (accent1-accent6, tx1, tx2, bg1, bg2). Use setText to rewrite a shape's text (it keeps each paragraph's formatting), formatText/formatParagraphs for styling (the whole shape when no range is given), formatBody for a text box's margins, autofit, columns, and Text Direction (vertical or stacked text, in table cells too), addSlide with a layout name for new slides (title and body fill its placeholders), addShape for text boxes, preset shapes, lines, tables, charts, or images, setChartData/setChartType/formatChart for charts the read marks editable, mergeCells/formatCells/setTableStyle/setTableGrid for tables (cell text through the text ops with cell), cropPicture/formatPicture for pictures (crop, fill or fit the frame, brightness, contrast, recolor, transparency), groupShapes/ungroupShape, setSlideLayout, setTransition, setAnimations/addAnimation/removeAnimations for a slide's click-through animations (entrance, emphasis, exit, and motion path effects by name, in playback order; setAnimations replaces the whole list and keeps listed existing ones), setShapeEffects for shadows, glows, soft edges, and reflections (by gallery preset name or options; formatText takes text shadow and glow too), setCustomGeometry to redraw a shape's outline as paths in shape-local points (moveTo/lineTo/cubicBezTo/quadBezTo/arcTo/close; the box follows the paths, keeping its formatting and text), mergeShapes to union/combine/fragment/intersect/subtract overlapping shapes (in selection order; the first shape's formatting and id win), SmartArt through addShape {kind: smartArt, layout, items: [{text, level}], colors, style}, editSmartArt (setText, addNode, deleteNode, promote, demote, moveUp, moveDown, setNodes, setLayout, setColors, setStyle, reset, by the node ids the read lists) and convertSmartArt (to shapes or text), equations with insertEquation (LaTeX-style linear text such as \frac{a}{b}, x^2, \sqrt{x}, \sum_{i=1}^{n}; without shape it makes a new centered text box) and setEquation (an equation stands in its paragraph as one U+FFFC character at the index the read lists; delete it with deleteText over that character), review comments with addComment/replyComment/editComment/resolveComment/deleteComment/deleteAllComments (thread ids from the read; legacy threads can only be edited or deleted; sign them with the user's name), slide masters and layouts by passing a master or layout id (the read lists them, at least 2147483648) as slide to shape, text, table, picture, or background ops so the change reaches every slide using it, plus addLayout/renameLayout/deleteLayout/insertPlaceholder/setLayoutOptions and setBackgroundStyle (1-12), setThemeColors/setThemeFonts to restyle the whole deck through its theme (prefer them over recoloring shapes one by one), setHeaderFooter for slide numbers, dates, and footers (omit slides to apply to all), setSlideSize to change the slide size (scale fit shrinks content to the new size), addSection/renameSection/removeSection/moveSection to organize slides into sections (by the section ids the read reports), setGuides to replace the deck's drawing guides, and replaceText for find-and-replace across the deck. Ids of created slides and shapes are returned with the changed slides as they now read; check them. At most 100 operations.*/@@ -8732,6 +9085,135 @@ export interface WordDocumentResponse {*/content: string;}+/**+ * Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.+ */+export interface FindPipelineEntries {+ /**+ * The pipeline's id from ListPipelines. Leave it out to look in every pipeline by `search` or `recordIds`; filters and sorting need a pipelineId.+ */+ pipelineId?: string | null;+ /**+ * Only entries whose fields hold these values; all filters must match. Options and people match exactly (labels ignore case), text matches a substring, dates match the day. Example: [{"field": "Stage", "values": ["Demo", "Trial"]}, {"field": "Owner", "value": "me"}].+ */+ filters?: ToolFieldValue[];+ /**+ * Only entries tracking these CRM company or contact ids.+ */+ recordIds?: string[];+ /**+ * Text the tracked company's name or domain, or the contact's name or email, must contain, ignoring case (e.g. "acme").+ */+ search?: string | null;+ /**+ * A field name to order entries by, e.g. "Revenue" or "Stage". Empty fields come last.+ */+ sortBy?: string | null;+ /**+ * Sort largest, latest or furthest stage first. Defaults to false.+ */+ descending?: boolean | null;+ /**+ * Most entries to return. Defaults to 50; max 200.+ */+ limit?: number | null;+}+/**+ * The entries found.+ */+export interface FindPipelineEntriesResponse {+ /**+ * Matching entries, grouped by pipeline.+ */+ pipelines: ToolPipelineEntries[];+ /**+ * How many entries matched; more than returned when `limit` cut them.+ */+ matched: number;+ /**+ * Whether every entry of the pipeline was read. When false the pipeline+ * is too large to read whole, and counts and totals are partial.+ */+ complete: boolean;+ /**+ * Matching entries per stage (and per option of every other+ * single-select field), over all matches.+ */+ counts: ToolOptionCounts[];+ /**+ * The sum of every number field, such as Revenue, over all matches.+ */+ totals: ToolTotal[];+ /**+ * What was found.+ */+ summary: string;+}+/**+ * One pipeline's matching entries.+ */+export interface ToolPipelineEntries {+ /**+ * The pipeline's id.+ */+ pipelineId: string;+ /**+ * The pipeline's name.+ */+ pipelineName: string;+ /**+ * The pipeline's version when read; pass as `baseVersion` to+ * UpdatePipelineEntries to refuse the update if it changed since.+ */+ version?: number | null;+ /**+ * The entries.+ */+ entries: ToolEntry[];+}+/**+ * Matching entries per option of one single-select field, such as Stage.+ */+export interface ToolOptionCounts {+ /**+ * The field.+ */+ field: string;+ /**+ * Every option in order with its count.+ */+ counts: ToolOptionCount[];+ /**+ * Matching entries with the field empty.+ */+ empty: number;+}+/**+ * How many matching entries hold one option.+ */+export interface ToolOptionCount {+ /**+ * The option's label.+ */+ label: string;+ /**+ * Matching entries holding it.+ */+ count: number;+}+/**+ * The sum of a number field over the matching entries.+ */+export interface ToolTotal {+ /**+ * The field.+ */+ field: string;+ /**+ * The sum.+ */+ sum: number;+}/*** Generate or edit an image with Google's Nano Banana image model and save the result in static file service. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the static file ID and image URL. The tool displays the image inline in chat. In channel messages without tool cards, copy the returned markdown verbatim on its own line; it includes dimensions so the image reserves space before loading. Do not cite it as a document. Generation takes several seconds.*/@@ -8986,7 +9468,7 @@ export interface GetBotWebhooksResponse {summary: string;}/**- * Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response.+ * Fetch one of the team's CRM companies by id, with its domains, contacts, its own Stage / Owner / Revenue properties (not a pipeline deal's), and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change one of the company's own properties (its Stage, Owner, Revenue or a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response. Deals in a pipeline have their own stage and fields: find them with FindPipelineEntries (recordIds = this company's id) and change them with UpdatePipelineEntries.*/export interface GetCompany {/**@@ -9031,7 +9513,8 @@ export interface GetCompanyResponse {*/lastInteraction: string;/**- * The company's pipeline stage, if set.+ * The company's own Stage property, if set; separate from any+ * pipeline entry's stage.*/stage?: ToolCompanyStage | null;/**@@ -9057,7 +9540,7 @@ export interface GetCompanyResponse {summary: string;}/**- * A company's pipeline stage: the select option id currently set plus its+ * A company's own Stage property: the select option id currently set plus its* human-readable label.*/export interface ToolCompanyStage {@@ -9823,7 +10306,7 @@ export interface CodingAgent {model?: string | null;}/**- * List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties.+ * List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and the company's own Stage / Owner / Revenue properties when set (not a pipeline deal's). Use the filters to narrow results: `search` for name/domain text, `stage` for the company's own Stage property, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to change the company's own Stage / Owner / Revenue or custom properties. Deals in a pipeline have their own stage and fields, separate from these: use FindPipelineEntries and UpdatePipelineEntries for them.*/export interface ListCompanies {/**@@ -9831,7 +10314,7 @@ export interface ListCompanies {*/search?: string | null;/**- * Filter to companies in this pipeline stage. Accepts a stage label matched case-insensitively (e.g. "lead", "Customer" — teams may have custom stage names) or a stage option UUID.+ * Filter to companies whose own Stage property (not a pipeline deal's stage) is this. Accepts a stage label matched case-insensitively (e.g. "lead", "Customer" — teams may have custom stage names) or a stage option UUID.*/stage?: string | null;/**@@ -9886,7 +10369,8 @@ export interface CompanyListItem {*/lastInteraction: string;/**- * The company's pipeline stage, if set.+ * The company's own Stage property, if set; separate from any+ * pipeline entry's stage.*/stage?: ToolCompanyStage | null;/**@@ -10419,6 +10903,23 @@ export interface NotificationItem {*/senderId?: string | null;}+/**+ * List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.+ */+export type ListPipelines = {};+/**+ * The user's pipelines.+ */+export interface ListPipelinesResponse {+ /**+ * Every live pipeline the user can see.+ */+ pipelines: ToolPipeline[];+ /**+ * What was found.+ */+ summary: string;+}/*** Find the authenticated user’s routines, including work delegated to other agents. Filter by name/instructions or enabled state. Returns up to 50 matches and the full count; narrow the query if truncated. Use ReadRoutine for history.*/@@ -12438,6 +12939,40 @@ export interface ReadWordDocument {*/count?: number | null;}+/**+ * Remove deals (entries) from a CRM pipeline, deleting their stage and other pipeline fields. The companies and contacts themselves stay in the CRM and in other pipelines. Address entries by entryId, or by the company or contact id they track (which removes every entry of that record in this pipeline). Only when the user asked to remove them.+ */+export interface RemoveFromPipeline {+ /**+ * The pipeline's id from ListPipelines.+ */+ pipelineId: string;+ /**+ * Entry ids from FindPipelineEntries.+ */+ entryIds?: string[];+ /**+ * CRM company or contact ids whose entries to remove.+ */+ recordIds?: string[];+}+/**+ * The entries removed.+ */+export interface RemoveFromPipelineResponse {+ /**+ * Each removed entry as it was.+ */+ removed: ToolEntry[];+ /**+ * The pipeline's version after the change.+ */+ version?: number | null;+ /**+ * What changed.+ */+ summary: string;+}/*** Rename an existing channel. Requires the current user to be an active channel participant. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.*/@@ -12962,7 +13497,7 @@ export interface SendEmail {* - Project (00000001-0000-0000-0000-000000000014): entity, single. Use entity_ref with entity_type='initiative' and the project UUID; send no value field to remove the task from its project. Setting it requires edit access to the task and the project, and the project's agents are assigned to the task.** CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties:- * - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids.+ * - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. This is the company's own Stage, not a deal's stage in a CRM pipeline: move pipeline deals with UpdatePipelineEntries.* - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'.* - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars).* Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only.@@ -13419,6 +13954,92 @@ export interface ProjectChannelSharing {channelId: string;access: ProjectShareAccess;}+/**+ * Move deals to another stage or change their fields in a CRM pipeline: "move Acme to Negotiation", "set the revenue on the Globex deal", "assign these deals to Sam". Address each entry by entryId (from FindPipelineEntries) or by the company or contact id it tracks, and set fields by name with text values: stages and other options by label, people as "me", an email or a macro| user id, numbers, true/false, or dates. Several entries change in one call, all or nothing. Returns each field before and after. This changes the entry in the pipeline, not the company's own properties.+ */+export interface UpdatePipelineEntries {+ /**+ * The pipeline's id from ListPipelines.+ */+ pipelineId: string;+ /**+ * The entries to change, each with its fields to set.+ */+ updates: ToolEntryUpdate[];+ /**+ * Optional: the pipeline version from the FindPipelineEntries read these changes are based on. The update is refused if the pipeline changed since; leave out for a direct change.+ */+ baseVersion?: number | null;+}+/**+ * The changes to one entry.+ */+export interface ToolEntryUpdate {+ /**+ * The entry's id from FindPipelineEntries. Give this or recordId.+ */+ entryId?: string | null;+ /**+ * Instead of entryId: the CRM company or contact id the entry tracks. Refused if the record has several entries in this pipeline; then use entryId.+ */+ recordId?: string | null;+ /**+ * Fields to set, e.g. [{"field": "Stage", "value": "Negotiation"}, {"field": "Revenue", "value": "48000"}]. Leave value out to empty a field.+ */+ set: ToolFieldValue[];+}+/**+ * The entries changed.+ */+export interface UpdatePipelineEntriesResponse {+ /**+ * Each changed entry, as saved.+ */+ updated: ToolUpdatedEntry[];+ /**+ * The pipeline's version after the change.+ */+ version?: number | null;+ /**+ * What changed.+ */+ summary: string;+}+/**+ * An updated entry.+ */+export interface ToolUpdatedEntry {+ /**+ * The entry.+ */+ entryId: string;+ record: ToolRecord;+ /**+ * The fields set.+ */+ changes: ToolFieldChange[];+}+/**+ * One field's value before and after.+ */+export interface ToolFieldChange {+ /**+ * The field.+ */+ field: string;+ /**+ * Its value before; null when it was empty.+ */+ before: {+ [k: string]: unknown;+ };+ /**+ * Its value now; null when it is empty.+ */+ after: {+ [k: string]: unknown;+ };+}/*** Pause/resume or replace the configuration of a routine owned by the authenticated user. ReadRoutine first before replacing configuration. Select an agent to delegate the routine or a model to run as Macro. Does not change ownership. A running routine can be paused but cannot be reconfigured until it finishes.*/diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex f7340c1496..05d8654631 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -510,6 +510,12 @@ pub async fn build_tool_service_context_from_env(soup_service.clone(),pool.clone(),);+ let crm_tool_context = crate::tool_context::build_crm_tool_context(pool.clone());+ let pipeline_tool_context = crate::tool_context::build_pipeline_tool_context(+ pool.clone(),+ &databases_tool_context,+ &crm_tool_context,+ );let forms_tool_context = crate::tool_context::build_forms_tool_context(pool.clone(),@@ -648,7 +654,8 @@ pub async fn build_tool_service_context_from_env(),initiative_tool_context,team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),- crm_tool_context: crate::tool_context::build_crm_tool_context(pool.clone()),+ crm_tool_context,+ pipeline_tool_context,skill_tool_context,schedule_tool_context: crate::build_routine_tool_context()?,anthropic_tool_context,diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 825230fc9b..1e39e1f27b 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -35,7 +35,7 @@ use calendar_scheduling::inbound::toolset::{use call::inbound::toolset::call_toolset;use channels::inbound::toolset::channel_toolset;use chat::inbound::toolset::chat_toolset;-use crm::inbound::toolset::crm_toolset;+use crm::inbound::toolset::{crm_toolset, pipelines::pipeline_toolset};use databases::inbound::toolset::{databases_read_only_toolset, databases_toolset};use databases_sql::toolset::{QueryDatabase, databases_sql_toolset};use display_results::DisplayResults;@@ -83,9 +83,10 @@ pub use tool_context::{ToolImageGenerationToolContext, ToolImportService, ToolImportToolContext,ToolInitiativeToolContext, ToolItemNotificationPreferenceToolContext, ToolMcpSelector,ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,- ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,- ToolPropertiesToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,- ToolSoupService, ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,+ ToolPipedreamConnection, ToolPipelineService, ToolPipelineToolContext, ToolPipelineWorkflows,+ ToolProjectService, ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,+ ToolServiceContext, ToolSkillService, ToolSkillToolContext, ToolSoupService,+ ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,ToolTeamCalendarToolContext, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context,build_booking_link_tool_context, build_booking_management_tool_context, build_bot_tool_context,@@ -95,10 +96,11 @@ pub use tool_context::{build_databases_tool_context, build_favorites_service, build_favorites_tool_context,build_forms_tool_context, build_image_generation_tool_context, build_initiative_tool_context,build_item_notification_preference_tool_context, build_message_service_with_side_effects,- build_message_service_without_side_effects, build_project_tool_context,- build_properties_service, build_properties_service_with_broker, build_properties_tool_context,- build_routine_tool_context, build_skill_tool_context, build_task_properties_adapter,- build_team_calendar_tool_context, build_team_repository, build_team_tool_context,+ build_message_service_without_side_effects, build_pipeline_tool_context,+ build_project_tool_context, build_properties_service, build_properties_service_with_broker,+ build_properties_tool_context, build_routine_tool_context, build_skill_tool_context,+ build_task_properties_adapter, build_team_calendar_tool_context, build_team_repository,+ build_team_tool_context,};pub use tool_context::{ToolConnectorToolContext, build_connector_tool_context};#[cfg(any(test, feature = "test-support"))]@@ -161,6 +163,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {.add_subtoolset::<ToolBotToolContext>(bot_toolset()).add_subtoolset::<ToolTeamToolContext>(team_toolset()).add_subtoolset::<ToolCrmToolContext>(crm_toolset())+ .add_subtoolset::<ToolPipelineToolContext>(pipeline_toolset()).add_subtoolset::<ToolDatabasesToolContext>(databases_toolset()).add_subtoolset::<ToolFormsToolContext>(forms::inbound::toolset::authoring_toolset()).add_subtoolset::<ToolDatabasesSqlToolContext>(databases_sql_toolset())diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex daea595bc5..6ad924b076 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -589,6 +589,61 @@ pub fn build_crm_tool_context(pool: sqlx::PgPool) -> ToolCrmToolContext {}}+/// CRM pipelines over the databases service and access the database tools+/// use, so a pipeline write reaches open clients the same way.+pub type ToolPipelineService = crm::domain::pipelines::PipelineServiceImpl<+ crm::outbound::pipelines::PgPipelineRepo<+ databases::outbound::pg_cell_store::PgCellStore<properties::PropertiesPgRepo>,+ >,+ ToolDatabasesService,+ ToolEntityAccessService,+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore<ToolPropertiesService>,+>;++/// Pipeline workflows: entries by record and fields by name, for agents.+pub type ToolPipelineWorkflows = crm::domain::pipeline_workflows::PipelineWorkflowServiceImpl<+ ToolPipelineService,+ ToolCrmService,+ ToolEntityAccessService,+>;++/// Type alias for the CRM pipeline AI tool context.+pub type ToolPipelineToolContext =+ crm::inbound::toolset::pipelines::PipelineToolContext<ToolPipelineWorkflows>;++/// Build the pipeline tools over the database tools' service and access and+/// the CRM tools' records and stage template.+pub fn build_pipeline_tool_context(+ pool: sqlx::PgPool,+ databases: &ToolDatabasesToolContext,+ crm: &ToolCrmToolContext,+) -> ToolPipelineToolContext {+ let pipelines = crm::domain::pipelines::PipelineServiceImpl::new(+ crm::outbound::pipelines::PgPipelineRepo::new(+ pool.clone(),+ databases::outbound::pg_cell_store::PgCellStore::new(+ pool.clone(),+ properties::PropertiesPgRepo::new(pool),+ ),+ ),+ databases.service.clone(),+ databases.entity_access_service.clone(),+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore::new(+ crm.properties.clone(),+ ),+ );+ crm::inbound::toolset::pipelines::PipelineToolContext {+ service: Arc::new(+ crm::domain::pipeline_workflows::PipelineWorkflowServiceImpl::new(+ Arc::new(pipelines),+ crm.service.clone(),+ databases.entity_access_service.clone(),+ ),+ ),+ actor: databases.actor,+ }+}+/// Type alias for the skill service implementation used by AI tools.pub type ToolSkillService = skills::domain::service::SkillServiceImpl<skills::outbound::search_service_searcher::SearchServiceSkillSearcher,@@ -1734,6 +1789,8 @@ pub struct ToolServiceContext {pub initiative_tool_context: ToolInitiativeToolContext,pub team_tool_context: ToolTeamToolContext,pub crm_tool_context: ToolCrmToolContext,+ /// CRM pipelines: deals by record, fields by name.+ pub pipeline_tool_context: ToolPipelineToolContext,pub skill_tool_context: ToolSkillToolContext,pub schedule_tool_context: RoutineToolContext,#[from_ref(skip)]@@ -1803,6 +1860,7 @@ impl ToolServiceContext {self.channel_tool_context = self.channel_tool_context.with_actor(actor);self.databases_tool_context = self.databases_tool_context.with_actor(actor);self.forms_tool_context.actor = actor;+ self.pipeline_tool_context.actor = actor;self.databases_sql_tool_context = self.databases_sql_tool_context.with_actor(actor);self}diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.tomlindex 6743f18742..f39fa20a83 100644--- a/crates/complete_graph/Cargo.toml+++ b/crates/complete_graph/Cargo.toml@@ -58,6 +58,7 @@ uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+bot_id = { path = "../bot_id" }crm = { path = "../crm", default-features = false, features = ["ports"] }databases = { path = "../databases", default-features = false, features = ["ports"] }activity = { path = "../activity", default-features = false, features = ["realtime"] }diff --git a/crates/complete_graph/src/schema/test/crm_record.rs b/crates/complete_graph/src/schema/test/crm_record.rsindex 4d9a167a7b..1879ce67f0 100644--- a/crates/complete_graph/src/schema/test/crm_record.rs+++ b/crates/complete_graph/src/schema/test/crm_record.rs@@ -1,7 +1,7 @@use ::crm::domain::{auth::CrmTeamReceipt, pipelines::*};use databases::domain::{models::{AppliedOps, OpBatch, RowId, TableDetail},- storage::{StorageRows, StorageRowsQuery},+ storage::{StorageRow, StorageRows, StorageRowsQuery},};use entity_access::domain::models::{EditAccessLevel, MemberTeamRole, OwnerAccessLevel, ViewAccessLevel,@@ -68,9 +68,24 @@ impl PipelineService for RecordingPipelines {) -> Result<StorageRows, PipelineError> {unimplemented!()}+ async fn read_rows(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ _: &[RowId],+ ) -> Result<Vec<StorageRow>, PipelineError> {+ unimplemented!()+ }+ async fn record_rows(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ _: &[Uuid],+ ) -> Result<Vec<PipelineReference>, PipelineError> {+ unimplemented!()+ }async fn apply_ops(&self,_: EntityAccessReceipt<EditAccessLevel>,+ _: Option<bot_id::BotId>,_: OpBatch,) -> Result<AppliedOps, PipelineError> {unimplemented!()diff --git a/crates/crm/Cargo.toml b/crates/crm/Cargo.tomlindex 9b09d95ddc..0cd7e2691e 100644--- a/crates/crm/Cargo.toml+++ b/crates/crm/Cargo.toml@@ -54,12 +54,13 @@ outbound = ["dep:unfurl","ports",]-ports = ["dep:databases", "dep:models_databases", "dep:models_properties", "dep:macro_user_id", "dep:macro_uuid", "dep:rootcause", "dep:utoipa", "entity_access/ports"]+ports = ["dep:bot_id", "dep:databases", "dep:models_databases", "dep:models_properties", "dep:macro_user_id", "dep:macro_uuid", "dep:rootcause", "dep:utoipa", "entity_access/ports"]# Read-only CRM search (name/domain). Pulls only sqlx + ports — no# reqwest/unfurl/axum — so search consumers stay lightweight.search = ["dep:sqlx", "ports"][dependencies]+bot_id = { path = "../bot_id", optional = true }databases = { path = "../databases", default-features = false, features = ["ports"], optional = true }models_databases = { path = "../models_databases", optional = true }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }diff --git a/crates/crm/src/domain.rs b/crates/crm/src/domain.rsindex 13ba0f3ded..9d724ee4d7 100644--- a/crates/crm/src/domain.rs+++ b/crates/crm/src/domain.rs@@ -37,6 +37,9 @@ pub mod search_service;/// Contact listing models shared by Soup and the CRM service.#[cfg(feature = "ports")]pub mod contact_listing;+/// Pipeline use cases addressed by record, field name and stage label.+#[cfg(feature = "ports")]+pub mod pipeline_workflows;/// CRM pipelines and their lifecycle.#[cfg(feature = "ports")]pub mod pipelines;diff --git a/crates/crm/src/domain/pipeline_workflows.rs b/crates/crm/src/domain/pipeline_workflows.rsnew file mode 100644index 0000000000..5b12562ddb--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows.rs@@ -0,0 +1,980 @@+//! Pipeline use cases addressed the way people talk about a pipeline: entries+//! by the company or contact they track, fields by name, stages by label.+//!+//! Each workflow resolves those names against the pipeline's current schema,+//! then reads and writes through [`PipelineService`], so the pipeline's+//! access, policy and the shared database operations stay the only path to+//! its storage.++mod entries;+mod fields;+mod models;+mod ops;+mod records;++use std::collections::{HashMap, HashSet};+use std::sync::Arc;++use databases::domain::{+ models::{OpBatch, RowId, TableVersion, Viewer},+ storage::{StorageRow, StorageRowsQuery},+};+use entity_access::domain::{+ models::{+ AccessError, EditAccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType,+ MemberTeamRole, OwnerAccessLevel, RequiredPermission, ViewAccessLevel,+ },+ ports::EntityAccessService,+};+use models_databases::{+ CellValue, CellWrite, ColumnChange, DatabaseOp, EntityRef, OpResult, RowChange, RowChanges,+ RowsChange, RowsResult,+};+use uuid::Uuid;++use super::{+ auth::CrmTeamReceipt,+ pipelines::{CreatePipeline, PipelineRecordType, PipelineService},+ service::CrmService,+};++pub use fields::{FieldInput, FieldKind, FieldValue, NewFieldKind, PipelineField};+pub use models::{+ AddedEntries, EntryAddition, EntryQuery, EntryTarget, EntryUpdate, FieldChange, FoundEntries,+ MAX_SCANNED_ROWS, NewField, NewPipeline, OptionCounts, PipelineEdit, PipelineEntryView,+ PipelineOverview, RecordEntries, RecordTarget, RemovedEntries, UpdatedEntries, UpdatedEntry,+ WorkflowError,+};+pub use records::PipelineRecord;++use entries::{entry_view, field_values, option_counts, record_id, totals, value_of};+use ops::{STAGE_FIELD, add_field, add_options, cells, select_field};++/// Pipeline workflows for a viewer, who may be an agent acting for a user.+pub trait PipelineWorkflowService: Send + Sync + 'static {+ /// The viewer's live pipelines with their fields.+ fn pipelines(+ &self,+ viewer: &Viewer,+ ) -> impl Future<Output = Result<Vec<PipelineOverview>, WorkflowError>> + Send;++ /// Entries of one pipeline matching `query`.+ fn find(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ query: EntryQuery,+ ) -> impl Future<Output = Result<FoundEntries, WorkflowError>> + Send;++ /// Entries of every pipeline the viewer can see whose company or contact+ /// matches `search`, at most `limit` per pipeline; pipelines without a+ /// match are left out.+ fn search_entries(+ &self,+ viewer: &Viewer,+ search: &str,+ limit: usize,+ ) -> impl Future<Output = Result<Vec<RecordEntries>, WorkflowError>> + Send;++ /// Every entry tracking one of `records`, across the viewer's pipelines.+ fn record_entries(+ &self,+ viewer: &Viewer,+ records: &[Uuid],+ ) -> impl Future<Output = Result<Vec<RecordEntries>, WorkflowError>> + Send;++ /// Add entries; a record already in the pipeline is added again only+ /// when `allow_duplicates`.+ fn add(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ additions: Vec<EntryAddition>,+ allow_duplicates: bool,+ ) -> impl Future<Output = Result<AddedEntries, WorkflowError>> + Send;++ /// Set fields of entries, refused if the table moved past `base_version`.+ fn update(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ updates: Vec<EntryUpdate>,+ base_version: Option<TableVersion>,+ ) -> impl Future<Output = Result<UpdatedEntries, WorkflowError>> + Send;++ /// Delete entries; their companies and contacts stay in the CRM.+ fn remove(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ targets: Vec<EntryTarget>,+ ) -> impl Future<Output = Result<RemovedEntries, WorkflowError>> + Send;++ /// Create a pipeline, then set its stages and add its fields.+ fn create(+ &self,+ viewer: &Viewer,+ input: NewPipeline,+ ) -> impl Future<Output = Result<PipelineOverview, WorkflowError>> + Send;++ /// Rename, share, or change the fields of a pipeline.+ fn edit(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ edit: PipelineEdit,+ ) -> impl Future<Output = Result<PipelineOverview, WorkflowError>> + Send;+}++/// [`PipelineWorkflowService`] over the pipeline and CRM services.+pub struct PipelineWorkflowServiceImpl<Pipelines, Crm, Access> {+ pipelines: Arc<Pipelines>,+ crm: Arc<Crm>,+ access: Arc<Access>,+}++impl<Pipelines, Crm, Access> PipelineWorkflowServiceImpl<Pipelines, Crm, Access> {+ /// Compose the workflows from the services they run through.+ pub fn new(pipelines: Arc<Pipelines>, crm: Arc<Crm>, access: Arc<Access>) -> Self {+ Self {+ pipelines,+ crm,+ access,+ }+ }+}++impl<Pipelines, Crm, Access> PipelineWorkflowServiceImpl<Pipelines, Crm, Access>+where+ Pipelines: PipelineService,+ Crm: CrmService,+ Access: EntityAccessService,+{+ async fn receipt<T: RequiredPermission>(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ ) -> Result<EntityAccessReceipt<T>, WorkflowError> {+ Ok(self+ .access+ .generate_entity_access_receipt::<T>(+ &viewer.user_id,+ None,+ &pipeline.to_string(),+ EntityType::CrmPipeline,+ )+ .await?)+ }++ /// The viewer's team CRM, `None` for a user in no team.+ async fn team(+ &self,+ viewer: &Viewer,+ ) -> Result<Option<CrmTeamReceipt<MemberTeamRole>>, WorkflowError> {+ let Some(team) = self.access.get_user_team(&viewer.user_id).await? else {+ return Ok(None);+ };+ let receipt = EntityAccessReceipt::try_new_authenticated_user(+ viewer.user_id.clone(),+ Entity {+ entity_id: team.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole { role: team.role },+ )?;+ Ok(Some(CrmTeamReceipt::from_team_receipt(receipt)?))+ }++ async fn overview(+ &self,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<PipelineOverview, WorkflowError> {+ let pipeline = self.pipelines.get(receipt.clone()).await?;+ let table = self.pipelines.table(receipt.clone()).await?;+ Ok(PipelineOverview::new(pipeline, table))+ }++ /// The records `rows` track, named as the viewer sees them.+ async fn records(+ &self,+ viewer: &Viewer,+ team: Option<&CrmTeamReceipt<MemberTeamRole>>,+ overview: &PipelineOverview,+ rows: &[&StorageRow],+ ) -> Result<HashMap<Uuid, PipelineRecord>, WorkflowError> {+ let record_field = overview.record_field();+ let ids: Vec<Uuid> = rows+ .iter()+ .filter_map(|row| record_id(row.cells.get(&record_field.id)))+ .collect::<HashSet<_>>()+ .into_iter()+ .collect();+ Ok(records::records(+ self.crm.as_ref(),+ team,+ viewer.user_id.as_ref(),+ overview.pipeline.pipeline.record_type,+ &ids,+ )+ .await?)+ }++ /// The entries `targets` name: an entry must be this pipeline's, a+ /// record must have one entry when `one_per_record`.+ async fn target_rows(+ &self,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+ overview: &PipelineOverview,+ targets: &[EntryTarget],+ one_per_record: bool,+ ) -> Result<Vec<Vec<RowId>>, WorkflowError> {+ let name = &overview.pipeline.pipeline.name;+ let records: Vec<Uuid> = targets+ .iter()+ .filter_map(|target| match target {+ EntryTarget::Record(id) => Some(*id),+ EntryTarget::Entry(_) => None,+ })+ .collect();+ let mut by_record: HashMap<Uuid, Vec<RowId>> = HashMap::new();+ for reference in self+ .pipelines+ .record_rows(receipt.clone(), &records)+ .await?+ {+ by_record+ .entry(reference.record_id)+ .or_default()+ .push(reference.row_id);+ }+ let entries: Vec<RowId> = targets+ .iter()+ .filter_map(|target| match target {+ EntryTarget::Entry(id) => Some(*id),+ EntryTarget::Record(_) => None,+ })+ .collect();+ let existing: HashSet<RowId> = if entries.is_empty() {+ HashSet::new()+ } else {+ self.pipelines+ .read_rows(receipt.clone(), &entries)+ .await?+ .into_iter()+ .map(|row| row.row_id)+ .collect()+ };+ targets+ .iter()+ .map(|target| match target {+ EntryTarget::Entry(id) if existing.contains(id) => Ok(vec![*id]),+ EntryTarget::Entry(id) => Err(WorkflowError::Invalid(format!(+ "Pipeline \"{name}\" has no entry {id}. Find entry ids with FindPipelineEntries."+ ))),+ EntryTarget::Record(id) => match by_record.remove(id) {+ None => Err(WorkflowError::Invalid(format!(+ "Record {id} has no entry in pipeline \"{name}\". Add it with AddToPipeline."+ ))),+ Some(rows) if one_per_record && rows.len() > 1 => {+ let ids: Vec<String> = rows.iter().map(ToString::to_string).collect();+ Err(WorkflowError::Invalid(format!(+ "Record {id} has {} entries in pipeline \"{name}\" ({}). Name the \+ one to change by its entryId.",+ rows.len(),+ ids.join(", ")+ )))+ }+ Some(rows) => Ok(rows),+ },+ })+ .collect()+ }++ /// Apply `ops` as the viewer, with the table's version after the write.+ async fn apply(+ &self,+ receipt: EntityAccessReceipt<EditAccessLevel>,+ viewer: &Viewer,+ batch: OpBatch,+ ) -> Result<(Vec<OpResult>, Option<TableVersion>), WorkflowError> {+ let applied = self+ .pipelines+ .apply_ops(receipt, viewer.acting_bot, batch)+ .await?;+ let version = applied+ .results+ .iter()+ .filter_map(OpResult::table_version)+ .next_back();+ Ok((applied.results, version))+ }+}++impl<Pipelines, Crm, Access> PipelineWorkflowService+ for PipelineWorkflowServiceImpl<Pipelines, Crm, Access>+where+ Pipelines: PipelineService,+ Crm: CrmService,+ Access: EntityAccessService,+{+ #[tracing::instrument(skip_all, err)]+ async fn pipelines(&self, viewer: &Viewer) -> Result<Vec<PipelineOverview>, WorkflowError> {+ let team = self.team(viewer).await?.ok_or(WorkflowError::NoTeam)?;+ let mut overviews = Vec::new();+ for pipeline in self.pipelines.list(team).await? {+ let receipt = self+ .receipt::<ViewAccessLevel>(viewer, pipeline.pipeline.id)+ .await?;+ let table = self.pipelines.table(receipt).await?;+ overviews.push(PipelineOverview::new(pipeline, table));+ }+ Ok(overviews)+ }++ #[tracing::instrument(skip_all, fields(pipeline = %pipeline), err)]+ async fn find(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ query: EntryQuery,+ ) -> Result<FoundEntries, WorkflowError> {+ let receipt = self.receipt::<ViewAccessLevel>(viewer, pipeline).await?;+ let overview = self.overview(&receipt).await?;+ let filters = query+ .filters+ .iter()+ .map(|(name, wanted)| {+ let field = overview.field(name)?;+ // A wrong label or person fails here, even when no entry exists.+ fields::matches(field, None, wanted, &viewer.user_id)+ .map_err(WorkflowError::Invalid)?;+ Ok((field, wanted))+ })+ .collect::<Result<Vec<_>, WorkflowError>>()?;+ let sort = query+ .sort+ .as_ref()+ .map(|(name, descending)| Ok::<_, WorkflowError>((overview.field(name)?, *descending)))+ .transpose()?;++ let (rows, complete) = self.scan(&receipt).await?;+ let record_field = overview.record_field();+ let wanted_records: HashSet<Uuid> = query.records.iter().copied().collect();+ let mut matched = Vec::new();+ for row in &rows {+ let tracked = record_id(row.cells.get(&record_field.id));+ if !wanted_records.is_empty() && !tracked.is_some_and(|id| wanted_records.contains(&id))+ {+ continue;+ }+ let mut keep = true;+ for (field, wanted) in &filters {+ if !fields::matches(field, row.cells.get(&field.id), wanted, &viewer.user_id)+ .map_err(WorkflowError::Invalid)?+ {+ keep = false;+ break;+ }+ }+ if keep {+ matched.push(row);+ }+ }++ let team = self.team(viewer).await?;+ let records = self+ .records(viewer, team.as_ref(), &overview, &matched)+ .await?;+ let mut entries: Vec<PipelineEntryView> = matched+ .into_iter()+ .map(|row| entry_view(&overview, row, &records))+ .filter(|entry| {+ query+ .search+ .as_deref()+ .is_none_or(|search| entry.record.matches(search))+ })+ .collect();+ let counts = option_counts(&overview, &entries);+ let totals = totals(&overview, &entries);+ if let Some((field, descending)) = sort {+ entries.sort_by(|left, right| {+ fields::compare(+ field,+ value_of(left, &field.name),+ value_of(right, &field.name),+ descending,+ )+ });+ }+ let matched = entries.len();+ entries.truncate(query.limit);+ Ok(FoundEntries {+ pipeline: overview,+ entries,+ matched,+ complete,+ counts,+ totals,+ })+ }++ #[tracing::instrument(skip_all, err)]+ async fn search_entries(+ &self,+ viewer: &Viewer,+ search: &str,+ limit: usize,+ ) -> Result<Vec<RecordEntries>, WorkflowError> {+ let mut found = Vec::new();+ for overview in self.pipelines(viewer).await? {+ let query = EntryQuery {+ search: Some(search.to_owned()),+ limit,+ ..Default::default()+ };+ let matches = self+ .find(viewer, overview.pipeline.pipeline.id, query)+ .await?;+ if !matches.entries.is_empty() {+ found.push(RecordEntries {+ pipeline: matches.pipeline.pipeline,+ entries: matches.entries,+ });+ }+ }+ Ok(found)+ }++ #[tracing::instrument(skip_all, err)]+ async fn record_entries(+ &self,+ viewer: &Viewer,+ records: &[Uuid],+ ) -> Result<Vec<RecordEntries>, WorkflowError> {+ let team = self.team(viewer).await?;+ let mut found: Vec<RecordEntries> = Vec::new();+ for record_type in [PipelineRecordType::Company, PipelineRecordType::Contact] {+ let entries = self+ .pipelines+ .entries(&viewer.user_id, record_type, records)+ .await?;+ let ids: Vec<Uuid> = entries.iter().map(|entry| entry.record_id).collect();+ let named = records::records(+ self.crm.as_ref(),+ team.as_ref(),+ viewer.user_id.as_ref(),+ record_type,+ &ids,+ )+ .await?;+ for entry in entries {+ let pipeline = entry.pipeline.pipeline.clone();+ let fields: Vec<PipelineField> = entry+ .columns+ .iter()+ .map(|column| PipelineField::new(column, &pipeline))+ .collect();+ let view = PipelineEntryView {+ entry_id: entry.row_id,+ record: named+ .get(&entry.record_id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(entry.record_id)),+ fields: field_values(&fields, &entry.cells),+ };+ match found+ .iter_mut()+ .find(|group| group.pipeline.pipeline.id == pipeline.id)+ {+ Some(group) => group.entries.push(view),+ None => found.push(RecordEntries {+ pipeline: entry.pipeline.as_ref().clone(),+ entries: vec![view],+ }),+ }+ }+ }+ Ok(found)+ }++ #[tracing::instrument(skip_all, fields(pipeline = %pipeline), err)]+ async fn add(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ additions: Vec<EntryAddition>,+ allow_duplicates: bool,+ ) -> Result<AddedEntries, WorkflowError> {+ if additions.is_empty() {+ return Err(WorkflowError::Invalid(+ "Name at least one company or contact to add.".into(),+ ));+ }+ let receipt = self.receipt::<EditAccessLevel>(viewer, pipeline).await?;+ let view = receipt.clone().try_into_requirement::<ViewAccessLevel>()?;+ let overview = self.overview(&view).await?;+ let record_type = overview.pipeline.pipeline.record_type;+ let team = self.team(viewer).await?;++ let mut resolved = Vec::with_capacity(additions.len());+ for addition in additions {+ let id = match &addition.record {+ RecordTarget::Id(id) => *id,+ RecordTarget::Email(email) => {+ let team = team.as_ref().ok_or(WorkflowError::NoTeam)?;+ let contact = self+ .crm+ .get_contact_by_email(team, email)+ .await?+ .ok_or_else(|| {+ WorkflowError::Invalid(format!(+ "No contact in the team's CRM has the email {email}."+ ))+ })?;+ match record_type {+ PipelineRecordType::Company => contact.company_id,+ PipelineRecordType::Contact => contact.id,+ }+ }+ };+ self.access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &viewer.user_id,+ None,+ &id.to_string(),+ match record_type {+ PipelineRecordType::Company => EntityType::CrmCompany,+ PipelineRecordType::Contact => EntityType::CrmContact,+ },+ )+ .await+ .map_err(|error| match error {+ AccessError::NotFound(_)+ | AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::BadRequest(_) => WorkflowError::Invalid(match record_type {+ PipelineRecordType::Company => format!(+ "{id} is not a CRM company the user can see. Find company ids with \+ ListCompanies, or add a company by one of its contacts' email."+ ),+ PipelineRecordType::Contact => format!(+ "{id} is not a CRM contact the user can see. Add a contact by its \+ email address."+ ),+ }),+ other => other.into(),+ })?;+ let cells = cells(&overview, &addition.set, viewer)?;+ resolved.push((id, cells));+ }++ let ids: Vec<Uuid> = resolved.iter().map(|(id, _)| *id).collect();+ let mut present: HashMap<Uuid, RowId> = HashMap::new();+ for reference in self.pipelines.record_rows(view.clone(), &ids).await? {+ present+ .entry(reference.record_id)+ .or_insert(reference.row_id);+ }+ let mut seen = HashSet::new();+ let mut already = Vec::new();+ let mut inserts = Vec::new();+ for (id, mut cells) in resolved {+ if !allow_duplicates {+ if !seen.insert(id) {+ continue;+ }+ if let Some(row) = present.get(&id) {+ already.push(*row);+ continue;+ }+ }+ cells.insert(+ 0,+ CellWrite {+ column: overview.record_field().id,+ value: CellValue::Entities(vec![EntityRef {+ entity_type: overview.record_kind(),+ entity_id: id.to_string(),+ }]),+ },+ );+ inserts.push(cells);+ }++ let (added, version) = if inserts.is_empty() {+ (Vec::new(), None)+ } else {+ let op = DatabaseOp::Rows {+ table: overview.pipeline.pipeline.table_id,+ change: RowsChange::Insert { rows: inserts },+ };+ let (results, version) = self.apply(receipt, viewer, OpBatch::from(vec![op])).await?;+ let added = results+ .into_iter()+ .flat_map(|result| match result {+ OpResult::Rows {+ change: RowsResult::Inserted { rows },+ ..+ } => rows,+ _ => Vec::new(),+ })+ .collect();+ (added, version)+ };+ let rows = self+ .pipelines+ .read_rows(view, &[added.as_slice(), already.as_slice()].concat())+ .await?;+ let references: Vec<&StorageRow> = rows.iter().collect();+ let records = self+ .records(viewer, team.as_ref(), &overview, &references)+ .await?;+ let views = |ids: &[RowId]| -> Vec<PipelineEntryView> {+ ids.iter()+ .filter_map(|id| rows.iter().find(|row| row.row_id == *id))+ .map(|row| entry_view(&overview, row, &records))+ .collect()+ };+ Ok(AddedEntries {+ added: views(&added),+ already_present: views(&already),+ version,+ })+ }++ #[tracing::instrument(skip_all, fields(pipeline = %pipeline), err)]+ async fn update(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ updates: Vec<EntryUpdate>,+ base_version: Option<TableVersion>,+ ) -> Result<UpdatedEntries, WorkflowError> {+ if updates.is_empty() {+ return Err(WorkflowError::Invalid(+ "Name at least one entry to update.".into(),+ ));+ }+ let receipt = self.receipt::<EditAccessLevel>(viewer, pipeline).await?;+ let view = receipt.clone().try_into_requirement::<ViewAccessLevel>()?;+ let overview = self.overview(&view).await?;+ let targets: Vec<EntryTarget> = updates.iter().map(|update| update.target).collect();+ let rows: Vec<RowId> = self+ .target_rows(&view, &overview, &targets, true)+ .await?+ .into_iter()+ .flatten()+ .collect();+ let mut changes = Vec::with_capacity(updates.len());+ let mut seen = HashSet::new();+ for (row, update) in rows.iter().zip(&updates) {+ if update.set.is_empty() {+ return Err(WorkflowError::Invalid(format!(+ "Name at least one field to set on entry {row}."+ )));+ }+ if !seen.insert(*row) {+ return Err(WorkflowError::Invalid(format!(+ "Entry {row} is named twice; give all of its changes in one update."+ )));+ }+ changes.push(RowChange {+ row: *row,+ cells: cells(&overview, &update.set, viewer)?,+ });+ }++ let before = self.pipelines.read_rows(view.clone(), &rows).await?;+ let table = overview.pipeline.pipeline.table_id;+ let batch = OpBatch {+ ops: vec![DatabaseOp::Rows {+ table,+ change: RowsChange::Update {+ changes: RowChanges::PerRow { rows: changes },+ },+ }],+ base_versions: base_version+ .map(|version| HashMap::from([(table, version)]))+ .unwrap_or_default(),+ };+ let (_, version) = self.apply(receipt, viewer, batch).await?;+ let after = self.pipelines.read_rows(view, &rows).await?;+ let team = self.team(viewer).await?;+ let references: Vec<&StorageRow> = after.iter().collect();+ let records = self+ .records(viewer, team.as_ref(), &overview, &references)+ .await?;+ let updated = rows+ .iter()+ .zip(&updates)+ .map(|(row, update)| {+ let cells_of = |rows: &[StorageRow]| {+ rows.iter()+ .find(|candidate| candidate.row_id == *row)+ .map(|found| found.cells.clone())+ .unwrap_or_default()+ };+ let (old, new) = (cells_of(&before), cells_of(&after));+ let record = record_id(new.get(&overview.record_field().id))+ .map(|id| {+ records+ .get(&id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(id))+ })+ .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()));+ let changes = update+ .set+ .iter()+ .filter_map(|(name, _)| overview.field(name).ok())+ .map(|field| FieldChange {+ field: field.name.clone(),+ before: old+ .get(&field.id)+ .and_then(|v| fields::field_value(field, v)),+ after: new+ .get(&field.id)+ .and_then(|v| fields::field_value(field, v)),+ })+ .collect();+ UpdatedEntry {+ entry_id: *row,+ record,+ changes,+ }+ })+ .collect();+ Ok(UpdatedEntries { updated, version })+ }++ #[tracing::instrument(skip_all, fields(pipeline = %pipeline), err)]+ async fn remove(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ targets: Vec<EntryTarget>,+ ) -> Result<RemovedEntries, WorkflowError> {+ if targets.is_empty() {+ return Err(WorkflowError::Invalid(+ "Name at least one entry to remove.".into(),+ ));+ }+ let receipt = self.receipt::<EditAccessLevel>(viewer, pipeline).await?;+ let view = receipt.clone().try_into_requirement::<ViewAccessLevel>()?;+ let overview = self.overview(&view).await?;+ let mut rows: Vec<RowId> = self+ .target_rows(&view, &overview, &targets, false)+ .await?+ .into_iter()+ .flatten()+ .collect();+ let mut seen = HashSet::new();+ rows.retain(|row| seen.insert(*row));+ let before = self.pipelines.read_rows(view, &rows).await?;+ let team = self.team(viewer).await?;+ let references: Vec<&StorageRow> = before.iter().collect();+ let records = self+ .records(viewer, team.as_ref(), &overview, &references)+ .await?;+ let op = DatabaseOp::Rows {+ table: overview.pipeline.pipeline.table_id,+ change: RowsChange::Delete { rows },+ };+ let (_, version) = self.apply(receipt, viewer, OpBatch::from(vec![op])).await?;+ Ok(RemovedEntries {+ removed: before+ .iter()+ .map(|row| entry_view(&overview, row, &records))+ .collect(),+ version,+ })+ }++ #[tracing::instrument(skip_all, err)]+ async fn create(+ &self,+ viewer: &Viewer,+ input: NewPipeline,+ ) -> Result<PipelineOverview, WorkflowError> {+ let team = self.team(viewer).await?.ok_or(WorkflowError::NoTeam)?;+ let created = self+ .pipelines+ .create(+ team,+ CreatePipeline {+ name: input.name,+ record_type: input.record_type,+ sharing: input.sharing,+ },+ )+ .await?;+ let id = created.pipeline.id;+ let view = self.receipt::<ViewAccessLevel>(viewer, id).await?;+ let overview = self.overview(&view).await?;+ if input.stages.is_empty() && input.fields.is_empty() {+ return Ok(overview);+ }+ let mut ops = Vec::new();+ if !input.stages.is_empty() {+ let stage = overview.field(STAGE_FIELD)?;+ ops.extend(stage.options.iter().map(|(option, _)| DatabaseOp::Column {+ table: overview.pipeline.pipeline.table_id,+ column: stage.id,+ change: ColumnChange::DeleteOption { option: *option },+ }));+ ops.push(add_options(&overview, stage, &input.stages));+ }+ for field in &input.fields {+ ops.push(add_field(&overview, field)?);+ }+ let receipt = self.receipt::<EditAccessLevel>(viewer, id).await?;+ self.apply(receipt, viewer, OpBatch::from(ops))+ .await+ .map_err(|error| {+ WorkflowError::Invalid(format!(+ "Created pipeline \"{}\" ({id}) with the default stages and fields, but \+ could not set its stages and fields: {error}. Change them with EditPipeline.",+ overview.pipeline.pipeline.name+ ))+ })?;+ self.overview(&view).await+ }++ #[tracing::instrument(skip_all, fields(pipeline = %pipeline), err)]+ async fn edit(+ &self,+ viewer: &Viewer,+ pipeline: Uuid,+ edit: PipelineEdit,+ ) -> Result<PipelineOverview, WorkflowError> {+ let receipt = self.receipt::<EditAccessLevel>(viewer, pipeline).await?;+ let view = receipt.clone().try_into_requirement::<ViewAccessLevel>()?;+ let overview = self.overview(&view).await?;+ let table = overview.pipeline.pipeline.table_id;+ let mut ops = Vec::new();+ for (from, to) in &edit.rename_fields {+ let field = overview.field(from)?;+ ops.push(DatabaseOp::Column {+ table,+ column: field.id,+ change: ColumnChange::Rename {+ name: to.trim().to_owned(),+ previous_name: Some(field.name.clone()),+ },+ });+ }+ for name in &edit.remove_fields {+ let field = overview.field(name)?;+ if field.is_record() {+ return Err(WorkflowError::Invalid(format!(+ "\"{}\" is the record each entry tracks and cannot be removed.",+ field.name+ )));+ }+ ops.push(DatabaseOp::Column {+ table,+ column: field.id,+ change: ColumnChange::Delete,+ });+ }+ for field in &edit.add_fields {+ ops.push(add_field(&overview, field)?);+ }+ for (name, labels) in &edit.add_options {+ let field = select_field(&overview, name)?;+ ops.push(add_options(&overview, field, labels));+ }+ for (name, from, to) in &edit.rename_options {+ let field = select_field(&overview, name)?;+ ops.push(DatabaseOp::Column {+ table,+ column: field.id,+ change: ColumnChange::UpdateOption {+ option: field.option(from).map_err(WorkflowError::Invalid)?,+ label: Some(to.trim().to_owned()),+ color: None,+ },+ });+ }+ for (name, label) in &edit.remove_options {+ let field = select_field(&overview, name)?;+ ops.push(DatabaseOp::Column {+ table,+ column: field.id,+ change: ColumnChange::DeleteOption {+ option: field.option(label).map_err(WorkflowError::Invalid)?,+ },+ });+ }+ if ops.is_empty() && edit.name.is_none() && edit.sharing.is_none() {+ return Err(WorkflowError::Invalid(+ "Nothing to change: give a new name, sharing, or field changes.".into(),+ ));+ }+ // Refuse a sharing change before writing anything else, so a refusal+ // never leaves the rest of the edit half-applied.+ let share = match edit.sharing {+ Some(sharing) => Some((+ self.receipt::<OwnerAccessLevel>(viewer, pipeline)+ .await+ .map_err(|_| {+ WorkflowError::Invalid(+ "Only the pipeline's owner can change who it is shared with; \+ nothing was changed."+ .into(),+ )+ })?,+ sharing,+ )),+ None => None,+ };+ if !ops.is_empty() {+ self.apply(receipt.clone(), viewer, OpBatch::from(ops))+ .await?;+ }+ if let Some(name) = edit.name {+ self.pipelines.rename(receipt, name).await?;+ }+ if let Some((owner, sharing)) = share {+ self.pipelines.share(owner, sharing).await?;+ }+ self.overview(&view).await+ }+}++impl<Pipelines, Crm, Access> PipelineWorkflowServiceImpl<Pipelines, Crm, Access>+where+ Pipelines: PipelineService,+{+ /// Every row of the pipeline up to [`MAX_SCANNED_ROWS`], and whether+ /// that was all of them.+ async fn scan(+ &self,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<(Vec<StorageRow>, bool), WorkflowError> {+ let mut rows = Vec::new();+ let mut after = None;+ loop {+ let page = self+ .pipelines+ .query_rows(+ receipt.clone(),+ StorageRowsQuery {+ after,+ ..Default::default()+ },+ )+ .await?;+ rows.extend(page.rows);+ match page.next {+ None => return Ok((rows, true)),+ Some(_) if rows.len() >= MAX_SCANNED_ROWS => {+ rows.truncate(MAX_SCANNED_ROWS);+ return Ok((rows, false));+ }+ Some(next) => after = Some(next),+ }+ }+ }+}diff --git a/crates/crm/src/domain/pipeline_workflows/entries.rs b/crates/crm/src/domain/pipeline_workflows/entries.rsnew file mode 100644index 0000000000..33eef7416a--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/entries.rs@@ -0,0 +1,130 @@+//! Entries as read back: the record each tracks, its fields by name, and the+//! counts and totals over a set of them.++use std::collections::{BTreeMap, HashMap};++use databases::domain::storage::StorageRow;+use models_databases::ColumnId;+use models_properties::service::property_value::PropertyValue;+use uuid::Uuid;++use super::{+ FieldKind, FieldValue, OptionCounts, PipelineEntryView, PipelineField, PipelineOverview,+ PipelineRecord, fields,+};++/// The record a primary cell references.+pub(super) fn record_id(cell: Option<&PropertyValue>) -> Option<Uuid> {+ match cell {+ Some(PropertyValue::EntityRef(references)) => references+ .first()+ .and_then(|reference| reference.entity_id.parse().ok()),+ _ => None,+ }+}++/// The filled-in fields of `cells`, other than the record, in column order.+pub(super) fn field_values(+ fields: &[PipelineField],+ cells: &HashMap<ColumnId, PropertyValue>,+) -> Vec<(String, FieldValue)> {+ fields+ .iter()+ .filter(|field| !field.is_record())+ .filter_map(|field| {+ let value = fields::field_value(field, cells.get(&field.id)?)?;+ Some((field.name.clone(), value))+ })+ .collect()+}++pub(super) fn entry_view(+ overview: &PipelineOverview,+ row: &StorageRow,+ records: &HashMap<Uuid, PipelineRecord>,+) -> PipelineEntryView {+ let record = record_id(row.cells.get(&overview.record_field().id))+ .map(|id| {+ records+ .get(&id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(id))+ })+ .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()));+ PipelineEntryView {+ entry_id: row.row_id,+ record,+ fields: field_values(&overview.fields, &row.cells),+ }+}++pub(super) fn value_of<'a>(entry: &'a PipelineEntryView, field: &str) -> Option<&'a FieldValue> {+ entry+ .fields+ .iter()+ .find(|(name, _)| name == field)+ .map(|(_, value)| value)+}++/// Matched entries per option of every single-select field.+pub(super) fn option_counts(+ overview: &PipelineOverview,+ entries: &[PipelineEntryView],+) -> Vec<OptionCounts> {+ overview+ .fields+ .iter()+ .filter(|field| field.kind == FieldKind::Select && !field.multiple)+ .map(|field| {+ let mut counts: BTreeMap<usize, usize> = BTreeMap::new();+ let mut empty = 0;+ for entry in entries {+ match value_of(entry, &field.name) {+ Some(FieldValue::Labels(labels)) => {+ if let Some(position) = labels+ .first()+ .and_then(|label| field.options.iter().position(|(_, l)| l == label))+ {+ *counts.entry(position).or_default() += 1;+ }+ }+ _ => empty += 1,+ }+ }+ OptionCounts {+ field: field.name.clone(),+ counts: field+ .options+ .iter()+ .enumerate()+ .map(|(position, (_, label))| {+ (label.clone(), counts.get(&position).copied().unwrap_or(0))+ })+ .collect(),+ empty,+ }+ })+ .collect()+}++/// The sum of every number field over `entries`.+pub(super) fn totals(+ overview: &PipelineOverview,+ entries: &[PipelineEntryView],+) -> Vec<(String, f64)> {+ overview+ .fields+ .iter()+ .filter(|field| field.kind == FieldKind::Number)+ .map(|field| {+ let sum = entries+ .iter()+ .filter_map(|entry| match value_of(entry, &field.name) {+ Some(FieldValue::Number(number)) => Some(*number),+ _ => None,+ })+ .sum();+ (field.name.clone(), sum)+ })+ .collect()+}diff --git a/crates/crm/src/domain/pipeline_workflows/fields.rs b/crates/crm/src/domain/pipeline_workflows/fields.rsnew file mode 100644index 0000000000..9303612b01--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/fields.rs@@ -0,0 +1,506 @@+//! A pipeline's columns as people name them, and their values as text: what+//! a written value becomes in a cell, and what a stored cell reads as.++#[cfg(test)]+mod test;++use std::cmp::Ordering;++use chrono::{DateTime, NaiveDate, Utc};+use databases::domain::{+ catalog,+ models::{ColumnDetail, ColumnId},+};+use macro_user_id::user_id::MacroUserIdStr;+use models_databases::{CellValue, ColumnKind, EntityKind, EntityRef, OptionId, OptionRef};+use models_properties::{DataType, service::property_value::PropertyValue};++use super::super::pipelines::{Pipeline, PipelineRecordType};++/// What a field holds.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FieldKind {+ /// The company or contact the entry tracks.+ Record(PipelineRecordType),+ /// Free text.+ Text,+ /// A number.+ Number,+ /// True or false.+ Checkbox,+ /// A date-time.+ Date,+ /// URLs.+ Link,+ /// Labels from the field's options, such as a stage.+ Select,+ /// Colored tags.+ Tags,+ /// Macro users.+ Person,+ /// Other Macro items, by id.+ Entity(EntityKind),+ /// Rows of another table; pipelines write these only through the app.+ Relation,+ /// Computed from the entry's other fields; nothing writes it.+ Formula,+}++/// One column of a pipeline, named as the user sees it.+#[derive(Debug, Clone, PartialEq)]+pub struct PipelineField {+ /// The column.+ pub id: ColumnId,+ /// Its display name.+ pub name: String,+ /// What it holds.+ pub kind: FieldKind,+ /// Whether a cell holds several values.+ pub multiple: bool,+ /// A select or tag field's options in their order, with their labels.+ pub options: Vec<(OptionId, String)>,+ /// Whether every entry must have a value.+ pub required: bool,+ /// Whether the viewer may write it.+ pub writable: bool,+}++impl PipelineField {+ /// The field `column` of `pipeline`.+ pub(crate) fn new(column: &ColumnDetail, pipeline: &Pipeline) -> Self {+ let kind = if column.column.id == pipeline.primary_column_id {+ FieldKind::Record(pipeline.record_type)+ } else if column.column.formula().is_some() {+ FieldKind::Formula+ } else if column.column.is_relation() {+ FieldKind::Relation+ } else {+ match column.definition.definition.data_type {+ DataType::String => FieldKind::Text,+ DataType::Number => FieldKind::Number,+ DataType::Boolean => FieldKind::Checkbox,+ DataType::Date => FieldKind::Date,+ DataType::Link => FieldKind::Link,+ DataType::SelectString | DataType::SelectNumber => FieldKind::Select,+ DataType::Tag => FieldKind::Tags,+ DataType::Entity => match column.entity_type().and_then(catalog::entity_kind) {+ Some(EntityKind::User) => FieldKind::Person,+ Some(kind) => FieldKind::Entity(kind),+ None => FieldKind::Relation,+ },+ }+ };+ Self {+ id: column.column.id,+ name: column.name().to_owned(),+ kind,+ multiple: column.is_multi_valued(),+ options: catalog::option_labels(&column.definition),+ required: !column.column.nullable,+ writable: column.writable && kind != FieldKind::Formula,+ }+ }++ /// Whether this is the field naming the entry's company or contact.+ pub fn is_record(&self) -> bool {+ matches!(self.kind, FieldKind::Record(_))+ }++ /// The option labelled `label`, ignoring case.+ pub(crate) fn option(&self, label: &str) -> Result<OptionId, String> {+ let label = label.trim();+ self.options+ .iter()+ .find(|(_, candidate)| candidate.eq_ignore_ascii_case(label))+ .map(|(id, _)| *id)+ .ok_or_else(|| {+ let labels: Vec<&str> = self.options.iter().map(|(_, l)| l.as_str()).collect();+ format!(+ "\"{}\" has no option \"{label}\". Its options are: {}. Add one by editing \+ the pipeline.",+ self.name,+ labels.join(", ")+ )+ })+ }++ /// The label of option `id`, or the id when the option is gone.+ fn label(&self, id: OptionId) -> String {+ self.options+ .iter()+ .find(|(candidate, _)| *candidate == id)+ .map_or_else(|| id.to_string(), |(_, label)| label.clone())+ }++ /// Where option `label` sits in the field's order; unknown labels last.+ fn position(&self, label: &str) -> usize {+ self.options+ .iter()+ .position(|(_, candidate)| candidate == label)+ .unwrap_or(usize::MAX)+ }+}++/// A value for a field, as text: the field's type says how it is read.+#[derive(Debug, Clone, PartialEq)]+pub enum FieldInput {+ /// No value: write an empty cell, or match one.+ Clear,+ /// One value.+ One(String),+ /// Several values, for a field holding several.+ Many(Vec<String>),+}++impl FieldInput {+ fn values(&self) -> Vec<&str> {+ match self {+ FieldInput::Clear => Vec::new(),+ FieldInput::One(value) => vec![value.as_str()],+ FieldInput::Many(values) => values.iter().map(String::as_str).collect(),+ }+ }+}++/// A stored value, read back in the field's own terms.+#[derive(Debug, Clone, PartialEq)]+pub enum FieldValue {+ /// Free text.+ Text(String),+ /// A number.+ Number(f64),+ /// True or false.+ Checkbox(bool),+ /// A date-time.+ Date(DateTime<Utc>),+ /// Option labels, in the cell's order.+ Labels(Vec<String>),+ /// URLs.+ Links(Vec<String>),+ /// Macro ids: users, records or other items.+ References(Vec<String>),+}++/// The cell `input` writes into `field`, for `viewer` ("me").+pub(crate) fn cell_value(+ field: &PipelineField,+ input: &FieldInput,+ viewer: &MacroUserIdStr<'_>,+) -> Result<CellValue, String> {+ let name = &field.name;+ match field.kind {+ FieldKind::Record(_) => {+ return Err(format!(+ "\"{name}\" is the record the entry tracks. To track another record, remove \+ this entry and add that record."+ ));+ }+ FieldKind::Formula => return Err(format!("\"{name}\" is computed; nothing writes it.")),+ FieldKind::Relation => {+ return Err(format!(+ "\"{name}\" links rows of another table; change it in the app."+ ));+ }+ _ => {}+ }+ if !field.writable {+ return Err(format!("The user cannot change \"{name}\"."));+ }+ let values = input.values();+ let Some(first) = values.first().copied() else {+ return Ok(CellValue::Clear);+ };+ if values.len() > 1 && !field.multiple {+ return Err(format!("\"{name}\" holds one value; give exactly one."));+ }+ Ok(match field.kind {+ FieldKind::Text => CellValue::Text(first.to_owned()),+ FieldKind::Number => CellValue::Number(number(name, first)?),+ FieldKind::Checkbox => CellValue::Boolean(checkbox(name, first)?),+ FieldKind::Date => CellValue::Date(date(name, first)?),+ FieldKind::Link => CellValue::Link(values.iter().map(|v| v.trim().to_owned()).collect()),+ FieldKind::Select | FieldKind::Tags => CellValue::Options(+ values+ .iter()+ .map(|label| field.option(label).map(OptionRef::Id))+ .collect::<Result<_, _>>()?,+ ),+ FieldKind::Person => CellValue::Entities(+ values+ .iter()+ .map(|value| {+ person(name, value, viewer).map(|id| EntityRef {+ entity_type: EntityKind::User,+ entity_id: id,+ })+ })+ .collect::<Result<_, _>>()?,+ ),+ FieldKind::Entity(kind) => CellValue::Entities(+ values+ .iter()+ .map(|id| EntityRef {+ entity_type: kind,+ entity_id: id.trim().to_owned(),+ })+ .collect(),+ ),+ FieldKind::Record(_) | FieldKind::Relation | FieldKind::Formula => {+ unreachable!("refused above")+ }+ })+}++/// What a stored cell reads as; `None` for an empty one.+pub(crate) fn field_value(field: &PipelineField, value: &PropertyValue) -> Option<FieldValue> {+ match value {+ PropertyValue::Bool(checked) => Some(FieldValue::Checkbox(*checked)),+ PropertyValue::Num(number) => Some(FieldValue::Number(*number)),+ PropertyValue::Str(text) => Some(FieldValue::Text(text.clone())),+ PropertyValue::Date(date) => Some(FieldValue::Date(*date)),+ PropertyValue::SelectOption(ids) if !ids.is_empty() => Some(FieldValue::Labels(+ ids.iter()+ .map(|id| field.label(OptionId::from_uuid(*id)))+ .collect(),+ )),+ PropertyValue::EntityRef(references) if !references.is_empty() => {+ Some(FieldValue::References(+ references+ .iter()+ .map(|reference| reference.entity_id.clone())+ .collect(),+ ))+ }+ PropertyValue::Link(urls) if !urls.is_empty() => Some(FieldValue::Links(urls.clone())),+ PropertyValue::SelectOption(_) | PropertyValue::EntityRef(_) | PropertyValue::Link(_) => {+ None+ }+ }+}++/// Whether `cell` holds `wanted`, or any of several wanted values.+///+/// Text and links match a case-insensitive substring; dates match the+/// calendar day; everything else matches exactly.+pub(crate) fn matches(+ field: &PipelineField,+ cell: Option<&PropertyValue>,+ wanted: &FieldInput,+ viewer: &MacroUserIdStr<'_>,+) -> Result<bool, String> {+ let name = &field.name;+ if matches!(field.kind, FieldKind::Formula | FieldKind::Relation) {+ return Err(format!("Entries cannot be filtered by \"{name}\"."));+ }+ let value = cell.and_then(|cell| field_value(field, cell));+ let wanted = wanted.values();+ if wanted.is_empty() {+ return Ok(value.is_none());+ }+ for candidate in wanted {+ let hit = match field.kind {+ FieldKind::Select | FieldKind::Tags => {+ let label = field.label(field.option(candidate)?);+ matches!(&value, Some(FieldValue::Labels(labels)) if labels.contains(&label))+ }+ FieldKind::Person => {+ let id = person(name, candidate, viewer)?;+ references(&value).any(|reference| reference.eq_ignore_ascii_case(&id))+ }+ FieldKind::Record(_) | FieldKind::Entity(_) => {+ references(&value).any(|reference| reference == candidate.trim())+ }+ FieldKind::Text => {+ matches!(&value, Some(FieldValue::Text(text)) if contains(text, candidate))+ }+ FieldKind::Link => {+ matches!(&value, Some(FieldValue::Links(urls)) if urls.iter().any(|url| contains(url, candidate)))+ }+ FieldKind::Number => {+ let wanted = number(name, candidate)?;+ matches!(value, Some(FieldValue::Number(n)) if (n - wanted).abs() < f64::EPSILON)+ }+ FieldKind::Checkbox => {+ let wanted = checkbox(name, candidate)?;+ matches!(value, Some(FieldValue::Checkbox(true))) == wanted+ }+ FieldKind::Date => {+ let wanted = date(name, candidate)?.date_naive();+ matches!(value, Some(FieldValue::Date(d)) if d.date_naive() == wanted)+ }+ FieldKind::Formula | FieldKind::Relation => unreachable!("refused above"),+ };+ if hit {+ return Ok(true);+ }+ }+ Ok(false)+}++/// How two stored values of `field` order: options in the field's order,+/// numbers and dates by value, text ignoring case. Empty cells sort last.+pub(crate) fn compare(+ field: &PipelineField,+ left: Option<&FieldValue>,+ right: Option<&FieldValue>,+ descending: bool,+) -> Ordering {+ let (left, right) = match (left, right) {+ (None, None) => return Ordering::Equal,+ (None, Some(_)) => return Ordering::Greater,+ (Some(_), None) => return Ordering::Less,+ (Some(left), Some(right)) => (left, right),+ };+ let order = match (left, right) {+ (FieldValue::Number(left), FieldValue::Number(right)) => left.total_cmp(right),+ (FieldValue::Date(left), FieldValue::Date(right)) => left.cmp(right),+ (FieldValue::Checkbox(left), FieldValue::Checkbox(right)) => left.cmp(right),+ (FieldValue::Labels(left), FieldValue::Labels(right)) => {+ let first =+ |labels: &[String]| labels.first().map_or(usize::MAX, |l| field.position(l));+ first(left).cmp(&first(right))+ }+ _ => text(left).to_lowercase().cmp(&text(right).to_lowercase()),+ };+ if descending { order.reverse() } else { order }+}++/// A stored value as one line of text.+pub(crate) fn text(value: &FieldValue) -> String {+ match value {+ FieldValue::Text(text) => text.clone(),+ FieldValue::Number(number) => number.to_string(),+ FieldValue::Checkbox(checked) => checked.to_string(),+ FieldValue::Date(date) => date.to_rfc3339(),+ FieldValue::Labels(values) | FieldValue::Links(values) | FieldValue::References(values) => {+ values.join(", ")+ }+ }+}++/// The type of a field to add.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NewFieldKind {+ /// Free text.+ Text,+ /// A number.+ Number,+ /// True or false.+ Checkbox,+ /// A date.+ Date,+ /// A URL.+ Link,+ /// One label from a list, such as a stage or priority.+ Select,+ /// Several labels from a list.+ MultiSelect,+ /// One Macro user.+ Person,+ /// Several Macro users.+ People,+}++impl NewFieldKind {+ /// The column type it adds.+ pub(crate) fn column_kind(self) -> ColumnKind {+ match self {+ NewFieldKind::Text => ColumnKind::Text,+ NewFieldKind::Number => ColumnKind::Number,+ NewFieldKind::Checkbox => ColumnKind::Boolean,+ NewFieldKind::Date => ColumnKind::Date,+ NewFieldKind::Link => ColumnKind::Link,+ NewFieldKind::Select => ColumnKind::Select { multi: false },+ NewFieldKind::MultiSelect => ColumnKind::Select { multi: true },+ NewFieldKind::Person => ColumnKind::Entity {+ target: EntityKind::User,+ multi: false,+ },+ NewFieldKind::People => ColumnKind::Entity {+ target: EntityKind::User,+ multi: true,+ },+ }+ }++ /// Whether the field takes options.+ pub(crate) fn takes_options(self) -> bool {+ matches!(self, NewFieldKind::Select | NewFieldKind::MultiSelect)+ }+}++fn references(value: &Option<FieldValue>) -> impl Iterator<Item = &String> {+ match value {+ Some(FieldValue::References(ids)) => ids.iter(),+ _ => [].iter(),+ }+}++fn contains(haystack: &str, needle: &str) -> bool {+ haystack+ .to_lowercase()+ .contains(&needle.trim().to_lowercase())+}++fn number(field: &str, value: &str) -> Result<f64, String> {+ let cleaned: String = value+ .trim()+ .trim_start_matches(['$', '€', '£'])+ .chars()+ .filter(|c| *c != ',' && !c.is_whitespace())+ .collect();+ cleaned+ .parse::<f64>()+ .ok()+ .filter(|number| number.is_finite())+ .ok_or_else(|| format!("\"{field}\" takes a number, not \"{value}\"."))+}++fn checkbox(field: &str, value: &str) -> Result<bool, String> {+ match value.trim().to_lowercase().as_str() {+ "true" | "yes" | "checked" => Ok(true),+ "false" | "no" | "unchecked" => Ok(false),+ _ => Err(format!("\"{field}\" takes true or false, not \"{value}\".")),+ }+}++fn date(field: &str, value: &str) -> Result<DateTime<Utc>, String> {+ let value = value.trim();+ DateTime::parse_from_rfc3339(value)+ .map(|date| date.with_timezone(&Utc))+ .or_else(|_| {+ NaiveDate::parse_from_str(value, "%Y-%m-%d").map(|date| {+ date.and_hms_opt(0, 0, 0)+ .expect("midnight exists")+ .and_utc()+ })+ })+ .map_err(|_| {+ format!(+ "\"{field}\" takes a date like 2026-10-12 or an ISO date-time, not \"{value}\"."+ )+ })+}++/// A person's Macro user id: `me`, an email address, or the id itself.+fn person(field: &str, value: &str, viewer: &MacroUserIdStr<'_>) -> Result<String, String> {+ let value = value.trim();+ if value.eq_ignore_ascii_case("me") {+ return Ok(viewer.as_ref().to_owned());+ }+ let id = if value.to_lowercase().starts_with("macro|") {+ value.to_lowercase()+ } else if value.contains('@') {+ format!("macro|{}", value.to_lowercase())+ } else {+ String::new()+ };+ MacroUserIdStr::parse_from_str(&id)+ .map(|_| id.clone())+ .map_err(|_| {+ format!(+ "\"{field}\" takes a person: \"me\", an email address, or a Macro user id like \+ macro|[email protected], not \"{value}\"."+ )+ })+}diff --git a/crates/crm/src/domain/pipeline_workflows/fields/test.rs b/crates/crm/src/domain/pipeline_workflows/fields/test.rsnew file mode 100644index 0000000000..87c36fc4e2--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/fields/test.rs@@ -0,0 +1,199 @@+use super::*;+use macro_user_id::cowlike::CowLike;+use models_properties::{EntityType, shared::entity_reference::EntityReference};++fn viewer() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned()+}++fn field(kind: FieldKind) -> PipelineField {+ PipelineField {+ id: ColumnId::new(),+ name: "Field".into(),+ kind,+ multiple: false,+ options: Vec::new(),+ required: false,+ writable: true,+ }+}++fn stage() -> (PipelineField, OptionId, OptionId) {+ let (lead, won) = (OptionId::new(), OptionId::new());+ let field = PipelineField {+ name: "Stage".into(),+ options: vec![(lead, "Lead".into()), (won, "Won".into())],+ ..field(FieldKind::Select)+ };+ (field, lead, won)+}++fn one(value: &str) -> FieldInput {+ FieldInput::One(value.into())+}++#[test]+fn stage_labels_resolve_to_options_ignoring_case() {+ let (stage, _, won) = stage();+ assert_eq!(+ cell_value(&stage, &one("won"), &viewer()),+ Ok(CellValue::Options(vec![OptionRef::Id(won)]))+ );+ let error = cell_value(&stage, &one("Closed"), &viewer()).unwrap_err();+ assert!(error.contains("Lead, Won"), "{error}");+}++#[test]+fn a_single_valued_field_refuses_several_values() {+ let (stage, _, _) = stage();+ let several = FieldInput::Many(vec!["Lead".into(), "Won".into()]);+ assert!(cell_value(&stage, &several, &viewer()).is_err());+ let tags = PipelineField {+ multiple: true,+ ..stage+ };+ assert!(matches!(+ cell_value(&tags, &several, &viewer()),+ Ok(CellValue::Options(options)) if options.len() == 2+ ));+}++#[test]+fn people_are_me_an_email_or_a_user_id() {+ let owner = field(FieldKind::Person);+ for (input, id) in [+ ("me", "macro|[email protected]"),+ ("[email protected]", "macro|[email protected]"),+ ("macro|[email protected]", "macro|[email protected]"),+ ] {+ assert_eq!(+ cell_value(&owner, &one(input), &viewer()),+ Ok(CellValue::Entities(vec![EntityRef {+ entity_type: EntityKind::User,+ entity_id: id.into(),+ }]))+ );+ }+ assert!(cell_value(&owner, &one("Sam"), &viewer()).is_err());+}++#[test]+fn numbers_dates_and_checkboxes_parse_from_text() {+ assert_eq!(+ cell_value(&field(FieldKind::Number), &one("$48,000.50"), &viewer()),+ Ok(CellValue::Number(48_000.5))+ );+ assert!(cell_value(&field(FieldKind::Number), &one("lots"), &viewer()).is_err());+ assert_eq!(+ cell_value(&field(FieldKind::Date), &one("2026-10-12"), &viewer()),+ Ok(CellValue::Date(+ DateTime::parse_from_rfc3339("2026-10-12T00:00:00Z")+ .unwrap()+ .with_timezone(&Utc)+ ))+ );+ assert_eq!(+ cell_value(&field(FieldKind::Checkbox), &one("Yes"), &viewer()),+ Ok(CellValue::Boolean(true))+ );+}++#[test]+fn clearing_empties_the_cell_but_record_and_computed_fields_refuse_writes() {+ assert_eq!(+ cell_value(&field(FieldKind::Text), &FieldInput::Clear, &viewer()),+ Ok(CellValue::Clear)+ );+ for kind in [+ FieldKind::Record(PipelineRecordType::Company),+ FieldKind::Formula,+ FieldKind::Relation,+ ] {+ assert!(cell_value(&field(kind), &one("x"), &viewer()).is_err());+ }+ let read_only = PipelineField {+ writable: false,+ ..field(FieldKind::Text)+ };+ assert!(cell_value(&read_only, &one("x"), &viewer()).is_err());+}++#[test]+fn stored_cells_read_back_as_labels_and_ids() {+ let (stage, lead, _) = stage();+ assert_eq!(+ field_value(&stage, &PropertyValue::SelectOption(vec![lead.into_uuid()])),+ Some(FieldValue::Labels(vec!["Lead".into()]))+ );+ assert_eq!(+ field_value(&stage, &PropertyValue::SelectOption(Vec::new())),+ None+ );+ let owner = PropertyValue::EntityRef(vec![EntityReference::new(+ "macro|[email protected]",+ EntityType::User,+ )]);+ assert_eq!(+ field_value(&field(FieldKind::Person), &owner),+ Some(FieldValue::References(vec!["macro|[email protected]".into()]))+ );+}++#[test]+fn filters_match_any_wanted_value_and_empty_cells() {+ let (stage, lead, _) = stage();+ let cell = PropertyValue::SelectOption(vec![lead.into_uuid()]);+ let either = FieldInput::Many(vec!["won".into(), "lead".into()]);+ assert_eq!(matches(&stage, Some(&cell), &either, &viewer()), Ok(true));+ assert_eq!(+ matches(&stage, Some(&cell), &one("Won"), &viewer()),+ Ok(false)+ );+ assert_eq!(+ matches(&stage, None, &FieldInput::Clear, &viewer()),+ Ok(true)+ );+ assert!(matches(&stage, None, &one("Closed"), &viewer()).is_err());++ let owner = PropertyValue::EntityRef(vec![EntityReference::new(+ "macro|[email protected]",+ EntityType::User,+ )]);+ assert_eq!(+ matches(+ &field(FieldKind::Person),+ Some(&owner),+ &one("me"),+ &viewer()+ ),+ Ok(true)+ );+ let notes = PropertyValue::Str("Call back next week".into());+ assert_eq!(+ matches(+ &field(FieldKind::Text),+ Some(¬es),+ &one("NEXT week"),+ &viewer()+ ),+ Ok(true)+ );+}++#[test]+fn stages_sort_in_pipeline_order_with_empty_cells_last() {+ let (stage, _, _) = stage();+ let lead = FieldValue::Labels(vec!["Lead".into()]);+ let won = FieldValue::Labels(vec!["Won".into()]);+ assert_eq!(+ compare(&stage, Some(&lead), Some(&won), false),+ Ordering::Less+ );+ assert_eq!(+ compare(&stage, Some(&lead), Some(&won), true),+ Ordering::Greater+ );+ assert_eq!(compare(&stage, None, Some(&lead), true), Ordering::Greater);+}diff --git a/crates/crm/src/domain/pipeline_workflows/models.rs b/crates/crm/src/domain/pipeline_workflows/models.rsnew file mode 100644index 0000000000..6651e7dd78--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/models.rs@@ -0,0 +1,289 @@+//! What the pipeline workflows take and return.++use databases::domain::models::{RowId, TableDetail, TableVersion};+use entity_access::domain::models::AccessError;+use models_databases::EntityKind;+use uuid::Uuid;++use super::super::{+ model::CrmError,+ pipelines::{AccessiblePipeline, PipelineError, PipelineRecordType, PipelineSharing},+};+use super::{FieldInput, FieldValue, NewFieldKind, PipelineField, PipelineRecord};++/// Most rows a read scans; a larger pipeline is reported as incomplete.+pub const MAX_SCANNED_ROWS: usize = 5_000;++/// A pipeline with its fields in column order.+#[derive(Debug, Clone)]+pub struct PipelineOverview {+ /// The pipeline and the viewer's grant on it.+ pub pipeline: AccessiblePipeline,+ /// Its fields, the record field first.+ pub fields: Vec<PipelineField>,+ /// Its table's version when it was read.+ pub version: TableVersion,+}++impl PipelineOverview {+ pub(super) fn new(pipeline: AccessiblePipeline, table: TableDetail) -> Self {+ Self {+ fields: table+ .columns+ .iter()+ .map(|column| PipelineField::new(column, &pipeline.pipeline))+ .collect(),+ version: table.table.version,+ pipeline,+ }+ }++ /// The field named `name`, ignoring case.+ pub fn field(&self, name: &str) -> Result<&PipelineField, WorkflowError> {+ let name = name.trim();+ self.fields+ .iter()+ .find(|field| field.name.eq_ignore_ascii_case(name))+ .ok_or_else(|| {+ let names: Vec<&str> = self.fields.iter().map(|f| f.name.as_str()).collect();+ WorkflowError::Invalid(format!(+ "Pipeline \"{}\" has no field \"{name}\". Its fields are: {}.",+ self.pipeline.pipeline.name,+ names.join(", ")+ ))+ })+ }++ pub(super) fn record_field(&self) -> &PipelineField {+ self.fields+ .iter()+ .find(|field| field.is_record())+ .expect("a pipeline's table has its record column")+ }++ pub(super) fn record_kind(&self) -> EntityKind {+ match self.pipeline.pipeline.record_type {+ PipelineRecordType::Company => EntityKind::Company,+ PipelineRecordType::Contact => EntityKind::Contact,+ }+ }+}++/// One entry: the record it tracks and its filled-in fields.+#[derive(Debug, Clone, PartialEq)]+pub struct PipelineEntryView {+ /// The entry, a row of the pipeline.+ pub entry_id: RowId,+ /// The company or contact it tracks.+ pub record: PipelineRecord,+ /// Its other fields that hold a value, in column order.+ pub fields: Vec<(String, FieldValue)>,+}++/// Which entries to read, and how to order them.+#[derive(Debug, Clone, Default)]+pub struct EntryQuery {+ /// Field name and the value (or any of several values) it must hold.+ pub filters: Vec<(String, FieldInput)>,+ /// Only entries tracking one of these records.+ pub records: Vec<Uuid>,+ /// Text the record's name, domain or email must contain.+ pub search: Option<String>,+ /// The field to order by, and whether to put the largest first.+ pub sort: Option<(String, bool)>,+ /// Most entries to return.+ pub limit: usize,+}++/// How many matched entries hold each option of a single-select field.+#[derive(Debug, Clone, PartialEq)]+pub struct OptionCounts {+ /// The field.+ pub field: String,+ /// Each option in the field's order, with its count.+ pub counts: Vec<(String, usize)>,+ /// Entries with no option.+ pub empty: usize,+}++/// The entries a query matched.+#[derive(Debug, Clone)]+pub struct FoundEntries {+ /// The pipeline read.+ pub pipeline: PipelineOverview,+ /// The first `limit` matches, in the requested order.+ pub entries: Vec<PipelineEntryView>,+ /// How many entries matched in all.+ pub matched: usize,+ /// Whether every entry was read; a pipeline beyond [`MAX_SCANNED_ROWS`]+ /// is not, so counts and totals cover only the rows read.+ pub complete: bool,+ /// Matched entries per option of each single-select field.+ pub counts: Vec<OptionCounts>,+ /// Sum of each number field over the matched entries.+ pub totals: Vec<(String, f64)>,+}++/// A record's entries in one pipeline.+#[derive(Debug, Clone)]+pub struct RecordEntries {+ /// The pipeline.+ pub pipeline: AccessiblePipeline,+ /// The entries tracking the records asked about.+ pub entries: Vec<PipelineEntryView>,+}++/// A company or contact to add, by id or by a contact's email address.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum RecordTarget {+ /// A CRM company or contact id.+ Id(Uuid),+ /// A contact's email: that contact, or in a company pipeline its company.+ Email(String),+}++/// One entry to add.+#[derive(Debug, Clone)]+pub struct EntryAddition {+ /// The record it tracks.+ pub record: RecordTarget,+ /// Fields to fill in, by name.+ pub set: Vec<(String, FieldInput)>,+}++/// Entries to change: one by its id, or every entry tracking a record.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum EntryTarget {+ /// One entry.+ Entry(RowId),+ /// The entries tracking this company or contact.+ Record(Uuid),+}++/// Fields to change on one entry.+#[derive(Debug, Clone)]+pub struct EntryUpdate {+ /// The entry; a record must have exactly one entry in the pipeline.+ pub target: EntryTarget,+ /// Fields to set, by name.+ pub set: Vec<(String, FieldInput)>,+}++/// Entries added, and requested records already in the pipeline.+#[derive(Debug, Clone)]+pub struct AddedEntries {+ /// The new entries.+ pub added: Vec<PipelineEntryView>,+ /// Existing entries of records that were not added again.+ pub already_present: Vec<PipelineEntryView>,+ /// The table's version after the write.+ pub version: Option<TableVersion>,+}++/// One field's value before and after an update.+#[derive(Debug, Clone, PartialEq)]+pub struct FieldChange {+ /// The field.+ pub field: String,+ /// Its value before.+ pub before: Option<FieldValue>,+ /// Its value after.+ pub after: Option<FieldValue>,+}++/// An updated entry.+#[derive(Debug, Clone)]+pub struct UpdatedEntry {+ /// The entry.+ pub entry_id: RowId,+ /// The record it tracks.+ pub record: PipelineRecord,+ /// The fields set, as they were and are.+ pub changes: Vec<FieldChange>,+}++/// The entries an update wrote.+#[derive(Debug, Clone)]+pub struct UpdatedEntries {+ /// Each entry, in request order.+ pub updated: Vec<UpdatedEntry>,+ /// The table's version after the write.+ pub version: Option<TableVersion>,+}++/// The entries a removal deleted.+#[derive(Debug, Clone)]+pub struct RemovedEntries {+ /// Each entry as it was.+ pub removed: Vec<PipelineEntryView>,+ /// The table's version after the write.+ pub version: Option<TableVersion>,+}++/// A field to add to a pipeline.+#[derive(Debug, Clone)]+pub struct NewField {+ /// Its name, unique in the pipeline ignoring case.+ pub name: String,+ /// Its type.+ pub kind: NewFieldKind,+ /// A select field's options, in order.+ pub options: Vec<String>,+}++/// A pipeline to create.+#[derive(Debug, Clone)]+pub struct NewPipeline {+ /// Its name.+ pub name: String,+ /// Whether entries track companies or contacts.+ pub record_type: PipelineRecordType,+ /// Whether the team may edit it.+ pub sharing: PipelineSharing,+ /// Its stages in order, replacing the team's default stages.+ pub stages: Vec<String>,+ /// Fields to add after the standard ones.+ pub fields: Vec<NewField>,+}++/// Changes to a pipeline's name, sharing and fields.+#[derive(Debug, Clone, Default)]+pub struct PipelineEdit {+ /// A new name.+ pub name: Option<String>,+ /// New team sharing; only the owner may change it.+ pub sharing: Option<PipelineSharing>,+ /// Fields to add.+ pub add_fields: Vec<NewField>,+ /// Fields to rename: current name, new name.+ pub rename_fields: Vec<(String, String)>,+ /// Fields to delete with their values.+ pub remove_fields: Vec<String>,+ /// Options to add to select fields: field, labels.+ pub add_options: Vec<(String, Vec<String>)>,+ /// Options to relabel: field, current label, new label.+ pub rename_options: Vec<(String, String, String)>,+ /// Options to delete, emptying the entries holding them: field, label.+ pub remove_options: Vec<(String, String)>,+}++/// Why a workflow did not run.+#[derive(Debug, thiserror::Error)]+pub enum WorkflowError {+ /// The request names something the pipeline does not have, or asks for+ /// what it cannot do; the message says what to change.+ #[error("{0}")]+ Invalid(String),+ /// The user belongs to no team, so has no CRM.+ #[error("the user is not in a team, so they have no CRM")]+ NoTeam,+ /// The pipeline refused or failed.+ #[error(transparent)]+ Pipeline(#[from] PipelineError),+ /// Reading CRM records failed.+ #[error(transparent)]+ Crm(#[from] CrmError),+ /// Access could not be established.+ #[error(transparent)]+ Access(#[from] AccessError),+}diff --git a/crates/crm/src/domain/pipeline_workflows/ops.rs b/crates/crm/src/domain/pipeline_workflows/ops.rsnew file mode 100644index 0000000000..9461f510d0--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/ops.rs@@ -0,0 +1,107 @@+//! The database operations a workflow sends, built from names and labels.++use std::collections::HashSet;++use databases::domain::models::Viewer;+use models_databases::{+ CellWrite, ColumnChange, ColumnId, DatabaseOp, NewColumn, NewOption, OptionId,+};++use super::{+ FieldInput, FieldKind, NewField, PipelineField, PipelineOverview, WorkflowError, fields,+};++/// The stage field every pipeline starts with.+pub(super) const STAGE_FIELD: &str = "Stage";++/// The cells `set` writes, by field name.+pub(super) fn cells(+ overview: &PipelineOverview,+ set: &[(String, FieldInput)],+ viewer: &Viewer,+) -> Result<Vec<CellWrite>, WorkflowError> {+ let mut seen = HashSet::new();+ set.iter()+ .map(|(name, input)| {+ let field = overview.field(name)?;+ if !seen.insert(field.id) {+ return Err(WorkflowError::Invalid(format!(+ "\"{}\" is set twice.",+ field.name+ )));+ }+ Ok(CellWrite {+ column: field.id,+ value: fields::cell_value(field, input, &viewer.user_id)+ .map_err(WorkflowError::Invalid)?,+ })+ })+ .collect()+}++pub(super) fn select_field<'a>(+ overview: &'a PipelineOverview,+ name: &str,+) -> Result<&'a PipelineField, WorkflowError> {+ let field = overview.field(name)?;+ if matches!(field.kind, FieldKind::Select | FieldKind::Tags) {+ Ok(field)+ } else {+ Err(WorkflowError::Invalid(format!(+ "\"{}\" has no options; only select fields such as Stage do.",+ field.name+ )))+ }+}++pub(super) fn add_options(+ overview: &PipelineOverview,+ field: &PipelineField,+ labels: &[String],+) -> DatabaseOp {+ DatabaseOp::Column {+ table: overview.pipeline.pipeline.table_id,+ column: field.id,+ change: ColumnChange::AddOptions {+ options: labels+ .iter()+ .map(|label| NewOption {+ id: OptionId::new(),+ label: label.trim().to_owned(),+ })+ .collect(),+ },+ }+}++pub(super) fn add_field(+ overview: &PipelineOverview,+ field: &NewField,+) -> Result<DatabaseOp, WorkflowError> {+ if !field.options.is_empty() && !field.kind.takes_options() {+ return Err(WorkflowError::Invalid(format!(+ "\"{}\" is not a select field, so it takes no options.",+ field.name+ )));+ }+ Ok(DatabaseOp::Column {+ table: overview.pipeline.pipeline.table_id,+ column: ColumnId::new(),+ change: ColumnChange::Create {+ definition: NewColumn::New {+ name: field.name.trim().to_owned(),+ kind: field.kind.column_kind(),+ options: field+ .options+ .iter()+ .map(|label| NewOption {+ id: OptionId::new(),+ label: label.trim().to_owned(),+ })+ .collect(),+ infer_type: false,+ },+ after: None,+ },+ })+}diff --git a/crates/crm/src/domain/pipeline_workflows/records.rs b/crates/crm/src/domain/pipeline_workflows/records.rsnew file mode 100644index 0000000000..931e515eeb--- /dev/null+++ b/crates/crm/src/domain/pipeline_workflows/records.rs@@ -0,0 +1,126 @@+//! The companies and contacts entries track, named as the viewer sees them.++use std::collections::HashMap;++use entity_access::domain::models::MemberTeamRole;+use filter_ast::Expr;+use item_filters::ast::crm_contact::CrmContactLiteral;+use uuid::Uuid;++use super::super::{+ auth::CrmTeamReceipt,+ companies_repo::CrmCompanyListSort,+ contact_listing::CrmContactListQuery,+ model::CrmError,+ pipelines::PipelineRecordType,+ service::{CrmService, MAX_CONTACT_SEARCH_LIMIT},+};++/// The company or contact an entry tracks.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PipelineRecord {+ /// The CRM company or contact id.+ pub id: Uuid,+ /// Its display name; `None` when the viewer cannot see the record.+ pub name: Option<String>,+ /// A company's primary domain, or a contact's email address.+ pub detail: Option<String>,+}++impl PipelineRecord {+ /// A record known only by its id.+ pub(crate) fn unnamed(id: Uuid) -> Self {+ Self {+ id,+ name: None,+ detail: None,+ }+ }++ /// Whether its name or detail contains `search`, ignoring case.+ pub(crate) fn matches(&self, search: &str) -> bool {+ let search = search.trim().to_lowercase();+ [&self.name, &self.detail]+ .into_iter()+ .flatten()+ .any(|text| text.to_lowercase().contains(&search))+ }+}++/// The records among `ids` the viewer can see, by id. Companies are read+/// through the viewer's team CRM, hidden ones only for its admins; contacts+/// through every CRM the viewer belongs to.+pub(crate) async fn records<Crm: CrmService>(+ crm: &Crm,+ team: Option<&CrmTeamReceipt<MemberTeamRole>>,+ user_id: &str,+ record_type: PipelineRecordType,+ ids: &[Uuid],+) -> Result<HashMap<Uuid, PipelineRecord>, CrmError> {+ let mut found = HashMap::with_capacity(ids.len());+ for chunk in ids.chunks(usize::from(MAX_CONTACT_SEARCH_LIMIT)) {+ match record_type {+ PipelineRecordType::Company => {+ let Some(team) = team else {+ return Ok(found);+ };+ let hidden = (!team.include_hidden()).then_some(false);+ let limit = i64::try_from(chunk.len()).unwrap_or(i64::MAX);+ for company in crm+ .list_companies_for_soup(+ team,+ user_id,+ chunk,+ hidden,+ CrmCompanyListSort::UpdatedAt,+ None,+ limit,+ )+ .await?+ {+ let domain = company+ .company+ .domains+ .first()+ .map(|domain| domain.domain.clone());+ found.insert(+ company.company.id,+ PipelineRecord {+ id: company.company.id,+ name: company.name.or_else(|| domain.clone()),+ detail: domain,+ },+ );+ }+ }+ PipelineRecordType::Contact => {+ let Some(filter) = chunk+ .iter()+ .map(|id| Expr::Literal(CrmContactLiteral::Id(*id)))+ .reduce(|left, right| Expr::Or(Box::new(left), Box::new(right)))+ else {+ continue;+ };+ let query = CrmContactListQuery {+ filter,+ sort: CrmCompanyListSort::UpdatedAt,+ cursor: None,+ ascending: false,+ limit: u16::try_from(chunk.len()).unwrap_or(MAX_CONTACT_SEARCH_LIMIT),+ };+ for listed in crm.list_contacts_for_soup(user_id, None, query).await? {+ let contact = listed.contact;+ found.insert(+ contact.id,+ PipelineRecord {+ id: contact.id,+ name: Some(contact.name.unwrap_or_else(|| contact.email.clone())),+ detail: Some(contact.email),+ },+ );+ }+ }+ }+ }+ Ok(found)+}diff --git a/crates/crm/src/domain/pipelines.rs b/crates/crm/src/domain/pipelines.rsindex 78414f9b73..14dcc2ec66 100644--- a/crates/crm/src/domain/pipelines.rs+++ b/crates/crm/src/domain/pipelines.rs@@ -4,6 +4,7 @@mod test;use super::{auth::CrmTeamReceipt, stages::StageDefinitionStore};+use bot_id::BotId;use chrono::{DateTime, Utc};use databases::domain::{models::{@@ -11,7 +12,7 @@ use databases::domain::{TableDetail, TableId, Viewer,},provisioning::{ProvisionedColumn, StorageBlueprint},- storage::{DatabaseStorageService, StorageRows, StorageRowsQuery},+ storage::{DatabaseStorageService, StorageRow, StorageRows, StorageRowsQuery},};use entity_access::domain::{models::{@@ -282,11 +283,27 @@ pub trait PipelineService: Send + Sync + 'static {receipt: EntityAccessReceipt<ViewAccessLevel>,query: StorageRowsQuery,) -> impl Future<Output = Result<StorageRows, PipelineError>> + Send;+ /// The cells of those of `rows` that are this pipeline's, in row order.+ fn read_rows(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ rows: &[RowId],+ ) -> impl Future<Output = Result<Vec<StorageRow>, PipelineError>> + Send;+ /// This pipeline's rows whose primary column references one of+ /// `records`, in row order.+ fn record_rows(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ records: &[Uuid],+ ) -> impl Future<Output = Result<Vec<PipelineReference>, PipelineError>> + Send;/// Validate pipeline policy, then use the shared storage operation planner.+ /// `acting_bot` is the agent making the change for the receipt's user,+ /// recorded for attribution only.fn apply_ops(&self,receipt: EntityAccessReceipt<EditAccessLevel>,+ acting_bot: Option<BotId>,batch: OpBatch,) -> impl Future<Output = Result<AppliedOps, PipelineError>> + Send;/// Rename pipeline metadata.@@ -727,9 +744,46 @@ where.await?)}+ async fn read_rows(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ rows: &[RowId],+ ) -> Result<Vec<StorageRow>, PipelineError> {+ let pipeline = self.pipeline(&receipt).await?;+ let _guard = self+ .repo+ .lock_live(pipeline.id)+ .await+ .map_err(storage)?+ .ok_or(PipelineError::NotFound)?;+ Ok(self+ .databases+ .storage_row_cells(pipeline.database_id, pipeline.table_id, rows)+ .await?)+ }++ async fn record_rows(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ records: &[Uuid],+ ) -> Result<Vec<PipelineReference>, PipelineError> {+ let pipeline = self.pipeline(&receipt).await?;+ if pipeline.trashed_at.is_some() {+ return Err(PipelineError::NotFound);+ }+ if records.is_empty() {+ return Ok(Vec::new());+ }+ self.repo+ .referencing_rows(&[pipeline.id], records)+ .await+ .map_err(storage)+ }+async fn apply_ops(&self,receipt: EntityAccessReceipt<EditAccessLevel>,+ acting_bot: Option<BotId>,batch: OpBatch,) -> Result<AppliedOps, PipelineError> {use models_databases::{DatabaseOp, TableChange};@@ -754,7 +808,7 @@ where}let viewer = Viewer {user_id: actor(&receipt)?,- acting_bot: None,+ acting_bot,};// A pipeline grant does not grant access to the records it references.// The editor may reference records from any team they can access.diff --git a/crates/crm/src/inbound/pipelines.rs b/crates/crm/src/inbound/pipelines.rsindex 560cb97dc8..b78b75bb30 100644--- a/crates/crm/src/inbound/pipelines.rs+++ b/crates/crm/src/inbound/pipelines.rs@@ -231,6 +231,7 @@ pub async fn apply_ops<P: PipelineService, E: EntityAccessService, A: MacroAutho.service.apply_ops(receipt::<EditAccessLevel, _, _>(&*state.access, auth, id).await?,+ None,batch,).await?,diff --git a/crates/crm/src/inbound/toolset.rs b/crates/crm/src/inbound/toolset.rsindex ecf0e5d501..75c3d6a8bb 100644--- a/crates/crm/src/inbound/toolset.rs+++ b/crates/crm/src/inbound/toolset.rs@@ -1,14 +1,17 @@//! Toolset inbound adapter for the CRM domain.//!//! Exposes team-scoped CRM company tools (`ListCompanies`, `GetCompany`,-//! `CreateCompany`, `CreateContact`) to AI agents. Property writes (stage moves, revenue, owner, custom-//! properties) go through the properties toolset's `SetEntityProperty`-//! with `entity_type = company`.+//! `CreateCompany`, `CreateContact`) to AI agents. The company's own+//! properties (its Stage, Owner, Revenue and custom properties) are written+//! through the properties toolset's `SetEntityProperty` with+//! `entity_type = company`. Pipelines, whose entries carry their own stage+//! and fields, have their own tools in [`pipelines`].mod create_company;mod create_contact;mod get_company;mod list_companies;+pub mod pipelines;#[cfg(test)]mod test;@@ -109,7 +112,7 @@ where.add_tool::<CreateContact, CrmToolContext<CSvc, ESvc, PSvc>>()}-/// A company's pipeline stage: the select option id currently set plus its+/// A company's own Stage property: the select option id currently set plus its/// human-readable label.#[derive(Debug, Clone, Serialize, JsonSchema)]#[serde(rename_all = "camelCase")]@@ -453,7 +456,15 @@ pub(crate) fn team_access_error(err: AccessError) -> ToolCallError {/// Map a [`CrmError`] into an actionable tool error.pub(crate) fn crm_error(err: CrmError) -> ToolCallError {- let description = match &err {+ ToolCallError {+ description: crm_error_description(&err),+ internal_error: err.into(),+ }+}++/// What went wrong, in words the model can act on.+pub(crate) fn crm_error_description(err: &CrmError) -> String {+ match err {CrmError::CompanyNotFoundForTeam => {"CRM company not found for the caller's team".to_string()}@@ -476,10 +487,5 @@ pub(crate) fn crm_error(err: CrmError) -> ToolCallError {role.as_db_str()),_ => "CRM request failed".to_string(),- };-- ToolCallError {- description,- internal_error: err.into(),}}diff --git a/crates/crm/src/inbound/toolset/get_company.rs b/crates/crm/src/inbound/toolset/get_company.rsindex 0517feec98..0851d322a2 100644--- a/crates/crm/src/inbound/toolset/get_company.rs+++ b/crates/crm/src/inbound/toolset/get_company.rs@@ -104,7 +104,8 @@ pub struct GetCompanyResponse {pub first_interaction: DateTime<Utc>,/// Most recent known email interaction with this company.pub last_interaction: DateTime<Utc>,- /// The company's pipeline stage, if set.+ /// The company's own Stage property, if set; separate from any+ /// pipeline entry's stage.#[serde(skip_serializing_if = "Option::is_none")]pub stage: Option<ToolCompanyStage>,/// Macro user id of the company's owner, if set.@@ -126,7 +127,7 @@ pub struct GetCompanyResponse {#[derive(Debug, Clone, Deserialize, JsonSchema)]#[schemars(title = "GetCompany",- description = "Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response."+ description = "Fetch one of the team's CRM companies by id, with its domains, contacts, its own Stage / Owner / Revenue properties (not a pipeline deal's), and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change one of the company's own properties (its Stage, Owner, Revenue or a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response. Deals in a pipeline have their own stage and fields: find them with FindPipelineEntries (recordIds = this company's id) and change them with UpdatePipelineEntries.")]pub struct GetCompany {/// The CRM company id to fetch.diff --git a/crates/crm/src/inbound/toolset/list_companies.rs b/crates/crm/src/inbound/toolset/list_companies.rsindex 2260e18ed3..ae9d2d7a4f 100644--- a/crates/crm/src/inbound/toolset/list_companies.rs+++ b/crates/crm/src/inbound/toolset/list_companies.rs@@ -47,7 +47,8 @@ pub struct CompanyListItem {pub hidden: bool,/// Most recent known email interaction with this company.pub last_interaction: DateTime<Utc>,- /// The company's pipeline stage, if set.+ /// The company's own Stage property, if set; separate from any+ /// pipeline entry's stage.#[serde(skip_serializing_if = "Option::is_none")]pub stage: Option<ToolCompanyStage>,/// Macro user id of the company's owner, if set.@@ -72,7 +73,7 @@ pub struct ListCompaniesResponse {#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]#[schemars(title = "ListCompanies",- description = "List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties."+ description = "List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and the company's own Stage / Owner / Revenue properties when set (not a pipeline deal's). Use the filters to narrow results: `search` for name/domain text, `stage` for the company's own Stage property, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to change the company's own Stage / Owner / Revenue or custom properties. Deals in a pipeline have their own stage and fields, separate from these: use FindPipelineEntries and UpdatePipelineEntries for them.")]pub struct ListCompanies {/// Case-insensitive substring matched against company names and domains.@@ -82,9 +83,9 @@ pub struct ListCompanies {#[serde(default)]pub search: Option<String>,- /// Filter to companies in this pipeline stage (label or option id).+ /// Filter to companies whose own Stage property is this (label or option id).#[schemars(- description = "Filter to companies in this pipeline stage. Accepts a stage label matched case-insensitively (e.g. \"lead\", \"Customer\" — teams may have custom stage names) or a stage option UUID."+ description = "Filter to companies whose own Stage property (not a pipeline deal's stage) is this. Accepts a stage label matched case-insensitively (e.g. \"lead\", \"Customer\" — teams may have custom stage names) or a stage option UUID.")]#[serde(default)]pub stage: Option<String>,diff --git a/crates/crm/src/inbound/toolset/pipelines.rs b/crates/crm/src/inbound/toolset/pipelines.rsnew file mode 100644index 0000000000..1a0597d6c8--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines.rs@@ -0,0 +1,499 @@+//! Agent tools over CRM pipelines, in the CRM's own words: pipelines hold+//! entries, each entry tracks a company or contact, and fields such as Stage,+//! Owner and Revenue belong to the entry. Every tool is a thin adapter over+//! [`PipelineWorkflowService`], which resolves names and labels against the+//! pipeline's schema and writes through the pipeline's own access boundary.++mod add_to_pipeline;+mod create_pipeline;+mod edit_pipeline;+mod find_pipeline_entries;+mod list_pipelines;+mod remove_from_pipeline;+mod update_pipeline_entries;++#[cfg(test)]+mod test;++use std::collections::BTreeMap;+use std::sync::Arc;++use ai_toolset::{AsyncToolCollection, ToolCallError};+use bot_id::BotId;+use databases::domain::models::{DatabaseError, Viewer};+use entity_access::domain::models::{AccessError, AccessLevel};+use macro_user_id::user_id::MacroUserIdStr;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::domain::{+ pipeline_workflows::{+ FieldInput, FieldKind, FieldValue, NewField, NewFieldKind, PipelineEntryView,+ PipelineField, PipelineOverview, PipelineRecord, PipelineWorkflowService, WorkflowError,+ },+ pipelines::{PipelineError, PipelineRecordType, PipelineSharing},+};++pub use add_to_pipeline::{AddToPipeline, AddToPipelineResponse};+pub use create_pipeline::{CreatePipeline, CreatePipelineResponse};+pub use edit_pipeline::{EditPipeline, EditPipelineResponse};+pub use find_pipeline_entries::{FindPipelineEntries, FindPipelineEntriesResponse};+pub use list_pipelines::{ListPipelines, ListPipelinesResponse};+pub use remove_from_pipeline::{RemoveFromPipeline, RemoveFromPipelineResponse};+pub use update_pipeline_entries::{UpdatePipelineEntries, UpdatePipelineEntriesResponse};++/// The pipeline workflows and the agent the tools act as.+pub struct PipelineToolContext<Workflows> {+ /// Resolves names, authorizes and writes through the pipeline service.+ pub service: Arc<Workflows>,+ /// The agent acting for the requesting user; attribution only.+ pub actor: BotId,+}++impl<Workflows> Clone for PipelineToolContext<Workflows> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ actor: self.actor,+ }+ }+}++impl<Workflows> PipelineToolContext<Workflows> {+ /// The tools over `service`, acting as the Macro AI bot.+ pub fn new(service: Workflows) -> Self {+ Self {+ service: Arc::new(service),+ actor: bot_id::MACRO_AI_BOT_ID,+ }+ }++ /// The requesting user, with this context's agent acting for them.+ fn viewer(&self, user_id: MacroUserIdStr<'static>) -> Viewer {+ Viewer {+ user_id,+ acting_bot: Some(self.actor),+ }+ }+}++/// Every pipeline tool.+pub fn pipeline_toolset<Workflows: PipelineWorkflowService>()+-> AsyncToolCollection<PipelineToolContext<Workflows>> {+ AsyncToolCollection::new()+ .add_tool::<ListPipelines, PipelineToolContext<Workflows>>()+ .add_tool::<FindPipelineEntries, PipelineToolContext<Workflows>>()+ .add_tool::<AddToPipeline, PipelineToolContext<Workflows>>()+ .add_tool::<UpdatePipelineEntries, PipelineToolContext<Workflows>>()+ .add_tool::<RemoveFromPipeline, PipelineToolContext<Workflows>>()+ .add_tool::<CreatePipeline, PipelineToolContext<Workflows>>()+ .add_tool::<EditPipeline, PipelineToolContext<Workflows>>()+}++/// A field and the value to write or match, as text.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolFieldValue {+ /// The field's name.+ #[schemars(+ description = "The field's name exactly as ListPipelines shows it, e.g. \"Stage\", \"Owner\", \"Revenue\"."+ )]+ pub field: String,+ /// One value as text.+ #[schemars(+ description = "The value as text: a stage or other option label (\"Negotiation\"), a person as \"me\", an email or a macro| user id, a number (\"48000\"), true/false, or a date (\"2026-10-12\"). Omit both value and values to empty the field (or, in a filter, to match empty fields)."+ )]+ #[serde(default)]+ pub value: Option<String>,+ /// Several values.+ #[schemars(+ description = "Several values, for a field that holds several (tags, people). In a filter, an entry matches if it holds any of them, e.g. [\"Demo\", \"Trial\"] for either stage."+ )]+ #[serde(default)]+ pub values: Option<Vec<String>>,+}++impl ToolFieldValue {+ fn pair(&self) -> (String, FieldInput) {+ let input = match (&self.values, &self.value) {+ (Some(values), _) if !values.is_empty() => FieldInput::Many(values.clone()),+ (_, Some(value)) => FieldInput::One(value.clone()),+ _ => FieldInput::Clear,+ };+ (self.field.clone(), input)+ }+}++fn pairs(values: &[ToolFieldValue]) -> Vec<(String, FieldInput)> {+ values.iter().map(ToolFieldValue::pair).collect()+}++/// What a pipeline's entries track. Documented on the fields that use it: a+/// doc comment on a variant would turn the schema into `oneOf`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+#[expect(+ missing_docs,+ reason = "variant docs would make the tool schema a oneOf"+)]+pub enum ToolRecordType {+ Company,+ Contact,+}++impl From<PipelineRecordType> for ToolRecordType {+ fn from(value: PipelineRecordType) -> Self {+ match value {+ PipelineRecordType::Company => Self::Company,+ PipelineRecordType::Contact => Self::Contact,+ }+ }+}++impl From<ToolRecordType> for PipelineRecordType {+ fn from(value: ToolRecordType) -> Self {+ match value {+ ToolRecordType::Company => Self::Company,+ ToolRecordType::Contact => Self::Contact,+ }+ }+}++/// The type of a field to add. Documented on the fields that use it.+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+#[expect(+ missing_docs,+ reason = "variant docs would make the tool schema a oneOf"+)]+pub enum ToolNewFieldType {+ Text,+ Number,+ Checkbox,+ Date,+ Link,+ Select,+ MultiSelect,+ Person,+ People,+}++impl From<ToolNewFieldType> for NewFieldKind {+ fn from(value: ToolNewFieldType) -> Self {+ match value {+ ToolNewFieldType::Text => Self::Text,+ ToolNewFieldType::Number => Self::Number,+ ToolNewFieldType::Checkbox => Self::Checkbox,+ ToolNewFieldType::Date => Self::Date,+ ToolNewFieldType::Link => Self::Link,+ ToolNewFieldType::Select => Self::Select,+ ToolNewFieldType::MultiSelect => Self::MultiSelect,+ ToolNewFieldType::Person => Self::Person,+ ToolNewFieldType::People => Self::People,+ }+ }+}++/// A field to add to a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolNewField {+ /// Its name.+ #[schemars(description = "The new field's name, unique in the pipeline.")]+ pub name: String,+ /// Its type.+ #[schemars(+ description = "text, number, checkbox, date, link, select (one label from a list, like a stage or priority), multi_select (several labels), person (one Macro user) or people (several)."+ )]+ #[serde(rename = "type")]+ pub field_type: ToolNewFieldType,+ /// A select field's options.+ #[schemars(description = "For select and multi_select: the labels to choose from, in order.")]+ #[serde(default)]+ pub options: Vec<String>,+}++impl From<&ToolNewField> for NewField {+ fn from(field: &ToolNewField) -> Self {+ Self {+ name: field.name.clone(),+ kind: field.field_type.into(),+ options: field.options.clone(),+ }+ }+}++/// What a field holds, as the model reads it.+#[derive(Debug, Clone, Copy, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ToolFieldType {+ /// The company the entry tracks.+ Company,+ /// The contact the entry tracks.+ Contact,+ /// Free text.+ Text,+ /// A number.+ Number,+ /// True or false.+ Checkbox,+ /// A date-time.+ Date,+ /// URLs.+ Link,+ /// Labels from `options`, such as a stage.+ Select,+ /// Tags.+ Tags,+ /// Macro users, written as "me", an email or a macro| id.+ Person,+ /// Ids of other Macro items.+ Item,+ /// Linked rows; read-only here.+ Relation,+ /// Computed; read-only.+ Formula,+}++impl From<FieldKind> for ToolFieldType {+ fn from(kind: FieldKind) -> Self {+ match kind {+ FieldKind::Record(PipelineRecordType::Company) => Self::Company,+ FieldKind::Record(PipelineRecordType::Contact) => Self::Contact,+ FieldKind::Text => Self::Text,+ FieldKind::Number => Self::Number,+ FieldKind::Checkbox => Self::Checkbox,+ FieldKind::Date => Self::Date,+ FieldKind::Link => Self::Link,+ FieldKind::Select => Self::Select,+ FieldKind::Tags => Self::Tags,+ FieldKind::Person => Self::Person,+ FieldKind::Entity(_) => Self::Item,+ FieldKind::Relation => Self::Relation,+ FieldKind::Formula => Self::Formula,+ }+ }+}++/// One field of a pipeline.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolField {+ /// The name to use in `field`.+ pub name: String,+ /// What it holds.+ #[serde(rename = "type")]+ pub field_type: ToolFieldType,+ /// Whether it holds several values.+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub multiple: bool,+ /// For a select field, its labels in order: for Stage, the pipeline's+ /// stages from first to last.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub options: Vec<String>,+ /// Whether every entry must have a value.+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub required: bool,+ /// Whether the user cannot write it.+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub read_only: bool,+}++impl From<&PipelineField> for ToolField {+ fn from(field: &PipelineField) -> Self {+ Self {+ name: field.name.clone(),+ field_type: field.kind.into(),+ multiple: field.multiple,+ options: field+ .options+ .iter()+ .map(|(_, label)| label.clone())+ .collect(),+ required: field.required,+ read_only: !field.writable,+ }+ }+}++/// What the user may do with a pipeline.+#[derive(Debug, Clone, Copy, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ToolPipelineAccess {+ /// Read its entries.+ View,+ /// Add, change and remove entries, and change its fields.+ Edit,+ /// Edit, and change who it is shared with.+ Owner,+}++/// A pipeline as the model sees it.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolPipeline {+ /// Pass as `pipelineId`.+ pub id: Uuid,+ /// Its name.+ pub name: String,+ /// What each entry tracks: `company` or `contact`.+ pub tracks: ToolRecordType,+ /// What the user may do with it.+ pub access: ToolPipelineAccess,+ /// Whether the owner's team may edit it; otherwise it is private.+ pub shared_with_team: bool,+ /// Its fields in column order; the first names the tracked record.+ pub fields: Vec<ToolField>,+ /// Its version now; pass as `baseVersion` to refuse an update if the+ /// pipeline changed in between.+ pub version: i64,+}++impl From<&PipelineOverview> for ToolPipeline {+ fn from(overview: &PipelineOverview) -> Self {+ let pipeline = &overview.pipeline.pipeline;+ Self {+ id: pipeline.id,+ name: pipeline.name.clone(),+ tracks: pipeline.record_type.into(),+ access: match overview.pipeline.grant {+ AccessLevel::View | AccessLevel::Comment => ToolPipelineAccess::View,+ AccessLevel::Edit => ToolPipelineAccess::Edit,+ AccessLevel::Owner => ToolPipelineAccess::Owner,+ },+ shared_with_team: pipeline.sharing == PipelineSharing::Team,+ fields: overview.fields.iter().map(ToolField::from).collect(),+ version: overview.version.0,+ }+ }+}++/// The company or contact an entry tracks.+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolRecord {+ /// The CRM company or contact id.+ pub id: Uuid,+ /// Its name; missing when the user cannot see the record.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// A company's domain or a contact's email.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub detail: Option<String>,+}++impl From<&PipelineRecord> for ToolRecord {+ fn from(record: &PipelineRecord) -> Self {+ Self {+ id: record.id,+ name: record.name.clone(),+ detail: record.detail.clone(),+ }+ }+}++/// One pipeline entry.+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolEntry {+ /// Pass as `entryId`.+ pub entry_id: Uuid,+ /// The company or contact it tracks.+ pub record: ToolRecord,+ /// Its filled-in fields by name: text, a number, true/false, a date, or a+ /// list when a field holds several values. People are macro| user ids.+ pub fields: BTreeMap<String, serde_json::Value>,+}++impl From<&PipelineEntryView> for ToolEntry {+ fn from(entry: &PipelineEntryView) -> Self {+ Self {+ entry_id: entry.entry_id.into_uuid(),+ record: (&entry.record).into(),+ fields: entry+ .fields+ .iter()+ .map(|(name, value)| (name.clone(), json(value)))+ .collect(),+ }+ }+}++/// A field value as JSON: one value plainly, several as a list.+pub(crate) fn json(value: &FieldValue) -> serde_json::Value {+ use serde_json::Value;+ let many = |values: &[String]| match values {+ [one] => Value::String(one.clone()),+ values => Value::from(values.to_vec()),+ };+ match value {+ FieldValue::Text(text) => Value::String(text.clone()),+ FieldValue::Number(number) => {+ serde_json::Number::from_f64(*number).map_or(Value::Null, Value::Number)+ }+ FieldValue::Checkbox(checked) => Value::Bool(*checked),+ FieldValue::Date(date) => Value::String(date.to_rfc3339()),+ FieldValue::Labels(values) | FieldValue::Links(values) | FieldValue::References(values) => {+ many(values)+ }+ }+}++/// The record a summary line names.+pub(crate) fn record_name(record: &ToolRecord) -> String {+ record+ .name+ .clone()+ .or_else(|| record.detail.clone())+ .unwrap_or_else(|| record.id.to_string())+}++/// A workflow failure in words the model can act on.+pub(crate) fn workflow_error(error: WorkflowError) -> ToolCallError {+ let description = match &error {+ WorkflowError::Invalid(message) => message.clone(),+ WorkflowError::NoTeam => {+ "The user is not in a team, so they have no CRM pipelines.".to_owned()+ }+ WorkflowError::Pipeline(PipelineError::NotFound)+ | WorkflowError::Access(AccessError::NotFound(_))+ | WorkflowError::Pipeline(PipelineError::Access(AccessError::NotFound(_))) => {+ "No pipeline with that id exists for this user. Call ListPipelines for the user's \+ pipelines and their ids."+ .to_owned()+ }+ WorkflowError::Access(+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),+ )+ | WorkflowError::Pipeline(PipelineError::Access(+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),+ )) => "The user does not have permission to do that to this pipeline. Reading needs view \+ access; changing entries or fields needs edit access."+ .to_owned(),+ WorkflowError::Access(AccessError::Unavailable(_))+ | WorkflowError::Pipeline(PipelineError::Access(AccessError::Unavailable(_))) => {+ "Access to the pipeline could not be checked right now. Retry the call.".to_owned()+ }+ WorkflowError::Pipeline(PipelineError::Invalid(message)) => (*message).to_owned(),+ WorkflowError::Pipeline(PipelineError::Database(DatabaseError::VersionConflict)) => {+ "The pipeline changed since it was read, so nothing was written. Read the entries \+ again with FindPipelineEntries and retry with its version."+ .to_owned()+ }+ WorkflowError::Pipeline(PipelineError::Database(+ refusal @ (DatabaseError::InvalidOp(_)+ | DatabaseError::InvalidSchemaOperation(_)+ | DatabaseError::OptionInUse+ | DatabaseError::RowInUse),+ )) => format!("The change was refused, so nothing changed: {refusal}."),+ WorkflowError::Pipeline(PipelineError::Crm(error)) | WorkflowError::Crm(error) => {+ super::crm_error_description(error)+ }+ _ => "The CRM pipeline service failed.".to_owned(),+ };+ ToolCallError {+ description,+ internal_error: anyhow::Error::new(error),+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rsnew file mode 100644index 0000000000..2d9927d23d--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rs@@ -0,0 +1,155 @@+//! AddToPipeline: put companies or contacts into a pipeline as new deals.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{PipelineToolContext, ToolEntry, ToolFieldValue, pairs, record_name, workflow_error};+use crate::domain::pipeline_workflows::{EntryAddition, PipelineWorkflowService, RecordTarget};++/// One company or contact to add.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolNewEntry {+ /// The record's id.+ #[schemars(+ description = "The CRM company or contact id to add (company ids come from ListCompanies). Give this or email."+ )]+ #[serde(default)]+ pub record_id: Option<Uuid>,+ /// A contact's email.+ #[schemars(+ description = "A contact's email address instead of an id: adds that contact, or in a company pipeline the contact's company."+ )]+ #[serde(default)]+ pub email: Option<String>,+ /// Fields to fill in.+ #[schemars(+ description = "Fields to fill in on the new entry, e.g. [{\"field\": \"Stage\", \"value\": \"Lead\"}, {\"field\": \"Owner\", \"value\": \"me\"}]."+ )]+ #[serde(default)]+ pub set: Vec<ToolFieldValue>,+}++/// Add records to a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "AddToPipeline",+ description = "Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved."+)]+pub struct AddToPipeline {+ /// The pipeline.+ #[schemars(description = "The pipeline's id from ListPipelines.")]+ pub pipeline_id: Uuid,+ /// What to add.+ #[schemars(description = "The companies or contacts to add, each with its starting fields.")]+ pub entries: Vec<ToolNewEntry>,+ /// Whether to add a record that is already in the pipeline.+ #[schemars(+ description = "Add a record again even if it already has an entry in this pipeline. Only for a genuinely separate second deal. Defaults to false."+ )]+ #[serde(default)]+ pub allow_duplicates: Option<bool>,+}++/// The entries added.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct AddToPipelineResponse {+ /// The new entries, as saved.+ pub added: Vec<ToolEntry>,+ /// Existing entries of requested records that were not added again.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub already_present: Vec<ToolEntry>,+ /// The pipeline's version after the change.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub version: Option<i64>,+ /// What changed.+ pub summary: String,+}++impl ToolAnnotated for AddToPipeline {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Add to pipeline");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for AddToPipeline+{+ type Output = AddToPipelineResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let additions = self+ .entries+ .iter()+ .map(|entry| {+ let record = match (entry.record_id, &entry.email) {+ (Some(id), None) => RecordTarget::Id(id),+ (None, Some(email)) => RecordTarget::Email(email.trim().to_owned()),+ _ => {+ return Err(ToolCallError {+ description: "Give each entry exactly one of recordId or email."+ .to_owned(),+ internal_error: anyhow::anyhow!("entry without one record"),+ });+ }+ };+ Ok(EntryAddition {+ record,+ set: pairs(&entry.set),+ })+ })+ .collect::<Result<Vec<_>, _>>()?;+ let viewer = context.viewer(request_context.user_id);+ let added = context+ .service+ .add(+ &viewer,+ self.pipeline_id,+ additions,+ self.allow_duplicates.unwrap_or(false),+ )+ .await+ .map_err(workflow_error)?;+ let added_entries: Vec<ToolEntry> = added.added.iter().map(ToolEntry::from).collect();+ let present: Vec<ToolEntry> = added.already_present.iter().map(ToolEntry::from).collect();+ let mut summary = match added_entries.as_slice() {+ [] => "Added nothing.".to_owned(),+ entries => format!(+ "Added {}.",+ entries+ .iter()+ .map(|entry| record_name(&entry.record))+ .collect::<Vec<_>>()+ .join(", ")+ ),+ };+ if !present.is_empty() {+ summary.push_str(&format!(+ " Already in the pipeline, so not added again: {}.",+ present+ .iter()+ .map(|entry| record_name(&entry.record))+ .collect::<Vec<_>>()+ .join(", ")+ ));+ }+ Ok(AddToPipelineResponse {+ added: added_entries,+ already_present: present,+ version: added.version.map(|version| version.0),+ summary,+ })+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rsnew file mode 100644index 0000000000..0b074f6b61--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rs@@ -0,0 +1,107 @@+//! CreatePipeline: a new CRM pipeline with its stages and fields.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::Deserialize;++use super::{PipelineToolContext, ToolNewField, ToolPipeline, ToolRecordType, workflow_error};+use crate::domain::{+ pipeline_workflows::{NewPipeline, PipelineWorkflowService},+ pipelines::PipelineSharing,+};++/// Create a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "CreatePipeline",+ description = "Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields."+)]+pub struct CreatePipeline {+ /// Its name.+ #[schemars(description = "The pipeline's name, e.g. \"Q4 Renewals\".")]+ pub name: String,+ /// What entries track.+ #[schemars(+ description = "\"company\" for deals with organizations, \"contact\" for deals with individual people (candidates, investors, partners)."+ )]+ pub tracks: ToolRecordType,+ /// Team sharing.+ #[schemars(+ description = "Let the user's team see and edit it. Defaults to false: only the user can see it."+ )]+ #[serde(default)]+ pub shared_with_team: Option<bool>,+ /// Its stages.+ #[schemars(+ description = "The stages, first to last, e.g. [\"Sourced\", \"Screen\", \"Interview\", \"Offer\", \"Hired\"]. Leave empty for the team's default stages."+ )]+ #[serde(default)]+ pub stages: Vec<String>,+ /// More fields.+ #[schemars(description = "Fields to add after Company/Contact, Stage, Owner and Revenue.")]+ #[serde(default)]+ pub fields: Vec<ToolNewField>,+}++/// The pipeline created.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreatePipelineResponse {+ /// The new pipeline.+ pub pipeline: ToolPipeline,+ /// What changed.+ pub summary: String,+}++impl ToolAnnotated for CreatePipeline {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create pipeline");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for CreatePipeline+{+ type Output = CreatePipelineResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let viewer = context.viewer(request_context.user_id);+ let created = context+ .service+ .create(+ &viewer,+ NewPipeline {+ name: self.name.clone(),+ record_type: self.tracks.into(),+ sharing: if self.shared_with_team.unwrap_or(false) {+ PipelineSharing::Team+ } else {+ PipelineSharing::Private+ },+ stages: self.stages.clone(),+ fields: self.fields.iter().map(Into::into).collect(),+ },+ )+ .await+ .map_err(workflow_error)?;+ let pipeline = ToolPipeline::from(&created);+ let summary = format!(+ "Created pipeline \"{}\" ({}).",+ pipeline.name,+ if pipeline.shared_with_team {+ "shared with the team"+ } else {+ "private"+ }+ );+ Ok(CreatePipelineResponse { pipeline, summary })+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/edit_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/edit_pipeline.rsnew file mode 100644index 0000000000..608664fae7--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/edit_pipeline.rs@@ -0,0 +1,190 @@+//! EditPipeline: rename, share, and change the stages and fields of a pipeline.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{PipelineToolContext, ToolNewField, ToolPipeline, workflow_error};+use crate::domain::{+ pipeline_workflows::{PipelineEdit, PipelineWorkflowService},+ pipelines::PipelineSharing,+};++/// A field to rename.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolRename {+ /// Current name.+ #[schemars(description = "The current name.")]+ pub from: String,+ /// New name.+ #[schemars(description = "The new name.")]+ pub to: String,+}++/// Options to add to a select field.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolAddOptions {+ /// The field.+ #[schemars(description = "The select field, e.g. \"Stage\".")]+ pub field: String,+ /// New labels.+ #[schemars(description = "Labels to add after the existing ones.")]+ pub labels: Vec<String>,+}++/// An option to relabel.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolRenameOption {+ /// The field.+ #[schemars(description = "The select field, e.g. \"Stage\".")]+ pub field: String,+ /// Current label.+ #[schemars(description = "The option's current label.")]+ pub from: String,+ /// New label.+ #[schemars(description = "Its new label; entries holding it keep it.")]+ pub to: String,+}++/// An option to delete.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolRemoveOption {+ /// The field.+ #[schemars(description = "The select field, e.g. \"Stage\".")]+ pub field: String,+ /// The label.+ #[schemars(description = "The option to delete.")]+ pub label: String,+}++/// Change a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "EditPipeline",+ description = "Change a CRM pipeline itself: rename it, share it with the team or make it private (owner only), add, rename or remove fields, and add, rename or remove stages and other select options. Stages are the options of the Stage field: to add a stage use addOptions on \"Stage\"; to rename one use renameOptions. Removing a field deletes its values from every entry, and removing a stage or option empties it on the entries holding it, so do that only when the user asked. New options go after the existing ones. Field changes apply together, all or nothing. Returns the pipeline with its fields as they are now."+)]+pub struct EditPipeline {+ /// The pipeline.+ #[schemars(description = "The pipeline's id from ListPipelines.")]+ pub pipeline_id: Uuid,+ /// New name.+ #[schemars(description = "A new name for the pipeline.")]+ #[serde(default)]+ pub name: Option<String>,+ /// Team sharing.+ #[schemars(+ description = "true lets the user's team see and edit it; false makes it private to its owner. Only the owner can change this."+ )]+ #[serde(default)]+ pub shared_with_team: Option<bool>,+ /// Fields to add.+ #[schemars(description = "Fields to add after the existing ones.")]+ #[serde(default)]+ pub add_fields: Vec<ToolNewField>,+ /// Fields to rename.+ #[schemars(description = "Fields to rename.")]+ #[serde(default)]+ pub rename_fields: Vec<ToolRename>,+ /// Fields to remove.+ #[schemars(+ description = "Names of fields to delete with their values. The Company or Contact field cannot be removed."+ )]+ #[serde(default)]+ pub remove_fields: Vec<String>,+ /// Options to add.+ #[schemars(description = "Stages or other select options to add.")]+ #[serde(default)]+ pub add_options: Vec<ToolAddOptions>,+ /// Options to relabel.+ #[schemars(description = "Stages or other select options to relabel.")]+ #[serde(default)]+ pub rename_options: Vec<ToolRenameOption>,+ /// Options to delete.+ #[schemars(description = "Stages or other select options to delete.")]+ #[serde(default)]+ pub remove_options: Vec<ToolRemoveOption>,+}++/// The pipeline after the change.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct EditPipelineResponse {+ /// The pipeline as it is now.+ pub pipeline: ToolPipeline,+ /// What changed.+ pub summary: String,+}++impl ToolAnnotated for EditPipeline {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Edit pipeline");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for EditPipeline+{+ type Output = EditPipelineResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let viewer = context.viewer(request_context.user_id);+ let edited = context+ .service+ .edit(+ &viewer,+ self.pipeline_id,+ PipelineEdit {+ name: self.name.clone(),+ sharing: self.shared_with_team.map(|shared| {+ if shared {+ PipelineSharing::Team+ } else {+ PipelineSharing::Private+ }+ }),+ add_fields: self.add_fields.iter().map(Into::into).collect(),+ rename_fields: self+ .rename_fields+ .iter()+ .map(|rename| (rename.from.clone(), rename.to.clone()))+ .collect(),+ remove_fields: self.remove_fields.clone(),+ add_options: self+ .add_options+ .iter()+ .map(|add| (add.field.clone(), add.labels.clone()))+ .collect(),+ rename_options: self+ .rename_options+ .iter()+ .map(|rename| {+ (rename.field.clone(), rename.from.clone(), rename.to.clone())+ })+ .collect(),+ remove_options: self+ .remove_options+ .iter()+ .map(|remove| (remove.field.clone(), remove.label.clone()))+ .collect(),+ },+ )+ .await+ .map_err(workflow_error)?;+ let pipeline = ToolPipeline::from(&edited);+ let summary = format!("Updated pipeline \"{}\".", pipeline.name);+ Ok(EditPipelineResponse { pipeline, summary })+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rs b/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rsnew file mode 100644index 0000000000..5632891be3--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rs@@ -0,0 +1,298 @@+//! FindPipelineEntries: the deals in a pipeline, or a record's deals in every+//! pipeline.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{PipelineToolContext, ToolEntry, ToolFieldValue, pairs, workflow_error};+use crate::domain::pipeline_workflows::{EntryQuery, FoundEntries, PipelineWorkflowService};++/// Entries returned when `limit` is left out.+const DEFAULT_LIMIT: u16 = 50;+/// Most entries one call returns.+const MAX_LIMIT: u16 = 200;++/// Read entries of a pipeline.+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "FindPipelineEntries",+ description = "Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like \"how many deals are in Negotiation\" or \"what is the pipeline worth\". To find where a company or contact is across all pipelines (\"what stage is Acme in?\"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines."+)]+pub struct FindPipelineEntries {+ /// The pipeline to read.+ #[schemars(+ description = "The pipeline's id from ListPipelines. Leave it out to look in every pipeline by `search` or `recordIds`; filters and sorting need a pipelineId."+ )]+ #[serde(default)]+ pub pipeline_id: Option<Uuid>,+ /// Field filters.+ #[schemars(+ description = "Only entries whose fields hold these values; all filters must match. Options and people match exactly (labels ignore case), text matches a substring, dates match the day. Example: [{\"field\": \"Stage\", \"values\": [\"Demo\", \"Trial\"]}, {\"field\": \"Owner\", \"value\": \"me\"}]."+ )]+ #[serde(default)]+ pub filters: Vec<ToolFieldValue>,+ /// Record ids.+ #[schemars(description = "Only entries tracking these CRM company or contact ids.")]+ #[serde(default)]+ pub record_ids: Vec<Uuid>,+ /// Record search text.+ #[schemars(+ description = "Text the tracked company's name or domain, or the contact's name or email, must contain, ignoring case (e.g. \"acme\")."+ )]+ #[serde(default)]+ pub search: Option<String>,+ /// The field to sort by.+ #[schemars(+ description = "A field name to order entries by, e.g. \"Revenue\" or \"Stage\". Empty fields come last."+ )]+ #[serde(default)]+ pub sort_by: Option<String>,+ /// Largest first.+ #[schemars(description = "Sort largest, latest or furthest stage first. Defaults to false.")]+ #[serde(default)]+ pub descending: Option<bool>,+ /// Most entries to return.+ #[schemars(description = "Most entries to return. Defaults to 50; max 200.")]+ #[serde(default)]+ pub limit: Option<u16>,+}++/// One pipeline's matching entries.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolPipelineEntries {+ /// The pipeline's id.+ pub pipeline_id: Uuid,+ /// The pipeline's name.+ pub pipeline_name: String,+ /// The pipeline's version when read; pass as `baseVersion` to+ /// UpdatePipelineEntries to refuse the update if it changed since.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub version: Option<i64>,+ /// The entries.+ pub entries: Vec<ToolEntry>,+}++/// How many matching entries hold one option.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolOptionCount {+ /// The option's label.+ pub label: String,+ /// Matching entries holding it.+ pub count: usize,+}++/// Matching entries per option of one single-select field, such as Stage.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolOptionCounts {+ /// The field.+ pub field: String,+ /// Every option in order with its count.+ pub counts: Vec<ToolOptionCount>,+ /// Matching entries with the field empty.+ pub empty: usize,+}++/// The sum of a number field over the matching entries.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolTotal {+ /// The field.+ pub field: String,+ /// The sum.+ pub sum: f64,+}++/// The entries found.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct FindPipelineEntriesResponse {+ /// Matching entries, grouped by pipeline.+ pub pipelines: Vec<ToolPipelineEntries>,+ /// How many entries matched; more than returned when `limit` cut them.+ pub matched: usize,+ /// Whether every entry of the pipeline was read. When false the pipeline+ /// is too large to read whole, and counts and totals are partial.+ pub complete: bool,+ /// Matching entries per stage (and per option of every other+ /// single-select field), over all matches.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub counts: Vec<ToolOptionCounts>,+ /// The sum of every number field, such as Revenue, over all matches.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub totals: Vec<ToolTotal>,+ /// What was found.+ pub summary: String,+}++impl ToolAnnotated for FindPipelineEntries {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Find pipeline entries");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for FindPipelineEntries+{+ type Output = FindPipelineEntriesResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let viewer = context.viewer(request_context.user_id);+ let limit = usize::from(self.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT));+ let Some(pipeline_id) = self.pipeline_id else {+ let search = self+ .search+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty());+ if !self.filters.is_empty() || self.sort_by.is_some() {+ return Err(ToolCallError {+ description: "Filters and sorting apply to one pipeline: pass its pipelineId \+ from ListPipelines."+ .to_owned(),+ internal_error: anyhow::anyhow!("filters without a pipeline"),+ });+ }+ let found = match (search, self.record_ids.is_empty()) {+ (Some(search), _) => context.service.search_entries(&viewer, search, limit).await,+ (None, false) => {+ context+ .service+ .record_entries(&viewer, &self.record_ids)+ .await+ }+ (None, true) => {+ return Err(ToolCallError {+ description: "Pass a pipelineId from ListPipelines, or a `search` or \+ recordIds to look in every pipeline."+ .to_owned(),+ internal_error: anyhow::anyhow!("nothing to look for"),+ });+ }+ }+ .map_err(workflow_error)?;+ let found: Vec<_> = found+ .into_iter()+ .map(|mut group| {+ if !self.record_ids.is_empty() {+ group+ .entries+ .retain(|entry| self.record_ids.contains(&entry.record.id));+ }+ group+ })+ .filter(|group| !group.entries.is_empty())+ .collect();+ let matched = found.iter().map(|group| group.entries.len()).sum();+ let found: Vec<_> = found+ .into_iter()+ .map(|mut group| {+ group.entries.truncate(limit);+ group+ })+ .collect();+ let summary = match matched {+ 0 => "No entry in any of the user's pipelines matches.".to_owned(),+ count => format!("Found {count} entries in {} pipelines.", found.len()),+ };+ return Ok(FindPipelineEntriesResponse {+ pipelines: found+ .iter()+ .map(|group| ToolPipelineEntries {+ pipeline_id: group.pipeline.pipeline.id,+ pipeline_name: group.pipeline.pipeline.name.clone(),+ version: None,+ entries: group.entries.iter().map(ToolEntry::from).collect(),+ })+ .collect(),+ matched,+ complete: true,+ counts: Vec::new(),+ totals: Vec::new(),+ summary,+ });+ };++ let found = context+ .service+ .find(+ &viewer,+ pipeline_id,+ EntryQuery {+ filters: pairs(&self.filters),+ records: self.record_ids.clone(),+ search: self+ .search+ .clone()+ .filter(|search| !search.trim().is_empty()),+ sort: self+ .sort_by+ .clone()+ .map(|field| (field, self.descending.unwrap_or(false))),+ limit,+ },+ )+ .await+ .map_err(workflow_error)?;+ Ok(response(found))+ }+}++fn response(found: FoundEntries) -> FindPipelineEntriesResponse {+ let name = found.pipeline.pipeline.pipeline.name.clone();+ let mut summary = match (found.matched, found.entries.len()) {+ (0, _) => format!("No entries in \"{name}\" match."),+ (matched, shown) if shown < matched => {+ format!("Showing {shown} of {matched} matching entries in \"{name}\".")+ }+ (matched, _) => format!("Found {matched} matching entries in \"{name}\"."),+ };+ if !found.complete {+ summary.push_str(+ " The pipeline is too large to read whole, so these results, counts and totals \+ cover only part of it: say so, and narrow the request.",+ );+ }+ FindPipelineEntriesResponse {+ pipelines: vec![ToolPipelineEntries {+ pipeline_id: found.pipeline.pipeline.pipeline.id,+ pipeline_name: name,+ version: Some(found.pipeline.version.0),+ entries: found.entries.iter().map(ToolEntry::from).collect(),+ }],+ matched: found.matched,+ complete: found.complete,+ counts: found+ .counts+ .into_iter()+ .map(|counts| ToolOptionCounts {+ field: counts.field,+ counts: counts+ .counts+ .into_iter()+ .map(|(label, count)| ToolOptionCount { label, count })+ .collect(),+ empty: counts.empty,+ })+ .collect(),+ totals: found+ .totals+ .into_iter()+ .map(|(field, sum)| ToolTotal { field, sum })+ .collect(),+ summary,+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rs b/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rsnew file mode 100644index 0000000000..b9767910c8--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rs@@ -0,0 +1,63 @@+//! ListPipelines: the user's CRM pipelines with their stages and fields.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++use super::{PipelineToolContext, ToolPipeline, workflow_error};+use crate::domain::pipeline_workflows::PipelineWorkflowService;++/// List the user's CRM pipelines.+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]+#[schemars(+ title = "ListPipelines",+ description = "List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one."+)]+pub struct ListPipelines {}++/// The user's pipelines.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListPipelinesResponse {+ /// Every live pipeline the user can see.+ pub pipelines: Vec<ToolPipeline>,+ /// What was found.+ pub summary: String,+}++impl ToolAnnotated for ListPipelines {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List pipelines");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for ListPipelines+{+ type Output = ListPipelinesResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let viewer = context.viewer(request_context.user_id);+ let pipelines: Vec<ToolPipeline> = context+ .service+ .pipelines(&viewer)+ .await+ .map_err(workflow_error)?+ .iter()+ .map(ToolPipeline::from)+ .collect();+ let summary = match pipelines.as_slice() {+ [] => "The user has no pipelines. CreatePipeline makes one.".to_owned(),+ [one] => format!("The user has one pipeline, \"{}\".", one.name),+ many => format!("The user has {} pipelines.", many.len()),+ };+ Ok(ListPipelinesResponse { pipelines, summary })+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rsnew file mode 100644index 0000000000..43546bfbca--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rs@@ -0,0 +1,95 @@+//! RemoveFromPipeline: take deals out of a pipeline.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use async_trait::async_trait;+use databases::domain::models::RowId;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{PipelineToolContext, ToolEntry, record_name, workflow_error};+use crate::domain::pipeline_workflows::{EntryTarget, PipelineWorkflowService};++/// Remove entries from a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "RemoveFromPipeline",+ description = "Remove deals (entries) from a CRM pipeline, deleting their stage and other pipeline fields. The companies and contacts themselves stay in the CRM and in other pipelines. Address entries by entryId, or by the company or contact id they track (which removes every entry of that record in this pipeline). Only when the user asked to remove them."+)]+pub struct RemoveFromPipeline {+ /// The pipeline.+ #[schemars(description = "The pipeline's id from ListPipelines.")]+ pub pipeline_id: Uuid,+ /// Entries to remove.+ #[schemars(description = "Entry ids from FindPipelineEntries.")]+ #[serde(default)]+ pub entry_ids: Vec<Uuid>,+ /// Records to take out.+ #[schemars(description = "CRM company or contact ids whose entries to remove.")]+ #[serde(default)]+ pub record_ids: Vec<Uuid>,+}++/// The entries removed.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RemoveFromPipelineResponse {+ /// Each removed entry as it was.+ pub removed: Vec<ToolEntry>,+ /// The pipeline's version after the change.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub version: Option<i64>,+ /// What changed.+ pub summary: String,+}++impl ToolAnnotated for RemoveFromPipeline {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Remove from pipeline");+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for RemoveFromPipeline+{+ type Output = RemoveFromPipelineResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let targets = self+ .entry_ids+ .iter()+ .map(|id| EntryTarget::Entry(RowId::from_uuid(*id)))+ .chain(self.record_ids.iter().map(|id| EntryTarget::Record(*id)))+ .collect();+ let viewer = context.viewer(request_context.user_id);+ let removed = context+ .service+ .remove(&viewer, self.pipeline_id, targets)+ .await+ .map_err(workflow_error)?;+ let entries: Vec<ToolEntry> = removed.removed.iter().map(ToolEntry::from).collect();+ let summary = match entries.as_slice() {+ [] => "Removed nothing.".to_owned(),+ entries => format!(+ "Removed {} from the pipeline; the records stay in the CRM.",+ entries+ .iter()+ .map(|entry| record_name(&entry.record))+ .collect::<Vec<_>>()+ .join(", ")+ ),+ };+ Ok(RemoveFromPipelineResponse {+ removed: entries,+ version: removed.version.map(|version| version.0),+ summary,+ })+ }+}diff --git a/crates/crm/src/inbound/toolset/pipelines/test.rs b/crates/crm/src/inbound/toolset/pipelines/test.rsnew file mode 100644index 0000000000..a9866bdb21--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/test.rs@@ -0,0 +1,85 @@+use ai_toolset::schema::generate_validated_input_schema;++use super::*;++#[test]+fn every_pipeline_tool_schema_is_valid_for_strict_tool_use() {+ for (name, validated) in [+ (+ "ListPipelines",+ generate_validated_input_schema::<ListPipelines>(),+ ),+ (+ "FindPipelineEntries",+ generate_validated_input_schema::<FindPipelineEntries>(),+ ),+ (+ "AddToPipeline",+ generate_validated_input_schema::<AddToPipeline>(),+ ),+ (+ "UpdatePipelineEntries",+ generate_validated_input_schema::<UpdatePipelineEntries>(),+ ),+ (+ "RemoveFromPipeline",+ generate_validated_input_schema::<RemoveFromPipeline>(),+ ),+ (+ "CreatePipeline",+ generate_validated_input_schema::<CreatePipeline>(),+ ),+ (+ "EditPipeline",+ generate_validated_input_schema::<EditPipeline>(),+ ),+ ] {+ let validated = validated.unwrap_or_else(|error| panic!("{name}: {error}"));+ assert_eq!(validated.name, name);+ // The deferred-tool catalog shows only the first sentence: it must+ // say what CRM users call these things.+ let first = validated.description.split(". ").next().unwrap_or_default();+ assert!(+ ["pipeline", "deal"].iter().any(|word| first.contains(word)),+ "{name}: {first}"+ );+ }+}++#[test]+fn a_field_value_is_one_value_several_or_empty() {+ let value = |value: Option<&str>, values: Option<Vec<&str>>| ToolFieldValue {+ field: "Stage".into(),+ value: value.map(Into::into),+ values: values.map(|values| values.into_iter().map(Into::into).collect()),+ };+ assert_eq!(+ value(Some("Demo"), None).pair().1,+ FieldInput::One("Demo".into())+ );+ assert_eq!(+ value(Some("Demo"), Some(vec!["Demo", "Trial"])).pair().1,+ FieldInput::Many(vec!["Demo".into(), "Trial".into()])+ );+ assert_eq!(value(None, Some(Vec::new())).pair().1, FieldInput::Clear);+ assert_eq!(value(None, None).pair().1, FieldInput::Clear);+}++#[test]+fn single_values_read_plainly_and_several_as_lists() {+ assert_eq!(+ json(&FieldValue::Labels(vec!["Demo".into()])),+ serde_json::json!("Demo")+ );+ assert_eq!(+ json(&FieldValue::References(vec![+ "macro|[email protected]".into(),+ "macro|[email protected]".into()+ ])),+ serde_json::json!(["macro|[email protected]", "macro|[email protected]"])+ );+ assert_eq!(+ json(&FieldValue::Number(48_000.0)),+ serde_json::json!(48_000.0)+ );+}diff --git a/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rs b/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rsnew file mode 100644index 0000000000..f78a1377cb--- /dev/null+++ b/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rs@@ -0,0 +1,188 @@+//! UpdatePipelineEntries: move deals between stages and change their fields.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use databases::domain::models::{RowId, TableVersion};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{+ PipelineToolContext, ToolFieldValue, ToolRecord, json, pairs, record_name, workflow_error,+};+use crate::domain::pipeline_workflows::{EntryTarget, EntryUpdate, PipelineWorkflowService};++/// The changes to one entry.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolEntryUpdate {+ /// The entry's id.+ #[schemars(description = "The entry's id from FindPipelineEntries. Give this or recordId.")]+ #[serde(default)]+ pub entry_id: Option<Uuid>,+ /// The tracked record's id.+ #[schemars(+ description = "Instead of entryId: the CRM company or contact id the entry tracks. Refused if the record has several entries in this pipeline; then use entryId."+ )]+ #[serde(default)]+ pub record_id: Option<Uuid>,+ /// Fields to set.+ #[schemars(+ description = "Fields to set, e.g. [{\"field\": \"Stage\", \"value\": \"Negotiation\"}, {\"field\": \"Revenue\", \"value\": \"48000\"}]. Leave value out to empty a field."+ )]+ pub set: Vec<ToolFieldValue>,+}++/// Change entries of a pipeline.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "UpdatePipelineEntries",+ description = "Move deals to another stage or change their fields in a CRM pipeline: \"move Acme to Negotiation\", \"set the revenue on the Globex deal\", \"assign these deals to Sam\". Address each entry by entryId (from FindPipelineEntries) or by the company or contact id it tracks, and set fields by name with text values: stages and other options by label, people as \"me\", an email or a macro| user id, numbers, true/false, or dates. Several entries change in one call, all or nothing. Returns each field before and after. This changes the entry in the pipeline, not the company's own properties."+)]+pub struct UpdatePipelineEntries {+ /// The pipeline.+ #[schemars(description = "The pipeline's id from ListPipelines.")]+ pub pipeline_id: Uuid,+ /// What to change.+ #[schemars(description = "The entries to change, each with its fields to set.")]+ pub updates: Vec<ToolEntryUpdate>,+ /// The version the change is based on.+ #[schemars(+ description = "Optional: the pipeline version from the FindPipelineEntries read these changes are based on. The update is refused if the pipeline changed since; leave out for a direct change."+ )]+ #[serde(default)]+ pub base_version: Option<i64>,+}++/// One field's value before and after.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolFieldChange {+ /// The field.+ pub field: String,+ /// Its value before; null when it was empty.+ pub before: serde_json::Value,+ /// Its value now; null when it is empty.+ pub after: serde_json::Value,+}++/// An updated entry.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolUpdatedEntry {+ /// The entry.+ pub entry_id: Uuid,+ /// The company or contact it tracks.+ pub record: ToolRecord,+ /// The fields set.+ pub changes: Vec<ToolFieldChange>,+}++/// The entries changed.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct UpdatePipelineEntriesResponse {+ /// Each changed entry, as saved.+ pub updated: Vec<ToolUpdatedEntry>,+ /// The pipeline's version after the change.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub version: Option<i64>,+ /// What changed.+ pub summary: String,+}++impl ToolAnnotated for UpdatePipelineEntries {+ // Destructive: a set overwrites the value that was there.+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Update pipeline entries").with_idempotent();+}++#[async_trait]+impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows>>+ for UpdatePipelineEntries+{+ type Output = UpdatePipelineEntriesResponse;++ #[tracing::instrument(skip_all, fields(user_id = ?request_context.user_id), err)]+ async fn call(+ &self,+ context: ServiceContext<PipelineToolContext<Workflows>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let updates = self+ .updates+ .iter()+ .map(|update| {+ let target = match (update.entry_id, update.record_id) {+ (Some(entry), None) => EntryTarget::Entry(RowId::from_uuid(entry)),+ (None, Some(record)) => EntryTarget::Record(record),+ _ => {+ return Err(ToolCallError {+ description: "Give each update exactly one of entryId or recordId."+ .to_owned(),+ internal_error: anyhow::anyhow!("update without one target"),+ });+ }+ };+ Ok(EntryUpdate {+ target,+ set: pairs(&update.set),+ })+ })+ .collect::<Result<Vec<_>, _>>()?;+ let viewer = context.viewer(request_context.user_id);+ let updated = context+ .service+ .update(+ &viewer,+ self.pipeline_id,+ updates,+ self.base_version.map(TableVersion),+ )+ .await+ .map_err(workflow_error)?;+ let entries: Vec<ToolUpdatedEntry> = updated+ .updated+ .iter()+ .map(|entry| ToolUpdatedEntry {+ entry_id: entry.entry_id.into_uuid(),+ record: (&entry.record).into(),+ changes: entry+ .changes+ .iter()+ .map(|change| ToolFieldChange {+ field: change.field.clone(),+ before: change.before.as_ref().map_or(serde_json::Value::Null, json),+ after: change.after.as_ref().map_or(serde_json::Value::Null, json),+ })+ .collect(),+ })+ .collect();+ let summary = format!(+ "Updated {}.",+ entries+ .iter()+ .map(|entry| {+ let fields: Vec<String> = entry+ .changes+ .iter()+ .map(|change| {+ format!("{} {} → {}", change.field, change.before, change.after)+ })+ .collect();+ format!("{} ({})", record_name(&entry.record), fields.join("; "))+ })+ .collect::<Vec<_>>()+ .join(", ")+ );+ Ok(UpdatePipelineEntriesResponse {+ updated: entries,+ version: updated.version.map(|version| version.0),+ summary,+ })+ }+}diff --git a/crates/crm/tests/pipeline_workflows.rs b/crates/crm/tests/pipeline_workflows.rsnew file mode 100644index 0000000000..5b8c269cfc--- /dev/null+++ b/crates/crm/tests/pipeline_workflows.rs@@ -0,0 +1,683 @@+//! Pipeline workflows as an agent drives them: records and fields by name,+//! through the real pipeline, CRM and access services.+#![cfg(feature = "outbound")]++use crm::domain::{+ auth::CrmTeamReceipt,+ model::CrmError,+ pipeline_workflows::*,+ pipelines::{PipelineError, PipelineRecordType, PipelineServiceImpl, PipelineSharing},+ service::CrmServiceImpl,+ stages::*,+};+use crm::outbound::{+ companies_repo::CompaniesRepositoryImpl, no_op_resolver::NoOpCompanyMetadataResolver,+ pipelines::PgPipelineRepo,+};+use databases::domain::models::{DatabaseError, Viewer};+use databases::outbound::{+ gateway_event_publisher::NoOpTableEventPublisher, pg_cell_store::PgCellStore,+};+use databases::wiring::{PgDatabasesService, build_service};+use entity_access::{+ domain::{models::*, service::EntityAccessServiceImpl},+ outbound::PgAccessRepository,+};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_event_broker::NoopMacroEventBroker;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use properties::PropertiesPgRepo;+use sqlx::PgPool;+use std::sync::Arc;+use uuid::Uuid;++const OWNER: &str = "macro|[email protected]";+const MEMBER: &str = "macro|[email protected]";+type Access = EntityAccessServiceImpl<PgAccessRepository>;+type DatabaseService = PgDatabasesService<NoOpTableEventPublisher, NoopMacroEventBroker, Access>;+type Pipelines = PipelineServiceImpl<+ PgPipelineRepo<PgCellStore<PropertiesPgRepo>>,+ DatabaseService,+ Access,+ Stages,+>;+type Crm = CrmServiceImpl<CompaniesRepositoryImpl, NoOpCompanyMetadataResolver>;+type Workflows = PipelineWorkflowServiceImpl<Pipelines, Crm, Access>;++/// The team's stage template: new pipelines copy it.+struct Stages;+impl StageDefinitionStore for Stages {+ async fn get_team_stage_set(+ &self,+ _: &CrmTeamReceipt<MemberTeamRole>,+ ) -> Result<Option<TeamStageSet>, CrmError> {+ Ok(Some(TeamStageSet {+ definition_id: Uuid::nil(),+ stages: ["Prospect", "Demo", "Won"]+ .into_iter()+ .enumerate()+ .map(|(order, label)| TeamStage {+ id: Uuid::nil(),+ label: label.into(),+ display_order: order as i32,+ })+ .collect(),+ }))+ }+ async fn create_team_stage_set(+ &self,+ _: &CrmTeamReceipt<MemberTeamRole>,+ _: &[String],+ ) -> Result<TeamStageSet, CrmError> {+ unreachable!("workflows never edit the template")+ }+ async fn replace_stages(+ &self,+ _: &CrmTeamReceipt<MemberTeamRole>,+ _: Uuid,+ _: StageReplacePlan,+ ) -> Result<TeamStageSet, CrmError> {+ unreachable!("workflows never edit the template")+ }+ async fn delete_team_stage_set(+ &self,+ _: &CrmTeamReceipt<MemberTeamRole>,+ _: Uuid,+ ) -> Result<(), CrmError> {+ unreachable!("workflows never edit the template")+ }+}++fn viewer(id: &str) -> Viewer {+ Viewer {+ user_id: MacroUserIdStr::parse_from_str(id).unwrap().into_owned(),+ acting_bot: Some(bot_id::MACRO_AI_BOT_ID),+ }+}++struct Fixture {+ workflows: Workflows,+ acme: Uuid,+ globex: Uuid,+ sam: Uuid,+}++async fn fixture(pool: &PgPool) -> Fixture {+ for id in [OWNER, MEMBER] {+ let uid = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$2)",+ uid,+ id+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1,$1,$2)"#,+ id,+ uid+ )+ .execute(pool)+ .await+ .unwrap();+ }+ let team = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Sales', $2)",+ team,+ OWNER+ )+ .execute(pool)+ .await+ .unwrap();+ for id in [OWNER, MEMBER] {+ sqlx::query!(+ "INSERT INTO team_user (team_id, user_id, team_role) VALUES ($1, $2, 'member')",+ team,+ id+ )+ .execute(pool)+ .await+ .unwrap();+ }+ sqlx::query!(+ "INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, true)",+ team+ )+ .execute(pool)+ .await+ .unwrap();+ let company = async |name: &str, domain: &str| {+ let id = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO crm_companies (id, team_id, custom_name, first_interaction, last_interaction)+ VALUES ($1, $2, $3, now(), now())",+ id,+ team,+ name+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ "INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)",+ id,+ team,+ domain+ )+ .execute(pool)+ .await+ .unwrap();+ id+ };+ let acme = company("Acme", "acme.com").await;+ let globex = company("Globex", "globex.com").await;+ let sam = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO crm_contacts (id, company_id, email, name, first_interaction, last_interaction)+ VALUES ($1, $2, '[email protected]', 'Sam Lee', now(), now())",+ sam,+ acme+ )+ .execute(pool)+ .await+ .unwrap();++ let access = Arc::new(Access::new(PgAccessRepository::new(pool.clone())));+ let databases = Arc::new(build_service(+ pool.clone(),+ access.clone(),+ NoOpTableEventPublisher,+ NoopMacroEventBroker,+ ));+ let pipelines = Pipelines::new(+ PgPipelineRepo::new(+ pool.clone(),+ PgCellStore::new(pool.clone(), PropertiesPgRepo::new(pool.clone())),+ ),+ databases,+ access.clone(),+ Stages,+ );+ let crm = Crm::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ Fixture {+ workflows: Workflows::new(Arc::new(pipelines), Arc::new(crm), access),+ acme,+ globex,+ sam,+ }+}++fn one(value: &str) -> FieldInput {+ FieldInput::One(value.into())+}++fn set(field: &str, value: &str) -> (String, FieldInput) {+ (field.into(), one(value))+}++fn field<'a>(entry: &'a PipelineEntryView, name: &str) -> Option<&'a FieldValue> {+ entry+ .fields+ .iter()+ .find(|(field, _)| field == name)+ .map(|(_, value)| value)+}++fn labels(value: &str) -> Option<FieldValue> {+ Some(FieldValue::Labels(vec![value.into()]))+}++async fn sales(workflows: &Workflows, sharing: PipelineSharing) -> PipelineOverview {+ workflows+ .create(+ &viewer(OWNER),+ NewPipeline {+ name: "Sales".into(),+ record_type: PipelineRecordType::Company,+ sharing,+ stages: Vec::new(),+ fields: Vec::new(),+ },+ )+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {+ let Fixture {+ workflows,+ acme,+ globex,+ ..+ } = fixture(&pool).await;+ let owner = viewer(OWNER);+ let sales = sales(&workflows, PipelineSharing::Team).await;+ let id = sales.pipeline.pipeline.id;+ assert_eq!(+ sales+ .fields+ .iter()+ .map(|f| f.name.as_str())+ .collect::<Vec<_>>(),+ ["Company", "Stage", "Owner", "Revenue"]+ );++ let added = workflows+ .add(+ &owner,+ id,+ vec![+ EntryAddition {+ record: RecordTarget::Id(acme),+ set: vec![+ set("stage", "prospect"),+ set("Owner", "me"),+ set("Revenue", "$48,000"),+ ],+ },+ EntryAddition {+ record: RecordTarget::Id(globex),+ set: Vec::new(),+ },+ ],+ false,+ )+ .await+ .unwrap();+ assert_eq!(added.added.len(), 2);+ let acme_entry = &added.added[0];+ assert_eq!(acme_entry.record.name.as_deref(), Some("Acme"));+ assert_eq!(acme_entry.record.detail.as_deref(), Some("acme.com"));+ assert_eq!(field(acme_entry, "Stage"), labels("Prospect").as_ref());+ assert_eq!(+ field(acme_entry, "Owner"),+ Some(&FieldValue::References(vec![OWNER.into()]))+ );+ assert_eq!(+ field(acme_entry, "Revenue"),+ Some(&FieldValue::Number(48_000.0))+ );++ // A record already in the pipeline is reported, not added twice.+ let again = workflows+ .add(+ &owner,+ id,+ vec![EntryAddition {+ record: RecordTarget::Id(acme),+ set: Vec::new(),+ }],+ false,+ )+ .await+ .unwrap();+ assert!(again.added.is_empty());+ assert_eq!(again.already_present[0].entry_id, acme_entry.entry_id);++ let query = |filters, search: Option<&str>| EntryQuery {+ filters,+ search: search.map(Into::into),+ limit: 50,+ ..Default::default()+ };+ let prospects = workflows+ .find(&owner, id, query(vec![set("Stage", "Prospect")], None))+ .await+ .unwrap();+ assert_eq!(prospects.matched, 1);+ assert!(prospects.complete);+ assert_eq!(prospects.entries[0].record.id, acme);+ let all = workflows+ .find(&owner, id, query(Vec::new(), None))+ .await+ .unwrap();+ assert_eq!(all.matched, 2);+ let stages = all.counts.iter().find(|c| c.field == "Stage").unwrap();+ assert_eq!(+ stages.counts,+ [+ (String::from("Prospect"), 1),+ (String::from("Demo"), 0),+ (String::from("Won"), 0)+ ]+ );+ assert_eq!(stages.empty, 1);+ assert_eq!(all.totals, [(String::from("Revenue"), 48_000.0)]);+ let found = workflows+ .find(&owner, id, query(Vec::new(), Some("GLOB")))+ .await+ .unwrap();+ assert_eq!(found.entries.len(), 1);+ assert_eq!(found.entries[0].record.id, globex);+ let mine = workflows+ .find(&owner, id, query(vec![set("Owner", "me")], None))+ .await+ .unwrap();+ assert_eq!(mine.matched, 1);+ assert!(matches!(+ workflows.find(&owner, id, query(vec![set("Stage", "Closed")], None)).await,+ Err(WorkflowError::Invalid(message)) if message.contains("Prospect, Demo, Won")+ ));++ // Move Acme by the record it tracks; the change reports before and after.+ let moved = workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Record(acme),+ set: vec![set("Stage", "Won")],+ }],+ None,+ )+ .await+ .unwrap();+ let change = &moved.updated[0].changes[0];+ assert_eq!(change.before, labels("Prospect"));+ assert_eq!(change.after, labels("Won"));+ assert_eq!(moved.updated[0].record.name.as_deref(), Some("Acme"));+ // Every write is the user's, made by the agent acting for them.+ let changes = sqlx::query!(+ "SELECT actor, acting_bot FROM database_changes WHERE database_id = $1",+ sales.pipeline.pipeline.database_id.into_uuid()+ )+ .fetch_all(&pool)+ .await+ .unwrap();+ assert!(!changes.is_empty());+ for change in changes {+ assert_eq!(change.actor.as_deref(), Some(OWNER));+ assert_eq!(change.acting_bot, Some(bot_id::MACRO_AI_BOT_ID.to_string()));+ }+ // A write based on a stale read is refused.+ assert!(matches!(+ workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Record(acme),+ set: vec![set("Stage", "Demo")],+ }],+ Some(all.pipeline.version),+ )+ .await,+ Err(WorkflowError::Pipeline(PipelineError::Database(+ DatabaseError::VersionConflict+ )))+ ));+ assert!(matches!(+ workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Record(acme),+ set: vec![set("Company", "anything")],+ }],+ None,+ )+ .await,+ Err(WorkflowError::Invalid(_))+ ));++ // The record's entries across pipelines, by id or by name.+ let everywhere = workflows.record_entries(&owner, &[acme]).await.unwrap();+ assert_eq!(everywhere.len(), 1);+ assert_eq!(+ field(&everywhere[0].entries[0], "Stage"),+ labels("Won").as_ref()+ );+ let by_name = workflows.search_entries(&owner, "acme", 50).await.unwrap();+ assert_eq!(by_name.len(), 1);+ assert_eq!(by_name[0].entries[0].record.id, acme);+ assert!(+ workflows+ .search_entries(&owner, "nobody", 50)+ .await+ .unwrap()+ .is_empty()+ );++ let removed = workflows+ .remove(&owner, id, vec![EntryTarget::Record(globex)])+ .await+ .unwrap();+ assert_eq!(removed.removed[0].record.id, globex);+ let left = workflows+ .find(&owner, id, query(Vec::new(), None))+ .await+ .unwrap();+ assert_eq!(left.matched, 1);+ assert!(matches!(+ workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Record(globex),+ set: vec![set("Stage", "Won")],+ }],+ None,+ )+ .await,+ Err(WorkflowError::Invalid(message)) if message.contains("AddToPipeline")+ ));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn contacts_are_added_by_email_and_a_record_with_two_deals_needs_an_entry_id(pool: PgPool) {+ let Fixture {+ workflows,+ acme,+ sam,+ ..+ } = fixture(&pool).await;+ let owner = viewer(OWNER);+ let people = workflows+ .create(+ &owner,+ NewPipeline {+ name: "Partners".into(),+ record_type: PipelineRecordType::Contact,+ sharing: PipelineSharing::Private,+ stages: Vec::new(),+ fields: Vec::new(),+ },+ )+ .await+ .unwrap();+ let added = workflows+ .add(+ &owner,+ people.pipeline.pipeline.id,+ vec![EntryAddition {+ record: RecordTarget::Email("[email protected]".into()),+ set: Vec::new(),+ }],+ false,+ )+ .await+ .unwrap();+ assert_eq!(added.added[0].record.id, sam);+ assert_eq!(added.added[0].record.name.as_deref(), Some("Sam Lee"));++ // In a company pipeline, a contact's email adds its company.+ let sales = sales(&workflows, PipelineSharing::Private).await;+ let id = sales.pipeline.pipeline.id;+ let email = || EntryAddition {+ record: RecordTarget::Email("[email protected]".into()),+ set: Vec::new(),+ };+ let added = workflows+ .add(&owner, id, vec![email()], false)+ .await+ .unwrap();+ assert_eq!(added.added[0].record.id, acme);+ let second = workflows+ .add(&owner, id, vec![email()], true)+ .await+ .unwrap();+ assert_eq!(second.added.len(), 1);+ assert!(matches!(+ workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Record(acme),+ set: vec![set("Stage", "Demo")],+ }],+ None,+ )+ .await,+ Err(WorkflowError::Invalid(message)) if message.contains("entryId")+ ));+ workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Entry(second.added[0].entry_id),+ set: vec![set("Stage", "Demo")],+ }],+ None,+ )+ .await+ .unwrap();+ assert!(matches!(+ workflows+ .add(+ &owner,+ id,+ vec![EntryAddition {+ record: RecordTarget::Id(Uuid::now_v7()),+ set: Vec::new(),+ }],+ false,+ )+ .await,+ Err(WorkflowError::Invalid(message)) if message.contains("ListCompanies")+ ));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pipelines_are_created_with_stages_and_edited_by_name(pool: PgPool) {+ let Fixture { workflows, .. } = fixture(&pool).await;+ let owner = viewer(OWNER);+ let hiring = workflows+ .create(+ &owner,+ NewPipeline {+ name: "Hiring".into(),+ record_type: PipelineRecordType::Contact,+ sharing: PipelineSharing::Team,+ stages: vec!["Sourced".into(), "Interview".into(), "Hired".into()],+ fields: vec![+ NewField {+ name: "Notes".into(),+ kind: NewFieldKind::Text,+ options: Vec::new(),+ },+ NewField {+ name: "Priority".into(),+ kind: NewFieldKind::Select,+ options: vec!["High".into(), "Low".into()],+ },+ ],+ },+ )+ .await+ .unwrap();+ let id = hiring.pipeline.pipeline.id;+ let options = |overview: &PipelineOverview, name: &str| -> Vec<String> {+ overview+ .field(name)+ .unwrap()+ .options+ .iter()+ .map(|(_, label)| label.clone())+ .collect()+ };+ assert_eq!(options(&hiring, "Stage"), ["Sourced", "Interview", "Hired"]);+ assert_eq!(options(&hiring, "Priority"), ["High", "Low"]);++ let edited = workflows+ .edit(+ &owner,+ id,+ PipelineEdit {+ name: Some("Hiring 2026".into()),+ rename_fields: vec![("notes".into(), "Summary".into())],+ add_options: vec![("Stage".into(), vec!["Offer".into()])],+ rename_options: vec![("Stage".into(), "hired".into(), "Joined".into())],+ remove_options: vec![("Stage".into(), "Interview".into())],+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(edited.pipeline.pipeline.name, "Hiring 2026");+ assert_eq!(options(&edited, "Stage"), ["Sourced", "Joined", "Offer"]);+ assert!(edited.field("Summary").is_ok());+ assert!(matches!(+ workflows+ .edit(+ &owner,+ id,+ PipelineEdit {+ remove_fields: vec!["Contact".into()],+ ..Default::default()+ },+ )+ .await,+ Err(WorkflowError::Invalid(_))+ ));++ // A team member may edit a shared pipeline, but only its owner shares it.+ let member = viewer(MEMBER);+ assert_eq!(workflows.pipelines(&member).await.unwrap().len(), 1);+ assert!(matches!(+ workflows+ .edit(+ &member,+ id,+ PipelineEdit {+ name: Some("Renamed by a member".into()),+ add_options: vec![("Stage".into(), vec!["Rejected".into()])],+ sharing: Some(PipelineSharing::Private),+ ..Default::default()+ },+ )+ .await,+ Err(WorkflowError::Invalid(message)) if message.contains("owner")+ ));+ // The refusal comes before any write: nothing of that edit landed.+ let unchanged = &workflows.pipelines(&member).await.unwrap()[0];+ assert_eq!(unchanged.pipeline.pipeline.name, "Hiring 2026");+ assert_eq!(options(unchanged, "Stage"), ["Sourced", "Joined", "Offer"]);+ workflows+ .edit(+ &owner,+ id,+ PipelineEdit {+ sharing: Some(PipelineSharing::Private),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert!(workflows.pipelines(&member).await.unwrap().is_empty());+ assert!(+ workflows+ .find(&member, id, EntryQuery::default())+ .await+ .is_err()+ );+}diff --git a/crates/crm/tests/pipelines.rs b/crates/crm/tests/pipelines.rsindex b87b3cc893..9ecfd8e05b 100644--- a/crates/crm/tests/pipelines.rs+++ b/crates/crm/tests/pipelines.rs@@ -203,6 +203,7 @@ async fn write() -> Result<Vec<OpResult>, PipelineError> {s.apply_ops(access(a, p.id, EntityType::CrmPipeline, OWNER).await,+ None,ops.into(),).awaitdiff --git a/crates/prompt/src/crm_pipelines.md b/crates/prompt/src/crm_pipelines.mdnew file mode 100644index 0000000000..a91b4c4fc0--- /dev/null+++ b/crates/prompt/src/crm_pipelines.md@@ -0,0 +1,11 @@+## How CRM pipelines work++A pipeline is a board of deals. Each entry tracks one CRM company or contact and has its own fields: usually Stage, Owner and Revenue, plus any the team added. "Deal", "opportunity", "lead", "the pipeline", "move Acme to Negotiation" and "who's in Demo" all refer to pipeline entries. A pipeline is not a Macro database: use the pipeline tools for it, never `ListDatabases` or `QueryDatabase`.++1. Find the pipeline: `ListPipelines` gives each pipeline's id, whether it tracks companies or contacts, and its fields with their options; Stage lists the stages in order. If the user names no pipeline and there is one, use it; if several could match, ask.+2. Read: `FindPipelineEntries` filters by field values and by company or contact name, and returns the count per stage and the total of each number field over every match. Answer counts and sums from those. To find which pipelines and stages a company or contact is in, leave out `pipelineId` and pass its name as `search` (or its `recordIds`).+3. Change: `UpdatePipelineEntries` moves entries between stages and sets fields by name, naming each entry by its `entryId` or by the company or contact it tracks. `AddToPipeline` adds companies (ids from `ListCompanies`) or contacts (by email). Remove entries with `RemoveFromPipeline` only when asked; the company or contact stays in the CRM. `EditPipeline` adds, renames or removes stages (the Stage field's options) and other fields. `CreatePipeline` makes a new pipeline only when the user asks for one.+4. Use the pipeline's exact field names and stage labels. If a requested stage does not exist, say so and offer to add it; never silently pick a similar one. Name people as "me", an email address, or a macro| user id; never guess a person.+5. Check the tool result, such as each field's value before and after, before saying a change is saved.++A company also has its own Stage, Owner and Revenue properties on its CRM page. They are separate from every pipeline and not kept in sync with it. When the user has pipelines, deal and stage requests mean pipeline entries; change the company's own properties with `SetEntityProperty` only when the user asks for those properties specifically.diff --git a/crates/prompt/src/crm_pipelines.rs b/crates/prompt/src/crm_pipelines.rsnew file mode 100644index 0000000000..73c21d4b0c--- /dev/null+++ b/crates/prompt/src/crm_pipelines.rs@@ -0,0 +1,14 @@+//! How agents work with CRM pipelines: the deal vocabulary users speak and+//! the pipeline tools that carry it out.++use crate::types::StaticPrompt;++/// Instructions for the CRM pipeline tools.+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(+ "CRM pipelines",+ include_str!("crm_pipelines.md"),+ "Map deal, stage and pipeline requests to pipeline entries, find them by name, change them by field name and stage label, verify the saved values, and keep pipeline stages apart from a company's own properties.",+);++#[cfg(test)]+mod test;diff --git a/crates/prompt/src/crm_pipelines/test.rs b/crates/prompt/src/crm_pipelines/test.rsnew file mode 100644index 0000000000..959cf4cfdf--- /dev/null+++ b/crates/prompt/src/crm_pipelines/test.rs@@ -0,0 +1,40 @@+use crate::{+ DATABASE_TOOL_USE_PROMPT, DIRECT_TOOL_USE_PROMPT, SESSION_TOOL_USE_PROMPT, TOOL_USE_PROMPT,+ mcp_instructions,+};++#[test]+fn every_agent_host_maps_deal_requests_to_the_pipeline_tools() {+ for text in [+ DIRECT_TOOL_USE_PROMPT.to_string(),+ SESSION_TOOL_USE_PROMPT.to_string(),+ TOOL_USE_PROMPT.to_string(),+ mcp_instructions("https://macro.com"),+ ] {+ for guidance in [+ "ListPipelines",+ "FindPipelineEntries",+ "UpdatePipelineEntries",+ "AddToPipeline",+ "RemoveFromPipeline",+ "EditPipeline",+ "CreatePipeline",+ "not a Macro database",+ "SetEntityProperty",+ ] {+ assert!(+ text.contains(guidance),+ "missing pipeline guidance: {guidance}"+ );+ }+ }+}++#[test]+fn the_database_only_assistant_has_no_pipeline_tools_to_describe() {+ assert!(+ !DATABASE_TOOL_USE_PROMPT+ .to_string()+ .contains("ListPipelines")+ );+}diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex f6547d8415..d185eca8a6 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -12,6 +12,7 @@ pub mod channel_mention;pub mod citations;pub mod coding_agents;pub mod connected_toolsets;+pub mod crm_pipelines;pub mod databases;pub mod deferred_tools;pub mod do_not;@@ -47,6 +48,7 @@ pub static BASE_PROMPT: ComposedPrompt = tone::PROMPTpub static DIRECT_TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT.compose(&tool_usage::PROMPT).compose(&databases::PROMPT)+ .compose(&crm_pipelines::PROMPT).compose(&skills::PROMPT).compose(&document_content_links::PROMPT).compose(&email::PROMPT);@@ -58,6 +60,7 @@ pub static DIRECT_TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPTpub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT.compose(&tool_usage::PROMPT).compose(&databases::PROMPT)+ .compose(&crm_pipelines::PROMPT).compose(&user_tools::PROMPT).compose(&skills::PROMPT).compose(&document_content_links::PROMPT)@@ -70,6 +73,7 @@ pub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPTpub static SESSION_TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT.compose(&tool_usage::PROMPT).compose(&databases::PROMPT)+ .compose(&crm_pipelines::PROMPT).compose(&user_tools::SESSION_PROMPT).compose(&skills::PROMPT).compose(&document_content_links::PROMPT)@@ -100,6 +104,7 @@ static MCP_STATIC_INSTRUCTIONS: ComposedPrompt = citations::PROMPT.compose(&do_not::PROMPT).compose(&about_macro::PROMPT).compose(&databases::PROMPT)+ .compose(&crm_pipelines::PROMPT).compose(&document_content_links::PROMPT);/// Builds the instructions surfaced to external MCP clients via the serverdiff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rsindex d4d21c5100..0397dcccb9 100644--- a/crates/properties/src/inbound/toolset/set_entity_property.rs+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs@@ -56,7 +56,7 @@ A task can belong to one project:- Project (00000001-0000-0000-0000-000000000014): entity, single. Use entity_ref with entity_type='initiative' and the project UUID; send no value field to remove the task from its project. Setting it requires edit access to the task and the project, and the project's agents are assigned to the task.CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties:-- Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids.+- Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids. This is the company's own Stage, not a deal's stage in a CRM pipeline: move pipeline deals with UpdatePipelineEntries.- Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'.- Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars).Any member of the owning team can edit visible company properties; hidden records remain admin/owner-only.diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.mdindex a8644ce882..071fcbe288 100644--- a/docs/AGENT_GUIDE/databases.md+++ b/docs/AGENT_GUIDE/databases.md@@ -103,6 +103,21 @@ adapter and shared provider against local test responses.Pipelines poll every five seconds. A poll that returns unchanged data must notremount company previews or request them again.+### Pipelines from AI chat++Chats and agent sessions manage pipelines with their own tools, not the database+tools: `ListPipelines`, `FindPipelineEntries`, `AddToPipeline`,+`UpdatePipelineEntries`, `RemoveFromPipeline`, `CreatePipeline`, and `EditPipeline`.+They address entries by the company or contact they track, fields by name, and+stages by label, so "move Acme to Negotiation in Sales" or "how many deals are in+Demo?" work without ids. Each tool row shows a kanban icon and expands to the+entries it read or changed; an update lists every field before and after.+To verify, ask a chat to move a company between stages and check that the pipeline+row (within the five-second poll) and the company page's **Pipelines** card both+show the new stage. The company's own Stage, Owner and Revenue properties in the+side panel are a separate field these tools do not change. A pipeline created or+renamed from chat appears in the CRM sidebar as soon as the tool finishes.+## Properties and recordsAn embedded records editor can allow cell edits while its host controls thediff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 0d60907940..3b7361c8e6 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -466,6 +466,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arsoup_service.clone(),pool.clone(),);+ let crm_tool_context = ai_tools::build_crm_tool_context(pool.clone());+ let pipeline_tool_context = ai_tools::build_pipeline_tool_context(+ pool.clone(),+ &databases_tool_context,+ &crm_tool_context,+ );let calendar_tool_context = ai_tools::build_calendar_tool_context(pool.clone(),@@ -553,7 +559,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar),initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(pool.clone()),- crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),+ crm_tool_context,+ pipeline_tool_context,skill_tool_context: ai_tools::build_skill_tool_context(search_service_client.clone(),soup_service.clone(),diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rsindex 496e40dc77..31b4dcf94d 100644--- a/services/document_cognition_service/src/server.rs+++ b/services/document_cognition_service/src/server.rs@@ -706,6 +706,12 @@ pub async fn run() -> anyhow::Result<()> {soup_service.clone(),db.clone(),);+ let crm_tool_context = ai_tools::build_crm_tool_context(db.clone());+ let pipeline_tool_context = ai_tools::build_pipeline_tool_context(+ db.clone(),+ &databases_tool_context,+ &crm_tool_context,+ );let calendar_tool_context = ai_tools::build_calendar_tool_context(db.clone(),@@ -792,7 +798,8 @@ pub async fn run() -> anyhow::Result<()> {),initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(db.clone()),- crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),+ crm_tool_context,+ pipeline_tool_context,skill_tool_context: ai_tools::build_skill_tool_context(search_service_client.clone(),soup_service.clone(),diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex d31e11f988..4d70471c02 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -441,6 +441,12 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Tosoup_service.clone(),db.clone(),);+ let crm_tool_context = ai_tools::build_crm_tool_context(db.clone());+ let pipeline_tool_context = ai_tools::build_pipeline_tool_context(+ db.clone(),+ &databases_tool_context,+ &crm_tool_context,+ );let calendar_tool_context = ai_tools::build_calendar_tool_context(db.clone(),@@ -589,7 +595,8 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To),initiative_tool_context,team_tool_context: ai_tools::build_team_tool_context(db.clone()),- crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),+ crm_tool_context,+ pipeline_tool_context,skill_tool_context,schedule_tool_context: ai_tools::build_routine_tool_context()?,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),