Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(mcp): add tools for item actions the app UI offers (#7943)

Jacob Beckerman95c27d1311d3
diff --git a/Cargo.lock b/Cargo.lock
index 7086450b5c..107ac8f89f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -962,6 +962,7 @@ dependencies = [
"entity_access_management",
"entity_registry",
"entity_registry_db_utils",
+ "favorites",
"foreign_entity",
"forms",
"frecency",
@@ -7663,7 +7664,9 @@ checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
name = "favorites"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
"anyhow",
+ "async-trait",
"axum",
"axum-extra",
"chrono",
@@ -7678,6 +7681,7 @@ dependencies = [
"model-error-response",
"model_user",
"rootcause",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/docs/AI/mcp/tools/create-company.mdx b/apps/docs/AI/mcp/tools/create-company.mdx
new file mode 100644
index 0000000000..d8aaf1dfda
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/create-company.mdx
@@ -0,0 +1,17 @@
+---
+title: CreateCompany
+description: >-
+ Add a company to the user's team CRM by name and web domain, as New Company in
+ the CRM does.
+---
+
+# CreateCompany
+
+Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `name` | string | Yes | The company's display name, e.g. "Acme". |
+| `domain` | string | Yes | The company's web domain, e.g. "acme.com" — no scheme or path. Contacts are matched to the company by this domain. |
diff --git a/apps/docs/AI/mcp/tools/create-contact.mdx b/apps/docs/AI/mcp/tools/create-contact.mdx
new file mode 100644
index 0000000000..1f52b133dd
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/create-contact.mdx
@@ -0,0 +1,18 @@
+---
+title: CreateContact
+description: >-
+ Add a contact person to a company in the user's team CRM, as Add Contact on a
+ company does.
+---
+
+# CreateContact
+
+Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `companyId` | string | Yes | The CRM company id to add the contact to. |
+| `name` | string | Yes | The contact's name. |
+| `email` | string | Yes | The contact's email address, e.g. "[email protected]". |
diff --git a/apps/docs/AI/mcp/tools/create-skill.mdx b/apps/docs/AI/mcp/tools/create-skill.mdx
new file mode 100644
index 0000000000..b109ce402c
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/create-skill.mdx
@@ -0,0 +1,18 @@
+---
+title: CreateSkill
+description: >-
+ Create a skill: a markdown document of reusable instructions that AI reads and
+ follows when the skill is referenced, as Compose Skill in the app does.
+---
+
+# CreateSkill
+
+Create a skill: a markdown document of reusable instructions that AI reads and follows when the skill is referenced, as Compose Skill in the app does. Write the instructions as the markdown body. Edit an existing skill with EditDocument; find skills with ListSkills or SearchSkills.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `skillName` | string | Yes | The skill's name. |
+| `markdown` | string | Yes | The skill's instructions, in markdown. |
+| `projectId` | string | No | The id of the project (shown as a folder in the app UI) to create the skill in. Requires edit access to the project. Omit to create it at the top level of the user's files. |
diff --git a/apps/docs/AI/mcp/tools/delete-call-record.mdx b/apps/docs/AI/mcp/tools/delete-call-record.mdx
new file mode 100644
index 0000000000..d7e8bbe3c8
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-call-record.mdx
@@ -0,0 +1,16 @@
+---
+title: DeleteCallRecord
+description: >-
+ Permanently delete a finished call with its recording and transcript, as
+ Delete on a call does.
+---
+
+# DeleteCallRecord
+
+Permanently delete a finished call with its recording and transcript, as Delete on a call does. This cannot be undone. Requires edit access to the call; calls still in progress cannot be deleted. Use only when the user explicitly asks to delete a call.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `callId` | string | Yes | The id of the call to delete. |
diff --git a/apps/docs/AI/mcp/tools/delete-channel-message.mdx b/apps/docs/AI/mcp/tools/delete-channel-message.mdx
new file mode 100644
index 0000000000..75c1c1ba90
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-channel-message.mdx
@@ -0,0 +1,16 @@
+---
+title: DeleteChannelMessage
+description: >-
+ Delete a channel message or thread reply.
+---
+
+# DeleteChannelMessage
+
+Delete a channel message or thread reply. The channel keeps a 'message deleted' placeholder; this cannot be undone. Users can delete their own messages and messages sent by bots; channel admins and owners can delete any message. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user explicitly asks to delete a message.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `channelId` | string | Yes | Channel id containing the message. |
+| `messageId` | string | Yes | Id of the message to delete. |
diff --git a/apps/docs/AI/mcp/tools/delete-document-comment.mdx b/apps/docs/AI/mcp/tools/delete-document-comment.mdx
new file mode 100644
index 0000000000..142266122d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-document-comment.mdx
@@ -0,0 +1,16 @@
+---
+title: DeleteDocumentComment
+description: >-
+ Delete a comment or reply on a document.
+---
+
+# DeleteDocumentComment
+
+Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `documentId` | string | Yes | The id of the document the comment is on. |
+| `commentId` | string | Yes | The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread. |
diff --git a/apps/docs/AI/mcp/tools/delete-routine.mdx b/apps/docs/AI/mcp/tools/delete-routine.mdx
new file mode 100644
index 0000000000..9d1a32061d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-routine.mdx
@@ -0,0 +1,16 @@
+---
+title: DeleteRoutine
+description: >-
+ Permanently delete a routine owned by the authenticated user, stopping all
+ future runs.
+---
+
+# DeleteRoutine
+
+Permanently delete a routine owned by the authenticated user, stopping all future runs. This cannot be undone; to stop it temporarily, pause it with UpdateRoutine instead. Use only when the user explicitly asks to delete a routine.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `routineId` | string | Yes | Routine UUID. |
diff --git a/apps/docs/AI/mcp/tools/duplicate-item.mdx b/apps/docs/AI/mcp/tools/duplicate-item.mdx
new file mode 100644
index 0000000000..f628ee09f8
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/duplicate-item.mdx
@@ -0,0 +1,18 @@
+---
+title: DuplicateItem
+description: >-
+ Make a copy of a document (including a task) or an AI chat, owned by the user,
+ as the Duplicate action in the app does.
+---
+
+# DuplicateItem
+
+Make a copy of a document (including a task) or an AI chat, owned by the user, as the Duplicate action in the app does. Requires view access to the original. Returns the copy's id.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"chat"` | Yes | The kind of item to duplicate. |
+| `entityId` | string | Yes | The id of the item to duplicate. |
+| `name` | string | No | Name for the copy of a document. Omit to use "\<original name> copy". AI chat copies always keep the original name. |
diff --git a/apps/docs/AI/mcp/tools/edit-channel-message.mdx b/apps/docs/AI/mcp/tools/edit-channel-message.mdx
new file mode 100644
index 0000000000..6503193f92
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/edit-channel-message.mdx
@@ -0,0 +1,17 @@
+---
+title: EditChannelMessage
+description: >-
+ Replace the content of an existing channel message or thread reply.
+---
+
+# EditChannelMessage
+
+Replace the content of an existing channel message or thread reply. Only the message's author can edit it, so this edits messages the user sent and messages this assistant sent for them; channel admins and owners may also edit others' messages. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to edit or correct a message.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `channelId` | string | Yes | Channel id containing the message. |
+| `messageId` | string | Yes | Id of the message to edit. |
+| `content` | string | Yes | The full replacement message content in macro markdown format. This replaces the whole message, not a fragment of it. |
diff --git a/apps/docs/AI/mcp/tools/edit-document-comment.mdx b/apps/docs/AI/mcp/tools/edit-document-comment.mdx
new file mode 100644
index 0000000000..6777da16cd
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/edit-document-comment.mdx
@@ -0,0 +1,17 @@
+---
+title: EditDocumentComment
+description: >-
+ Replace the text of a comment or reply on a document.
+---
+
+# EditDocumentComment
+
+Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `documentId` | string | Yes | The id of the document the comment is on. |
+| `commentId` | string | Yes | The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id. |
+| `content` | string | Yes | The full replacement text of the comment, in markdown. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index bfa9038eae..d4e60d9a4a 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -21,26 +21,36 @@ These pages are generated from Macro's Rust MCP tool registry.
- [CreateBot](/AI/mcp/tools/create-bot)
- [CreateCalendarEvent](/AI/mcp/tools/create-calendar-event)
- [CreateChannel](/AI/mcp/tools/create-channel)
+- [CreateCompany](/AI/mcp/tools/create-company)
- [CreateConfirmedCalendarEvent](/AI/mcp/tools/create-confirmed-calendar-event)
+- [CreateContact](/AI/mcp/tools/create-contact)
- [CreateDocument](/AI/mcp/tools/create-document)
- [CreateForm](/AI/mcp/tools/create-form)
- [CreateImportEntity](/AI/mcp/tools/create-import-entity)
- [CreateInitiative](/AI/mcp/tools/create-initiative)
- [CreateProject](/AI/mcp/tools/create-project)
- [CreateRoutine](/AI/mcp/tools/create-routine)
+- [CreateSkill](/AI/mcp/tools/create-skill)
- [CreateTag](/AI/mcp/tools/create-tag)
- [DeleteBot](/AI/mcp/tools/delete-bot)
- [DeleteCalendarEvent](/AI/mcp/tools/delete-calendar-event)
+- [DeleteCallRecord](/AI/mcp/tools/delete-call-record)
+- [DeleteChannelMessage](/AI/mcp/tools/delete-channel-message)
- [DeleteDatabaseView](/AI/mcp/tools/delete-database-view)
+- [DeleteDocumentComment](/AI/mcp/tools/delete-document-comment)
- [DeleteImportEntity](/AI/mcp/tools/delete-import-entity)
- [DeleteInitiative](/AI/mcp/tools/delete-initiative)
+- [DeleteRoutine](/AI/mcp/tools/delete-routine)
- [DeleteTag](/AI/mcp/tools/delete-tag)
- [DescribeDatabase](/AI/mcp/tools/describe-database)
- [DiscoverConnectors](/AI/mcp/tools/discover-connectors)
- [DispatchCodingAgent](/AI/mcp/tools/dispatch-coding-agent)
- [DisplayResults](/AI/mcp/tools/display-results)
+- [DuplicateItem](/AI/mcp/tools/duplicate-item)
- [EditBookingLink](/AI/mcp/tools/edit-booking-link)
+- [EditChannelMessage](/AI/mcp/tools/edit-channel-message)
- [EditDocument](/AI/mcp/tools/edit-document)
+- [EditDocumentComment](/AI/mcp/tools/edit-document-comment)
- [EditForm](/AI/mcp/tools/edit-form)
- [EditPresentation](/AI/mcp/tools/edit-presentation)
- [EditSpreadsheet](/AI/mcp/tools/edit-spreadsheet)
@@ -82,8 +92,12 @@ These pages are generated from Macro's Rust MCP tool registry.
- [MarkNotificationsDone](/AI/mcp/tools/mark-notifications-done)
- [MarkNotificationsSeen](/AI/mcp/tools/mark-notifications-seen)
- [MoveToProject](/AI/mcp/tools/move-to-project)
+- [MoveToTrash](/AI/mcp/tools/move-to-trash)
+- [MuteNotifications](/AI/mcp/tools/mute-notifications)
- [NameSearch](/AI/mcp/tools/name-search)
+- [OpenDirectMessage](/AI/mcp/tools/open-direct-message)
- [QueryDatabase](/AI/mcp/tools/query-database)
+- [ReactToChannelMessage](/AI/mcp/tools/react-to-channel-message)
- [ReadActivity](/AI/mcp/tools/read-activity)
- [ReadBookingSettings](/AI/mcp/tools/read-booking-settings)
- [ReadCallRecord](/AI/mcp/tools/read-call-record)
@@ -108,7 +122,9 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ReadWordDocument](/AI/mcp/tools/read-word-document)
- [RenameChannel](/AI/mcp/tools/rename-channel)
- [RenameDocument](/AI/mcp/tools/rename-document)
+- [RenameItem](/AI/mcp/tools/rename-item)
- [ResolveDocumentComment](/AI/mcp/tools/resolve-document-comment)
+- [RunRoutine](/AI/mcp/tools/run-routine)
- [SaveDatabaseQuery](/AI/mcp/tools/save-database-query)
- [SaveDatabaseView](/AI/mcp/tools/save-database-view)
- [SearchSkills](/AI/mcp/tools/search-skills)
@@ -118,6 +134,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [SendConfirmedEmail](/AI/mcp/tools/send-confirmed-email)
- [SendEmail](/AI/mcp/tools/send-email)
- [SetEntityProperty](/AI/mcp/tools/set-entity-property)
+- [SetFavorite](/AI/mcp/tools/set-favorite)
- [SetFormAccess](/AI/mcp/tools/set-form-access)
- [SetSenderPolicy](/AI/mcp/tools/set-sender-policy)
- [ShareWithChannel](/AI/mcp/tools/share-with-channel)
@@ -125,9 +142,11 @@ These pages are generated from Macro's Rust MCP tool registry.
- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)
- [UpdateBookingSettings](/AI/mcp/tools/update-booking-settings)
- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)
+- [UpdateCallRecord](/AI/mcp/tools/update-call-record)
- [UpdateInitiative](/AI/mcp/tools/update-initiative)
- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)
- [UpdateRoutine](/AI/mcp/tools/update-routine)
+- [UpdateSharing](/AI/mcp/tools/update-sharing)
- [UpdateThreadLabels](/AI/mcp/tools/update-thread-labels)
- [UploadFile](/AI/mcp/tools/upload-file)
- [WebFetch](/AI/mcp/tools/web-fetch)
diff --git a/apps/docs/AI/mcp/tools/list-entities.mdx b/apps/docs/AI/mcp/tools/list-entities.mdx
index a1a9c91a66..4530cd91db 100644
--- a/apps/docs/AI/mcp/tools/list-entities.mdx
+++ b/apps/docs/AI/mcp/tools/list-entities.mdx
@@ -13,6 +13,7 @@ Browse the user's Macro workspace to see recent items they have access to. Retur
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `includeTypes` | (`"calendar_event"` \| `"document"` \| `"ai_chat"` \| `"project"` \| `"email"` \| `"channel"` \| `"channel_thread"` \| `"call"` \| `"foreign_entity"`)[] | No | Filter returned items to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails. Macro tasks are returned as document items, so use includeTypes=["document"] with df subtype task for task requests. This is folded into the AST and applied as part of cursor-level filtering. |
+| `favoritesOnly` | boolean | No | Only return items the user has favorited (starred). Use for requests like "my favorites" or "what have I starred". Combine with includeTypes and the other filters as usual. Favorite or unfavorite an item with SetFavorite. |
| `sortBy` | `"recently_viewed"` \| `"recently_updated"` \| `"recently_created"` | No | Sort order for the list entities AI tool. |
| `df` | any | No | Full soup AST document filter (df). Use the same shape as /items/soup/ast, e.g. \{"l":\{"id":"..."}}. For Macro tasks, use \{"l":\{"dst":"task"}}; for skills, \{"l":\{"dst":"skill"}}. For "completed yesterday", AND the task subtype with updatedAt bounds, e.g. \{"&":[\{"l":\{"dst":"task"}},\{"&":[\{"l":\{"ua":\{"gte":"\<start>"}}},\{"l":\{"ua":\{"lt":"\<end>"}}}]}]} using ISO timestamps. |
| `pf` | any | No | Full soup AST project filter (pf). |
diff --git a/apps/docs/AI/mcp/tools/move-to-trash.mdx b/apps/docs/AI/mcp/tools/move-to-trash.mdx
new file mode 100644
index 0000000000..01f4038783
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/move-to-trash.mdx
@@ -0,0 +1,17 @@
+---
+title: MoveToTrash
+description: >-
+ Delete a document (including a task), an AI chat, or a project (folder) by
+ moving it to the trash, as the Delete action in the app does.
+---
+
+# MoveToTrash
+
+Delete a document (including a task), an AI chat, or a project (folder) by moving it to the trash, as the Delete action in the app does. Trashing a project also trashes everything inside it. Only the item's owner can trash it. Use only when the user explicitly asks to delete an item. Channels, email threads, and calendar events are not deleted with this tool.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"chat"` \| `"project"` | Yes | The kind of item to move to the trash. |
+| `entityId` | string | Yes | The id of the item to move to the trash. |
diff --git a/apps/docs/AI/mcp/tools/mute-notifications.mdx b/apps/docs/AI/mcp/tools/mute-notifications.mdx
new file mode 100644
index 0000000000..15d7c4bcde
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/mute-notifications.mdx
@@ -0,0 +1,19 @@
+---
+title: MuteNotifications
+description: >-
+ Mute, snooze, or unmute notifications about one item for the user only, as
+ Mute and Snooze in the app do.
+---
+
+# MuteNotifications
+
+Mute, snooze, or unmute notifications about one item for the user only, as Mute and Snooze in the app do. Muting never changes anyone else's notifications or the item itself. Use the entity type and id from ListNotifications or other tools.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"user"` \| `"chat"` \| `"channel"` \| `"channel_message"` \| `"document"` \| `"project"` \| `"email_thread"` \| `"calendar_event"` \| `"team"` \| `"call"` \| `"foreign_entity"` \| `"static_file"` \| `"crm_company"` \| `"crm_contact"` \| `"reminder"` \| `"skill"` \| `"scheduled_action"` | Yes | Canonical entity types accepted by the notification-listing tool. This mirrors [`EntityType`] because the shared model intentionally does not depend on `schemars`, while AI tool inputs require [`JsonSchema`]. |
+| `entityId` | string | Yes | The item's id. |
+| `action` | `"mute"` \| `"snooze"` \| `"unmute"` | Yes | What to do with an item's notifications. |
+| `snoozeUntil` | string | No | When notifications resume, as an ISO 8601 timestamp in the future. Required for snooze; omit otherwise. |
diff --git a/apps/docs/AI/mcp/tools/open-direct-message.mdx b/apps/docs/AI/mcp/tools/open-direct-message.mdx
new file mode 100644
index 0000000000..e264ec2d09
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/open-direct-message.mdx
@@ -0,0 +1,16 @@
+---
+title: OpenDirectMessage
+description: >-
+ Find the user's direct-message conversation with one or more people, creating
+ it if it does not exist yet, and return its channel id.
+---
+
+# OpenDirectMessage
+
+Find the user's direct-message conversation with one or more people, creating it if it does not exist yet, and return its channel id. One person opens a 1:1 DM; several open a group DM with exactly that set of people. Use this before SendChannelMessage when the user asks to message someone directly and no channel id is known. Find people with ListTeamMembers.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `participants` | string[] | Yes | The other people in the conversation, as Macro user ids (`macro\|<email>`) or emails. Do not include the user. |
diff --git a/apps/docs/AI/mcp/tools/react-to-channel-message.mdx b/apps/docs/AI/mcp/tools/react-to-channel-message.mdx
new file mode 100644
index 0000000000..c47416fbfe
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/react-to-channel-message.mdx
@@ -0,0 +1,19 @@
+---
+title: ReactToChannelMessage
+description: >-
+ Add or remove the user's own emoji reaction on a channel message or thread
+ reply.
+---
+
+# ReactToChannelMessage
+
+Add or remove the user's own emoji reaction on a channel message or thread reply. The reaction is shown as coming from the user. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to react to a message.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `channelId` | string | Yes | Channel id containing the message. |
+| `messageId` | string | Yes | Id of the message to react to. |
+| `emoji` | string | Yes | The emoji itself as a Unicode character, for example 👍 or 🎉 — not a shortcode like :thumbsup:. |
+| `action` | `"add"` \| `"remove"` | No | Whether to add or remove a reaction. |
diff --git a/apps/docs/AI/mcp/tools/rename-item.mdx b/apps/docs/AI/mcp/tools/rename-item.mdx
new file mode 100644
index 0000000000..ca00397acf
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/rename-item.mdx
@@ -0,0 +1,17 @@
+---
+title: RenameItem
+description: >-
+ Rename a project (shown as a folder in the app) or an AI chat.
+---
+
+# RenameItem
+
+Rename a project (shown as a folder in the app) or an AI chat. Renaming a project requires edit access; renaming an AI chat requires owning it. Use RenameDocument for documents and tasks, and RenameChannel for channels.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"project"` \| `"chat"` | Yes | The kind of item to rename. |
+| `entityId` | string | Yes | The id of the item to rename. |
+| `name` | string | Yes | The new name. |
diff --git a/apps/docs/AI/mcp/tools/run-routine.mdx b/apps/docs/AI/mcp/tools/run-routine.mdx
new file mode 100644
index 0000000000..3d8e80e7cc
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/run-routine.mdx
@@ -0,0 +1,16 @@
+---
+title: RunRoutine
+description: >-
+ Start a routine owned by the authenticated user now, outside its schedule, as
+ Run Now in the app does.
+---
+
+# RunRoutine
+
+Start a routine owned by the authenticated user now, outside its schedule, as Run Now in the app does. The run continues after this returns; check its result later with ReadRoutine. Fails if the routine is already running.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `routineId` | string | Yes | Routine UUID. |
diff --git a/apps/docs/AI/mcp/tools/set-favorite.mdx b/apps/docs/AI/mcp/tools/set-favorite.mdx
new file mode 100644
index 0000000000..d89bff9526
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/set-favorite.mdx
@@ -0,0 +1,18 @@
+---
+title: SetFavorite
+description: >-
+ Add an item to the user's favorites (shown starred in the app sidebar) or
+ remove it, as the Favorite action does.
+---
+
+# SetFavorite
+
+Add an item to the user's favorites (shown starred in the app sidebar) or remove it, as the Favorite action does. Requires view access to add an item. List favorites with ListEntities and favoritesOnly.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"project"` \| `"chat"` \| `"channel"` \| `"email"` \| `"call"` \| `"crm_company"` \| `"crm_contact"` | Yes | The kinds of item a user can favorite. |
+| `entityId` | string | Yes | The id of the item. |
+| `favorite` | boolean | Yes | True to add the item to favorites, false to remove it. |
diff --git a/apps/docs/AI/mcp/tools/update-call-record.mdx b/apps/docs/AI/mcp/tools/update-call-record.mdx
new file mode 100644
index 0000000000..5047d158f4
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/update-call-record.mdx
@@ -0,0 +1,18 @@
+---
+title: UpdateCallRecord
+description: >-
+ Rename a recorded call or change whether it is shared with the team, as the
+ call's header menu does.
+---
+
+# UpdateCallRecord
+
+Rename a recorded call or change whether it is shared with the team, as the call's header menu does. Requires edit access to the call; only the call's creator can change team sharing on a finished call. Find calls with ListEntities or NameSearch.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `callId` | string | Yes | The id of the call. |
+| `name` | string | No | New display name for the call. An empty string clears the custom name. Omit to leave it unchanged. |
+| `shareWithTeam` | boolean | No | True to share the call with the creator's team (view access), false to stop sharing it. Omit to leave it unchanged. |
diff --git a/apps/docs/AI/mcp/tools/update-sharing.mdx b/apps/docs/AI/mcp/tools/update-sharing.mdx
new file mode 100644
index 0000000000..8620f0037d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/update-sharing.mdx
@@ -0,0 +1,22 @@
+---
+title: UpdateSharing
+description: >-
+ Change who can access a document (including a task), an AI chat, or a project
+ (folder), as the Share menu in the app does: link sharing, team access, and
+ per-channel access.
+---
+
+# UpdateSharing
+
+Change who can access a document (including a task), an AI chat, or a project (folder), as the Share menu in the app does: link sharing, team access, and per-channel access. Each omitted field stays unchanged; off disables that share. Requires edit access to a document, or owning an AI chat or project; only the owner can change team access. Use ShareWithChannel to post an item into a channel, and UpdateInitiativeSharing for Tasks projects (initiatives).
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"chat"` \| `"project"` | Yes | The kind of item whose sharing changes. |
+| `entityId` | string | Yes | The id of the item whose sharing changes. |
+| `linkScope` | `"off"` \| `"public"` \| `"team"` | No | Who the item's share link admits: public (anyone with the link), team (the owner's team members with the link), or off to disable link sharing. |
+| `linkAccess` | `"off"` \| `"view"` \| `"comment"` \| `"edit"` | No | Permission granted by an enabled share link. Off resets it to the default level. |
+| `teamAccess` | `"off"` \| `"view"` \| `"comment"` \| `"edit"` | No | Access for everyone on the owner's team; off removes it. |
+| `channels` | SharingChannel[] | No | Individual channel grants to set or remove; other channel grants stay unchanged. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 964396ec17..b3c789e5c8 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -12,26 +12,36 @@
"AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-channel",
+ "AI/mcp/tools/create-company",
"AI/mcp/tools/create-confirmed-calendar-event",
+ "AI/mcp/tools/create-contact",
"AI/mcp/tools/create-document",
"AI/mcp/tools/create-form",
"AI/mcp/tools/create-import-entity",
"AI/mcp/tools/create-initiative",
"AI/mcp/tools/create-project",
"AI/mcp/tools/create-routine",
+ "AI/mcp/tools/create-skill",
"AI/mcp/tools/create-tag",
"AI/mcp/tools/delete-bot",
"AI/mcp/tools/delete-calendar-event",
+ "AI/mcp/tools/delete-call-record",
+ "AI/mcp/tools/delete-channel-message",
"AI/mcp/tools/delete-database-view",
+ "AI/mcp/tools/delete-document-comment",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-initiative",
+ "AI/mcp/tools/delete-routine",
"AI/mcp/tools/delete-tag",
"AI/mcp/tools/describe-database",
"AI/mcp/tools/discover-connectors",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
+ "AI/mcp/tools/duplicate-item",
"AI/mcp/tools/edit-booking-link",
+ "AI/mcp/tools/edit-channel-message",
"AI/mcp/tools/edit-document",
+ "AI/mcp/tools/edit-document-comment",
"AI/mcp/tools/edit-form",
"AI/mcp/tools/edit-presentation",
"AI/mcp/tools/edit-spreadsheet",
@@ -73,8 +83,12 @@
"AI/mcp/tools/mark-notifications-done",
"AI/mcp/tools/mark-notifications-seen",
"AI/mcp/tools/move-to-project",
+ "AI/mcp/tools/move-to-trash",
+ "AI/mcp/tools/mute-notifications",
"AI/mcp/tools/name-search",
+ "AI/mcp/tools/open-direct-message",
"AI/mcp/tools/query-database",
+ "AI/mcp/tools/react-to-channel-message",
"AI/mcp/tools/read-activity",
"AI/mcp/tools/read-booking-settings",
"AI/mcp/tools/read-call-record",
@@ -99,7 +113,9 @@
"AI/mcp/tools/read-word-document",
"AI/mcp/tools/rename-channel",
"AI/mcp/tools/rename-document",
+ "AI/mcp/tools/rename-item",
"AI/mcp/tools/resolve-document-comment",
+ "AI/mcp/tools/run-routine",
"AI/mcp/tools/save-database-query",
"AI/mcp/tools/save-database-view",
"AI/mcp/tools/search-skills",
@@ -109,6 +125,7 @@
"AI/mcp/tools/send-confirmed-email",
"AI/mcp/tools/send-email",
"AI/mcp/tools/set-entity-property",
+ "AI/mcp/tools/set-favorite",
"AI/mcp/tools/set-form-access",
"AI/mcp/tools/set-sender-policy",
"AI/mcp/tools/share-with-channel",
@@ -116,9 +133,11 @@
"AI/mcp/tools/text-editor-code-execution",
"AI/mcp/tools/update-booking-settings",
"AI/mcp/tools/update-calendar-event",
+ "AI/mcp/tools/update-call-record",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
"AI/mcp/tools/update-routine",
+ "AI/mcp/tools/update-sharing",
"AI/mcp/tools/update-thread-labels",
"AI/mcp/tools/upload-file",
"AI/mcp/tools/web-fetch",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index e76377d72b..d61dc19e0c 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -83,26 +83,36 @@
"AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-channel",
+ "AI/mcp/tools/create-company",
"AI/mcp/tools/create-confirmed-calendar-event",
+ "AI/mcp/tools/create-contact",
"AI/mcp/tools/create-document",
"AI/mcp/tools/create-form",
"AI/mcp/tools/create-import-entity",
"AI/mcp/tools/create-initiative",
"AI/mcp/tools/create-project",
"AI/mcp/tools/create-routine",
+ "AI/mcp/tools/create-skill",
"AI/mcp/tools/create-tag",
"AI/mcp/tools/delete-bot",
"AI/mcp/tools/delete-calendar-event",
+ "AI/mcp/tools/delete-call-record",
+ "AI/mcp/tools/delete-channel-message",
"AI/mcp/tools/delete-database-view",
+ "AI/mcp/tools/delete-document-comment",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-initiative",
+ "AI/mcp/tools/delete-routine",
"AI/mcp/tools/delete-tag",
"AI/mcp/tools/describe-database",
"AI/mcp/tools/discover-connectors",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
+ "AI/mcp/tools/duplicate-item",
"AI/mcp/tools/edit-booking-link",
+ "AI/mcp/tools/edit-channel-message",
"AI/mcp/tools/edit-document",
+ "AI/mcp/tools/edit-document-comment",
"AI/mcp/tools/edit-form",
"AI/mcp/tools/edit-presentation",
"AI/mcp/tools/edit-spreadsheet",
@@ -144,8 +154,12 @@
"AI/mcp/tools/mark-notifications-done",
"AI/mcp/tools/mark-notifications-seen",
"AI/mcp/tools/move-to-project",
+ "AI/mcp/tools/move-to-trash",
+ "AI/mcp/tools/mute-notifications",
"AI/mcp/tools/name-search",
+ "AI/mcp/tools/open-direct-message",
"AI/mcp/tools/query-database",
+ "AI/mcp/tools/react-to-channel-message",
"AI/mcp/tools/read-activity",
"AI/mcp/tools/read-booking-settings",
"AI/mcp/tools/read-call-record",
@@ -170,7 +184,9 @@
"AI/mcp/tools/read-word-document",
"AI/mcp/tools/rename-channel",
"AI/mcp/tools/rename-document",
+ "AI/mcp/tools/rename-item",
"AI/mcp/tools/resolve-document-comment",
+ "AI/mcp/tools/run-routine",
"AI/mcp/tools/save-database-query",
"AI/mcp/tools/save-database-view",
"AI/mcp/tools/search-skills",
@@ -180,6 +196,7 @@
"AI/mcp/tools/send-confirmed-email",
"AI/mcp/tools/send-email",
"AI/mcp/tools/set-entity-property",
+ "AI/mcp/tools/set-favorite",
"AI/mcp/tools/set-form-access",
"AI/mcp/tools/set-sender-policy",
"AI/mcp/tools/share-with-channel",
@@ -187,9 +204,11 @@
"AI/mcp/tools/text-editor-code-execution",
"AI/mcp/tools/update-booking-settings",
"AI/mcp/tools/update-calendar-event",
+ "AI/mcp/tools/update-call-record",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
"AI/mcp/tools/update-routine",
+ "AI/mcp/tools/update-sharing",
"AI/mcp/tools/update-thread-labels",
"AI/mcp/tools/upload-file",
"AI/mcp/tools/web-fetch",
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.ts
index c15a8b259f..14615d6989 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
@@ -26,25 +26,36 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
CreateBot: (whose) => `create a bot in ${whose} workspace`,
CreateCalendarEvent: (whose) => `add an event to ${whose} calendar`,
CreateChannel: (whose) => `create a channel from ${whose} account`,
+ CreateCompany: (whose) => `add a company to ${whose} CRM`,
CreateConfirmedCalendarEvent: (whose) => `add an event to ${whose} calendar`,
+ CreateContact: (whose) => `add a contact to ${whose} CRM`,
CreateDocument: (whose) => `create a document in ${whose} workspace`,
CreateForm: (whose) => `create a form in ${whose} workspace`,
CreateImportEntity: (whose) => `import into ${whose} workspace`,
CreateInitiative: (whose) => `create an initiative in ${whose} workspace`,
CreateProject: (whose) => `create a project in ${whose} workspace`,
CreateRoutine: (whose) => `create a routine for ${whose} account`,
+ CreateSkill: (whose) => `create a skill in ${whose} workspace`,
CreateTag: (whose) => `create a tag in ${whose} workspace`,
DeleteBot: (whose) => `delete ${whose} bots`,
DeleteCalendarEvent: (whose) => `delete an event from ${whose} calendar`,
+ DeleteCallRecord: (whose) => `delete ${whose} calls`,
+ DeleteChannelMessage: (whose) => `delete messages from ${whose} account`,
DeleteDatabaseView: (whose) => `delete a view from ${whose} databases`,
+ DeleteDocumentComment: (whose) => `delete comments on ${whose} documents`,
DeleteImportEntity: (whose) => `delete an import from ${whose} workspace`,
DeleteInitiative: (whose) => `delete ${whose} initiatives`,
+ DeleteRoutine: (whose) => `delete ${whose} routines`,
DeleteTag: (whose) => `delete tags in ${whose} workspace`,
DescribeDatabase: (whose) => `read ${whose} databases`,
- DisplayResults: (whose) => `show results from ${whose} workspace`,
+ DiscoverConnectors: null,
DispatchCodingAgent: (whose) => `start a coding agent with ${whose} access`,
+ DisplayResults: (whose) => `show results from ${whose} workspace`,
+ DuplicateItem: (whose) => `duplicate items in ${whose} workspace`,
EditBookingLink: (whose) => `edit ${whose} booking links`,
+ EditChannelMessage: (whose) => `edit messages from ${whose} account`,
EditDocument: (whose) => `edit ${whose} documents`,
+ EditDocumentComment: (whose) => `edit comments on ${whose} documents`,
EditForm: (whose) => `edit ${whose} forms`,
EditPresentation: (whose) => `edit ${whose} presentations`,
EditSpreadsheet: (whose) => `edit ${whose} spreadsheets`,
@@ -88,8 +99,12 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
MarkNotificationsDone: (whose) => `mark ${whose} notifications done`,
MarkNotificationsSeen: (whose) => `mark ${whose} notifications seen`,
MoveToProject: (whose) => `reorganize ${whose} projects`,
+ MoveToTrash: (whose) => `delete items in ${whose} workspace`,
+ MuteNotifications: (whose) => `change ${whose} notifications`,
NameSearch: (whose) => `search ${whose} workspace`,
+ OpenDirectMessage: (whose) => `open a direct message from ${whose} account`,
QueryDatabase: (whose) => `query ${whose} databases`,
+ ReactToChannelMessage: (whose) => `react to messages from ${whose} account`,
ReadActivity: (whose) => `read ${whose} recent activity`,
ReadBookingSettings: (whose) => `read ${whose} booking settings`,
ReadCallRecord: (whose) => `read ${whose} call recordings`,
@@ -114,17 +129,19 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
ReadWordDocument: (whose) => `read ${whose} documents`,
RenameChannel: (whose) => `rename ${whose} channels`,
RenameDocument: (whose) => `rename ${whose} documents`,
+ RenameItem: (whose) => `rename items in ${whose} workspace`,
ResolveDocumentComment: (whose) => `resolve comments on ${whose} documents`,
+ RunRoutine: (whose) => `run ${whose} routines`,
SaveDatabaseQuery: (whose) => `save a query in ${whose} databases`,
SaveDatabaseView: (whose) => `save a view in ${whose} databases`,
SearchSkills: (whose) => `search ${whose} skills`,
SearchTools: null,
- DiscoverConnectors: null,
SelfKnowledge: null,
SendChannelMessage: (whose) => `post a message from ${whose} account`,
SendConfirmedEmail: (whose) => `send email from ${whose} account`,
SendEmail: (whose) => `send email from ${whose} account`,
SetEntityProperty: (whose) => `set properties in ${whose} workspace`,
+ SetFavorite: (whose) => `change ${whose} favorites`,
SetFormAccess: (whose) => `change who can respond to ${whose} forms`,
SetSenderPolicy: (whose) => `change ${whose} email sender rules`,
ShareWithChannel: (whose) =>
@@ -133,9 +150,11 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
TextEditorCodeExecution: (whose) => `edit files with ${whose} access`,
UpdateBookingSettings: (whose) => `change ${whose} booking settings`,
UpdateCalendarEvent: (whose) => `change an event on ${whose} calendar`,
+ UpdateCallRecord: (whose) => `change ${whose} calls`,
UpdateInitiative: (whose) => `change ${whose} initiatives`,
UpdateInitiativeSharing: (whose) => `change who can see ${whose} initiatives`,
UpdateRoutine: (whose) => `change ${whose} routines`,
+ UpdateSharing: (whose) => `change sharing in ${whose} workspace`,
UpdateThreadLabels: (whose) => `relabel ${whose} email`,
UploadFile: (whose) => `upload a file to ${whose} workspace`,
WebFetch: null,
diff --git a/apps/web/src/features/crm/crm-tool-renderers.tsx b/apps/web/src/features/crm/crm-tool-renderers.tsx
index 18edaf456b..db414b1115 100644
--- a/apps/web/src/features/crm/crm-tool-renderers.tsx
+++ b/apps/web/src/features/crm/crm-tool-renderers.tsx
@@ -1,7 +1,9 @@
import { BaseTool } from '@core/component/AI/component/tool/BaseTool';
import { createToolRenderer } from '@core/component/AI/component/tool/ToolRenderer';
+import { ItemPreview } from '@core/component/ItemPreview';
import Buildings from '@phosphor-icons/core/regular/buildings.svg';
-import { Show } from 'solid-js';
+import UserPlus from '@phosphor-icons/core/regular/user-plus.svg';
+import { Show, Suspense } from 'solid-js';
import {
GetCompanyToolResponse,
ListCompaniesToolResponse,
@@ -92,4 +94,60 @@ const getCompanyHandler = createToolRenderer({
},
});
-export { getCompanyHandler, listCompaniesHandler };
+function CompanyPreview(props: { companyId: string }) {
+ return (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={props.companyId}
+ type="crm_company"
+ />
+ </Suspense>
+ );
+}
+
+const createCompanyHandler = createToolRenderer({
+ name: 'CreateCompany',
+ render: (ctx) => (
+ <BaseTool icon={Buildings} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ <Show
+ when={ctx.response?.data.companyId}
+ fallback={
+ <>
+ Add CRM company <span class="text-ink">{ctx.tool.data.name}</span>{' '}
+ ({ctx.tool.data.domain})
+ </>
+ }
+ >
+ {(companyId) => (
+ <>
+ Added CRM company <CompanyPreview companyId={companyId()} />
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+const createContactHandler = createToolRenderer({
+ name: 'CreateContact',
+ render: (ctx) => (
+ <BaseTool icon={UserPlus} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Added' : 'Add'} contact{' '}
+ <span class="text-ink">{ctx.tool.data.name}</span> (
+ {ctx.tool.data.email}) to{' '}
+ <CompanyPreview companyId={ctx.tool.data.companyId} />
+ </div>
+ </BaseTool>
+ ),
+});
+
+export {
+ createCompanyHandler,
+ createContactHandler,
+ getCompanyHandler,
+ listCompaniesHandler,
+};
diff --git a/apps/web/src/lib/core/component/AI/component/tool/CallRecordMutations.tsx b/apps/web/src/lib/core/component/AI/component/tool/CallRecordMutations.tsx
new file mode 100644
index 0000000000..a90bea6c1a
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/CallRecordMutations.tsx
@@ -0,0 +1,55 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
+import { Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+function CallPreview(props: { callId: string }) {
+ return (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={props.callId}
+ type="call"
+ />
+ </Suspense>
+ );
+}
+
+export const updateCallRecordHandler = createToolRenderer({
+ name: 'UpdateCallRecord',
+ render: (ctx) => (
+ <BaseTool icon={PencilSimple} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ <Show
+ when={ctx.response?.data.summary}
+ fallback={
+ <>
+ Update <CallPreview callId={ctx.tool.data.callId} />
+ </>
+ }
+ >
+ {(summary) => (
+ <>
+ <CallPreview callId={ctx.tool.data.callId} />{' '}
+ <span class="text-ink">{summary()}</span>
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const deleteCallRecordHandler = createToolRenderer({
+ name: 'DeleteCallRecord',
+ render: (ctx) => (
+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Deleted' : 'Delete'}{' '}
+ <CallPreview callId={ctx.tool.data.callId} />
+ </div>
+ </BaseTool>
+ ),
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ChannelMessageMutations.tsx b/apps/web/src/lib/core/component/AI/component/tool/ChannelMessageMutations.tsx
new file mode 100644
index 0000000000..e738e56af2
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/ChannelMessageMutations.tsx
@@ -0,0 +1,126 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import ChatCircleDots from '@phosphor-icons/core/regular/chat-circle-dots.svg';
+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import Smiley from '@phosphor-icons/core/regular/smiley.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
+import { createSignal, Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+function ChannelPreview(props: { channelId: string }) {
+ return (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={props.channelId}
+ type="channel"
+ />
+ </Suspense>
+ );
+}
+
+export const editChannelMessageHandler = createToolRenderer({
+ name: 'EditChannelMessage',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+
+ return (
+ <BaseTool
+ icon={PencilSimple}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <p class="whitespace-pre-wrap break-words rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
+ {ctx.tool.data.content}
+ </p>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Edited a message in' : 'Edit a message in'}{' '}
+ <ChannelPreview channelId={ctx.tool.data.channelId} />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.content}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const deleteChannelMessageHandler = createToolRenderer({
+ name: 'DeleteChannelMessage',
+ render: (ctx) => (
+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Deleted a message in' : 'Delete a message in'}{' '}
+ <ChannelPreview channelId={ctx.tool.data.channelId} />
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const reactToChannelMessageHandler = createToolRenderer({
+ name: 'ReactToChannelMessage',
+ render: (ctx) => {
+ const removing = () => ctx.tool.data.action === 'remove';
+ const verb = () => {
+ if (removing()) return ctx.response ? 'Removed' : 'Remove';
+ return ctx.response ? 'Reacted' : 'React';
+ };
+
+ return (
+ <BaseTool icon={Smiley} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {verb()} <span class="text-ink">{ctx.tool.data.emoji}</span>{' '}
+ {removing() ? 'from' : 'to'} a message in{' '}
+ <ChannelPreview channelId={ctx.tool.data.channelId} />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const openDirectMessageHandler = createToolRenderer({
+ name: 'OpenDirectMessage',
+ render: (ctx) => {
+ const participants = () =>
+ (ctx.response?.data.participants ?? ctx.tool.data.participants)
+ .map((id) => (id.startsWith('macro|') ? id.slice('macro|'.length) : id))
+ .join(', ');
+
+ return (
+ <BaseTool
+ icon={ChatCircleDots}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <div class="min-w-0 flex-1">
+ <Show
+ when={ctx.response?.data}
+ fallback={
+ <>
+ Open a direct message with{' '}
+ <span class="text-ink">{participants()}</span>
+ </>
+ }
+ >
+ {(response) => (
+ <>
+ {response().created ? 'Started' : 'Opened'}{' '}
+ <ChannelPreview channelId={response().channelId} /> with{' '}
+ <span class="text-ink">{participants()}</span>
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/CreateSkill.tsx b/apps/web/src/lib/core/component/AI/component/tool/CreateSkill.tsx
new file mode 100644
index 0000000000..87053a3835
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/CreateSkill.tsx
@@ -0,0 +1,60 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import Lightning from '@phosphor-icons/core/regular/lightning.svg';
+import { createSignal, Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+export const createSkillHandler = createToolRenderer({
+ name: 'CreateSkill',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+
+ return (
+ <BaseTool
+ icon={Lightning}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <pre class="whitespace-pre-wrap break-words rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
+ {ctx.tool.data.markdown}
+ </pre>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ <Show
+ when={ctx.response?.data.documentId}
+ fallback={
+ <>
+ Create skill{' '}
+ <span class="text-ink">{ctx.tool.data.skillName}</span>
+ </>
+ }
+ >
+ {(documentId) => (
+ <>
+ Created skill{' '}
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={documentId()}
+ type="document"
+ />
+ </Suspense>
+ </>
+ )}
+ </Show>
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.markdown}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx b/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx
index 9c086a868a..8257504714 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx
@@ -2,6 +2,8 @@ import { ItemPreview } from '@core/component/ItemPreview';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg';
import ChatCircle from '@phosphor-icons/core/regular/chat-circle.svg';
import CheckCircle from '@phosphor-icons/core/regular/check-circle.svg';
+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
import { createSignal, Show, Suspense } from 'solid-js';
import { BaseTool } from './BaseTool';
import { Tool } from './Tool';
@@ -96,3 +98,54 @@ export const resolveDocumentCommentHandler = createToolRenderer({
);
},
});
+
+export const editDocumentCommentHandler = createToolRenderer({
+ name: 'EditDocumentComment',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+
+ return (
+ <BaseTool
+ icon={PencilSimple}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <p class="whitespace-pre-wrap break-words rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
+ {ctx.tool.data.content}
+ </p>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Edited a comment on' : 'Edit a comment on'}{' '}
+ <DocumentPreview documentId={ctx.tool.data.documentId} />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.content}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const deleteDocumentCommentHandler = createToolRenderer({
+ name: 'DeleteDocumentComment',
+ render: (ctx) => {
+ const noun = () =>
+ ctx.response?.data.deletedThread ? 'a comment thread' : 'a comment';
+
+ return (
+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Deleted' : 'Delete'} {noun()} on{' '}
+ <DocumentPreview documentId={ctx.tool.data.documentId} />
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/EntityLifecycle.tsx b/apps/web/src/lib/core/component/AI/component/tool/EntityLifecycle.tsx
new file mode 100644
index 0000000000..223494c45d
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/EntityLifecycle.tsx
@@ -0,0 +1,203 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import Copy from '@phosphor-icons/core/regular/copy.svg';
+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import ShareNetwork from '@phosphor-icons/core/regular/share-network.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
+import type {
+ DuplicableEntityType,
+ RenameableEntityType,
+ ShareAccess,
+ SharingEntityType,
+ TrashableEntityType,
+} from '@service-cognition/generated/tools/types';
+import type { ItemType } from '@service-storage/client';
+import { createSignal, For, Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+type LifecycleEntityType =
+ | TrashableEntityType
+ | DuplicableEntityType
+ | RenameableEntityType
+ | SharingEntityType;
+
+const ITEM_TYPES: Record<LifecycleEntityType, ItemType> = {
+ document: 'document',
+ chat: 'chat',
+ project: 'project',
+};
+
+function EntityPreview(props: { id: string; type: LifecycleEntityType }) {
+ return (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={props.id}
+ type={ITEM_TYPES[props.type]}
+ />
+ </Suspense>
+ );
+}
+
+export const moveToTrashHandler = createToolRenderer({
+ name: 'MoveToTrash',
+ render: (ctx) => (
+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Moved' : 'Move'}{' '}
+ <EntityPreview
+ id={ctx.tool.data.entityId}
+ type={ctx.tool.data.entityType}
+ />{' '}
+ to the trash
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const duplicateItemHandler = createToolRenderer({
+ name: 'DuplicateItem',
+ render: (ctx) => (
+ <BaseTool icon={Copy} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ <Show
+ when={ctx.response?.data}
+ fallback={
+ <>
+ Duplicate{' '}
+ <EntityPreview
+ id={ctx.tool.data.entityId}
+ type={ctx.tool.data.entityType}
+ />
+ </>
+ }
+ >
+ {(response) => (
+ <>
+ Duplicated{' '}
+ <EntityPreview
+ id={response().sourceId}
+ type={response().entityType}
+ />{' '}
+ as{' '}
+ <EntityPreview
+ id={response().copyId}
+ type={response().entityType}
+ />
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const renameItemHandler = createToolRenderer({
+ name: 'RenameItem',
+ render: (ctx) => (
+ <BaseTool icon={PencilSimple} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Renamed' : 'Rename'}{' '}
+ <EntityPreview
+ id={ctx.tool.data.entityId}
+ type={ctx.tool.data.entityType}
+ />{' '}
+ to <span class="text-ink">{ctx.tool.data.name}</span>
+ </div>
+ </BaseTool>
+ ),
+});
+
+const ACCESS_LABELS: Record<ShareAccess, string> = {
+ off: 'Off',
+ view: 'Can view',
+ comment: 'Can comment',
+ edit: 'Can edit',
+};
+
+const LINK_LABELS = {
+ off: 'Off',
+ public: 'Anyone with the link',
+ team: 'Team members with the link',
+} as const;
+
+export const updateSharingHandler = createToolRenderer({
+ name: 'UpdateSharing',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const details = () => {
+ const data = ctx.tool.data;
+ return [
+ data.linkScope != null && {
+ label: 'Link',
+ value: LINK_LABELS[data.linkScope],
+ },
+ data.linkAccess != null && {
+ label: 'Link access',
+ value: ACCESS_LABELS[data.linkAccess],
+ },
+ data.teamAccess != null && {
+ label: 'Team',
+ value: ACCESS_LABELS[data.teamAccess],
+ },
+ ].filter((detail) => !!detail);
+ };
+ const channels = () => ctx.tool.data.channels ?? [];
+
+ return (
+ <BaseTool
+ icon={ShareNetwork}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <dl class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs">
+ <For each={details()}>
+ {(detail) => (
+ <div class="grid grid-cols-[7rem_minmax(0,1fr)] gap-2">
+ <dt class="text-ink-extra-muted">{detail.label}</dt>
+ <dd class="min-w-0 text-ink">{detail.value}</dd>
+ </div>
+ )}
+ </For>
+ <For each={channels()}>
+ {(channel) => (
+ <div class="grid grid-cols-[7rem_minmax(0,1fr)] gap-2">
+ <dt class="min-w-0 text-ink-extra-muted">
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={channel.channelId}
+ type="channel"
+ />
+ </Suspense>
+ </dt>
+ <dd class="min-w-0 text-ink">
+ {ACCESS_LABELS[channel.access]}
+ </dd>
+ </div>
+ )}
+ </For>
+ </dl>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Updated sharing on' : 'Update sharing on'}{' '}
+ <EntityPreview
+ id={ctx.tool.data.entityId}
+ type={ctx.tool.data.entityType}
+ />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={details().length > 0 || channels().length > 0}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Notifications.tsx b/apps/web/src/lib/core/component/AI/component/tool/Notifications.tsx
index 74d66e309c..9406059da4 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Notifications.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Notifications.tsx
@@ -1,3 +1,5 @@
+import BellSlash from '@phosphor-icons/core/regular/bell-slash.svg';
+import BellZ from '@phosphor-icons/core/regular/bell-z.svg';
import Check from '@phosphor-icons/core/regular/check.svg';
import List from '@phosphor-icons/core/regular/list.svg';
import type { ListNotifications as ListNotificationsTool } from '@service-cognition/generated/tools/types';
@@ -111,8 +113,43 @@ const markNotificationsDoneHandler = createToolRenderer({
),
});
+const muteNotificationsHandler = createToolRenderer({
+ name: 'MuteNotifications',
+ render: (ctx) => {
+ const label = () => {
+ const done = !!ctx.response;
+ switch (ctx.tool.data.action) {
+ case 'mute':
+ return done ? 'Muted notifications' : 'Mute notifications';
+ case 'snooze':
+ return done ? 'Snoozed notifications' : 'Snooze notifications';
+ case 'unmute':
+ return done ? 'Unmuted notifications' : 'Unmute notifications';
+ }
+ };
+ const until = () => {
+ const value = ctx.tool.data.snoozeUntil;
+ return value ? new Date(value).toLocaleString() : undefined;
+ };
+
+ return (
+ <BaseTool
+ icon={ctx.tool.data.action === 'snooze' ? BellZ : BellSlash}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <div class="min-w-0 flex-1">
+ {label()} for a {ctx.tool.data.entityType.replaceAll('_', ' ')}
+ <Show when={until()}>{(time) => <> until {time()}</>}</Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
export {
listNotificationsHandler,
markNotificationsDoneHandler,
markNotificationsSeenHandler,
+ muteNotificationsHandler,
};
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx b/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx
index 60748918e8..cdb3d185d8 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx
@@ -88,3 +88,29 @@ export const updateRoutineHandler = createToolRenderer({
/>
),
});
+export const runRoutineHandler = createToolRenderer({
+ name: 'RunRoutine',
+ handleResponse: async () => {
+ await invalidateSchedules();
+ },
+ render: (ctx) => (
+ <RoutineResult
+ label={ctx.response ? 'Started routine' : 'Run routine'}
+ result={ctx.response?.data}
+ renderContext={ctx.renderContext}
+ />
+ ),
+});
+export const deleteRoutineHandler = createToolRenderer({
+ name: 'DeleteRoutine',
+ handleResponse: async () => {
+ await invalidateSchedules();
+ },
+ render: (ctx) => (
+ <RoutineResult
+ label={ctx.response ? 'Deleted routine' : 'Delete routine'}
+ result={ctx.response?.data}
+ renderContext={ctx.renderContext}
+ />
+ ),
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/SetFavorite.tsx b/apps/web/src/lib/core/component/AI/component/tool/SetFavorite.tsx
new file mode 100644
index 0000000000..333350796f
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/SetFavorite.tsx
@@ -0,0 +1,44 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import Star from '@phosphor-icons/core/regular/star.svg';
+import type { FavoritableEntityType } from '@service-cognition/generated/tools/types';
+import type { ItemType } from '@service-storage/client';
+import { Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const ITEM_TYPES: Record<FavoritableEntityType, ItemType> = {
+ document: 'document',
+ project: 'project',
+ chat: 'chat',
+ channel: 'channel',
+ email: 'email',
+ call: 'call',
+ crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
+};
+
+export const setFavoriteHandler = createToolRenderer({
+ name: 'SetFavorite',
+ render: (ctx) => {
+ const verb = () => {
+ if (ctx.tool.data.favorite)
+ return ctx.response ? 'Favorited' : 'Favorite';
+ return ctx.response ? 'Unfavorited' : 'Unfavorite';
+ };
+
+ return (
+ <BaseTool icon={Star} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {verb()}{' '}
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={ctx.tool.data.entityId}
+ type={ITEM_TYPES[ctx.tool.data.entityType]}
+ />
+ </Suspense>
+ </div>
+ </BaseTool>
+ );
+ },
+});
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.tsx
index d1ee0d1579..eba9a4fc53 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
@@ -1,4 +1,6 @@
import {
+ createCompanyHandler,
+ createContactHandler,
getCompanyHandler,
listCompaniesHandler,
} from '@app/features/crm/crm-tool-renderers';
@@ -43,6 +45,16 @@ import {
listCalendarsHandler,
updateCalendarEventHandler,
} from './CalendarTools';
+import {
+ deleteCallRecordHandler,
+ updateCallRecordHandler,
+} from './CallRecordMutations';
+import {
+ deleteChannelMessageHandler,
+ editChannelMessageHandler,
+ openDirectMessageHandler,
+ reactToChannelMessageHandler,
+} from './ChannelMessageMutations';
import {
createChannelHandler,
manageChannelParticipantsHandler,
@@ -55,6 +67,7 @@ import {
} from './CodingAgents';
import { createDocumentHandler } from './CreateDocument';
import { createProjectHandler } from './CreateProject';
+import { createSkillHandler } from './CreateSkill';
import { createTagHandler } from './CreateTag';
import {
DatabaseToolPlaceholder,
@@ -71,10 +84,18 @@ import { discoverConnectorsHandler } from './DiscoverConnectors';
import { displayResultsHandler } from './DisplayResults';
import {
commentOnDocumentHandler,
+ deleteDocumentCommentHandler,
+ editDocumentCommentHandler,
resolveDocumentCommentHandler,
} from './DocumentComments';
import { editDocumentHandler } from './EditDocument';
import { editTagHandler } from './EditTag';
+import {
+ duplicateItemHandler,
+ moveToTrashHandler,
+ renameItemHandler,
+ updateSharingHandler,
+} from './EntityLifecycle';
import { lazyFormsToolHandlers } from './FormsHandlers';
import { generateImageHandler } from './GenerateImage';
import { getThreadHandler } from './GetThread';
@@ -97,6 +118,7 @@ import {
listNotificationsHandler,
markNotificationsDoneHandler,
markNotificationsSeenHandler,
+ muteNotificationsHandler,
} from './Notifications';
import {
editPresentationHandler,
@@ -123,8 +145,10 @@ import { readThreadHandler } from './ReadThread';
import { renameDocumentHandler } from './RenameDocument';
import {
createRoutineHandler,
+ deleteRoutineHandler,
listRoutinesHandler,
readRoutineHandler,
+ runRoutineHandler,
updateRoutineHandler,
} from './Routines';
import { contentSearchHandler, nameSearchHandler } from './Search';
@@ -134,6 +158,7 @@ import { selfKnowledgeHandler } from './SelfKnowledge';
import { sendChannelMessageHandler } from './SendChannelMessage';
import { sendConfirmedEmailHandler } from './SendConfirmedEmail';
import { sendEmailHandler } from './SendEmail';
+import { setFavoriteHandler } from './SetFavorite';
import { setSenderPolicyHandler } from './SetSenderPolicy';
import {
calculateSpreadsheetHandler,
@@ -177,6 +202,10 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListAgents: listAgentsHandler,
ConfigureBot: configureBotHandler,
CreateChannel: createChannelHandler,
+ EditChannelMessage: editChannelMessageHandler,
+ DeleteChannelMessage: deleteChannelMessageHandler,
+ ReactToChannelMessage: reactToChannelMessageHandler,
+ OpenDirectMessage: openDirectMessageHandler,
CreateBot: createBotHandler,
DeleteBot: deleteBotHandler,
GetBotWebhooks: getBotWebhooksHandler,
@@ -204,6 +233,8 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
DeleteImportEntity: deleteImportEntityHandler,
ImportNotionPage: importNotionPageHandler,
GetCompany: getCompanyHandler,
+ CreateCompany: createCompanyHandler,
+ CreateContact: createContactHandler,
GetEntityProperties: getEntityPropertiesHandler,
ListCompanies: listCompaniesHandler,
ListImportEntities: listImportEntitiesHandler,
@@ -218,17 +249,25 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListRoutines: listRoutinesHandler,
ReadRoutine: readRoutineHandler,
UpdateRoutine: updateRoutineHandler,
+ RunRoutine: runRoutineHandler,
+ DeleteRoutine: deleteRoutineHandler,
ListTags: listTagsHandler,
ListTeamMembers: listTeamMembersHandler,
LoadTools: loadToolsHandler,
MarkNotificationsDone: markNotificationsDoneHandler,
MarkNotificationsSeen: markNotificationsSeenHandler,
+ MuteNotifications: muteNotificationsHandler,
MoveToProject: moveToProjectHandler,
+ MoveToTrash: moveToTrashHandler,
+ DuplicateItem: duplicateItemHandler,
+ RenameItem: renameItemHandler,
+ UpdateSharing: updateSharingHandler,
BashCodeExecution: bashCodeExecutionHandler,
DisplayResults: displayResultsHandler,
DiscoverConnectors: discoverConnectorsHandler,
ContentSearch: contentSearchHandler,
CreateDocument: createDocumentHandler,
+ CreateSkill: createSkillHandler,
UploadFile: uploadFileHandler,
GenerateImage: generateImageHandler,
CreateProject: createProjectHandler,
@@ -240,6 +279,8 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
NameSearch: nameSearchHandler,
ReadActivity: readActivityHandler,
ReadCallRecord: readCallRecordHandler,
+ UpdateCallRecord: updateCallRecordHandler,
+ DeleteCallRecord: deleteCallRecordHandler,
ReadChannelMessageContext: readChannelMessageContextHandler,
ReadChannelMessages: readChannelMessagesHandler,
ReadChannelThread: readChannelThreadHandler,
@@ -253,6 +294,8 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
RenameDocument: renameDocumentHandler,
CommentOnDocument: commentOnDocumentHandler,
ResolveDocumentComment: resolveDocumentCommentHandler,
+ EditDocumentComment: editDocumentCommentHandler,
+ DeleteDocumentComment: deleteDocumentCommentHandler,
SearchSkills: searchSkillsHandler,
SearchTools: searchToolsHandler,
SelfKnowledge: selfKnowledgeHandler,
@@ -261,6 +304,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
SendConfirmedEmail: sendConfirmedEmailHandler,
SendEmail: sendEmailHandler,
SetSenderPolicy: setSenderPolicyHandler,
+ SetFavorite: setFavoriteHandler,
SetEntityProperty: setEntityPropertyHandler,
BulkSetEntityPropertyOptions: bulkSetEntityPropertyOptionsHandler,
Subagent: subagentHandler,
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.ts
index 0471aecc30..ab192f4b25 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
@@ -2153,6 +2153,14 @@ export const CreateChannelResponse = z.object({
summary: z.string(),
});
+export const CreateCompany = z.object({ name: z.string(), domain: z.string() });
+
+export const CreateCompanyResponse = z.object({
+ companyId: z.string().uuid(),
+ name: z.union([z.string(), z.null()]).optional(),
+ domains: z.array(z.string()),
+});
+
export const CreateConfirmedCalendarEvent = z.object({
title: z.string(),
time: z.any().superRefine((x, ctx) => {
@@ -2295,6 +2303,19 @@ export const ToolCalendarEvent = z.object({
calendarId: z.union([z.string().uuid(), z.null()]).optional(),
});
+export const CreateContact = z.object({
+ companyId: z.string().uuid(),
+ name: z.string(),
+ email: z.string(),
+});
+
+export const CreateContactResponse = z.object({
+ contactId: z.string().uuid(),
+ companyId: z.string().uuid(),
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+});
+
export const CreateDocument = z.object({
documentName: z.string(),
fileContent: z.string(),
@@ -3884,6 +3905,14 @@ export const RoutineInfo = z.object({
.optional(),
});
+export const CreateSkill = z.object({
+ skillName: z.string(),
+ markdown: z.string(),
+ projectId: z.union([z.string().uuid(), z.null()]).optional(),
+});
+
+export const CreateSkillResponse = z.object({ documentId: z.string().uuid() });
+
export const CreateTag = z.object({
label: z.string(),
color: z.any().superRefine((x, ctx) => {
@@ -4012,6 +4041,21 @@ export const DeleteCalendarEventResponse = z.object({
summary: z.string(),
});
+export const DeleteCallRecord = z.object({ callId: z.string().uuid() });
+
+export const DeleteCallRecordResponse = z.object({ callId: z.string().uuid() });
+
+export const DeleteChannelMessage = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+});
+
+export const DeleteChannelMessageResponse = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+ summary: z.string(),
+});
+
export const DeleteDatabaseView = z.object({
databaseId: z.string().uuid(),
viewId: z.string().uuid(),
@@ -4024,6 +4068,17 @@ export const DeletedDatabaseView = z.object({
name: z.string(),
});
+export const DeleteDocumentComment = z.object({
+ documentId: z.string().uuid(),
+ commentId: z.string().uuid(),
+});
+
+export const DeleteDocumentCommentResponse = z.object({
+ documentId: z.string().uuid(),
+ commentId: z.string().uuid(),
+ deletedThread: z.boolean(),
+});
+
export const DeleteImportEntity = z.object({ id: z.string().uuid() });
export const DeleteImportEntityResponse = z.object({
@@ -4035,6 +4090,10 @@ export const DeleteInitiative = z.object({ initiativeId: z.string().uuid() });
export const ProjectOperationComplete = z.object({ success: z.boolean() });
+export const DeleteRoutine = z.object({ routineId: z.string().uuid() });
+
+export const DeletedRoutine = z.object({ routineId: z.string().uuid() });
+
export const DeleteTag = z.object({
id: z.string().uuid(),
property_definition_id: z.string().uuid(),
@@ -4225,6 +4284,53 @@ export const DisplayResults = z.object({ view: z.any() });
export const DisplayResultsResponse = z.object({ message: z.string() });
+export const DuplicateItem = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('document'), z.literal('chat')];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ name: z.union([z.string(), z.null()]).optional(),
+});
+
+export const DuplicateItemResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('document'), z.literal('chat')];
+ 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',
+ });
+ }
+ }),
+ sourceId: z.string().uuid(),
+ copyId: z.string(),
+ message: z.string(),
+});
+
export const EditBookingLink = z
.object({
teamId: z.union([z.string().uuid(), z.null()]).optional(),
@@ -4311,6 +4417,18 @@ export const EditBookingLink = z
})
.strict();
+export const EditChannelMessage = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+ content: z.string(),
+});
+
+export const EditChannelMessageResponse = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+ summary: z.string(),
+});
+
export const EditDocument = z.object({
document_id: z.string(),
instructions: z.string(),
@@ -4322,6 +4440,17 @@ export const EditDocumentResponse = z.object({
clarification: z.union([z.string(), z.null()]).optional(),
});
+export const EditDocumentComment = z.object({
+ documentId: z.string().uuid(),
+ commentId: z.string().uuid(),
+ content: z.string(),
+});
+
+export const EditDocumentCommentResponse = z.object({
+ documentId: z.string().uuid(),
+ commentId: z.string().uuid(),
+});
+
export const EditForm = z.object({
formId: z.string().uuid(),
changes: z.array(
@@ -8857,6 +8986,7 @@ export const ListEntities = z.object({
z.null(),
])
.optional(),
+ favoritesOnly: z.boolean().optional(),
sortBy: z
.any()
.superRefine((x, ctx) => {
@@ -9859,6 +9989,136 @@ export const MoveToProjectResponse = z.object({
message: z.string(),
});
+export const MoveToTrash = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+});
+
+export const MoveToTrashResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ message: z.string(),
+});
+
+export const MuteNotifications = z.object({
+ entityType: z.enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'reminder',
+ 'skill',
+ 'scheduled_action',
+ ]),
+ entityId: z.string(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('mute'),
+ z.literal('snooze'),
+ z.literal('unmute'),
+ ];
+ 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',
+ });
+ }
+ }),
+ snoozeUntil: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+});
+
+export const MuteNotificationsResponse = z.object({
+ entityId: z.string(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('mute'),
+ z.literal('snooze'),
+ z.literal('unmute'),
+ ];
+ 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',
+ });
+ }
+ }),
+ snoozeUntil: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+});
+
export const NameSearch = z.object({
name: z.string(),
matchType: z
@@ -9956,6 +10216,17 @@ export const NameSearch = z.object({
.optional(),
});
+export const OpenDirectMessage = z.object({
+ participants: z.array(z.string()),
+});
+
+export const OpenDirectMessageResponse = z.object({
+ channelId: z.string().uuid(),
+ created: z.boolean(),
+ participants: z.array(z.string()),
+ summary: z.string(),
+});
+
export const QueryDatabase = z.object({
sql: z.string(),
databaseId: z.union([z.string().uuid(), z.null()]).optional(),
@@ -10181,28 +10452,82 @@ export const QueryDatabaseResponse = z.object({
summary: z.string(),
});
-export const ReadActivity = z.object({
- from: z.string().datetime({ offset: true }),
- to: z.string().datetime({ offset: true }),
+export const ReactToChannelMessage = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+ emoji: z.string(),
+ action: z
+ .intersection(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('add'), z.literal('remove')];
+ 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',
+ });
+ }
+ }),
+ z.any().default('add')
+ )
+ .optional(),
});
-export const ReadActivityResponse = z.object({
- activities: z.array(
- z.object({
- actorId: z.string(),
- entityType: z.string(),
- entityId: z.string(),
- action: z.any().superRefine((x, ctx) => {
- const schemas = [
- z.object({ type: z.literal('created') }),
- z.object({ type: z.literal('edited') }),
- z.object({ type: z.literal('opened') }),
- z.object({ type: z.literal('deleted') }),
- z.object({ type: z.literal('messaged') }),
- z.object({ type: z.literal('sent') }),
- z.object({ type: z.literal('responded') }),
- z.object({
- property: z.string(),
+export const ReactToChannelMessageResponse = z.object({
+ channelId: z.string().uuid(),
+ messageId: z.string().uuid(),
+ emoji: z.string(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('add'), z.literal('remove')];
+ 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',
+ });
+ }
+ }),
+ count: z.number().int().gte(0),
+});
+
+export const ReadActivity = z.object({
+ from: z.string().datetime({ offset: true }),
+ to: z.string().datetime({ offset: true }),
+});
+
+export const ReadActivityResponse = z.object({
+ activities: z.array(
+ z.object({
+ actorId: z.string(),
+ entityType: z.string(),
+ entityId: z.string(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ type: z.literal('created') }),
+ z.object({ type: z.literal('edited') }),
+ z.object({ type: z.literal('opened') }),
+ z.object({ type: z.literal('deleted') }),
+ z.object({ type: z.literal('messaged') }),
+ z.object({ type: z.literal('sent') }),
+ z.object({ type: z.literal('responded') }),
+ z.object({
+ property: z.string(),
propertyName: z.union([z.string(), z.null()]).optional(),
propertyType: z.union([z.string(), z.null()]).optional(),
from: z.any().optional(),
@@ -12800,6 +13125,52 @@ export const RenameDocumentResponse = z.object({
message: z.string(),
});
+export const RenameItem = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('project'), z.literal('chat')];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ name: z.string(),
+});
+
+export const RenameItemResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('project'), z.literal('chat')];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ name: z.string(),
+});
+
export const ResolveDocumentComment = z.object({
documentId: z.string().uuid(),
threadId: z.string().uuid(),
@@ -12812,6 +13183,13 @@ export const ResolveDocumentCommentResponse = z.object({
resolved: z.boolean(),
});
+export const RunRoutine = z.object({ routineId: z.string().uuid() });
+
+export const RoutineRunStarted = z.object({
+ routineId: z.string().uuid(),
+ resource: z.any().optional(),
+});
+
export const SaveDatabaseQuery = z.object({
databaseId: z.union([z.string().uuid(), z.null()]).optional(),
sql: z.string(),
@@ -13476,6 +13854,70 @@ export const SetEntityPropertyResponse = z.object({
message: z.string(),
});
+export const SetFavorite = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('project'),
+ z.literal('chat'),
+ z.literal('channel'),
+ z.literal('email'),
+ z.literal('call'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ favorite: z.boolean(),
+});
+
+export const SetFavoriteResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('project'),
+ z.literal('chat'),
+ z.literal('channel'),
+ z.literal('email'),
+ z.literal('call'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ favorite: z.boolean(),
+});
+
export const SetFormAccess = z.object({
formId: z.string().uuid(),
draft: z
@@ -14077,6 +14519,17 @@ export const UpdateCalendarEvent = z.object({
.optional(),
});
+export const UpdateCallRecord = z.object({
+ callId: z.string().uuid(),
+ name: z.union([z.string(), z.null()]).optional(),
+ shareWithTeam: z.union([z.boolean(), z.null()]).optional(),
+});
+
+export const UpdateCallRecordResponse = z.object({
+ callId: z.string().uuid(),
+ summary: z.string(),
+});
+
export const UpdateInitiative = z.object({
initiativeId: z.string().uuid(),
name: z.union([z.string(), z.null()]).optional(),
@@ -14289,6 +14742,176 @@ export const UpdateRoutine = z.object({
}),
});
+export const UpdateSharing = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ linkScope: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('off'),
+ z.literal('public'),
+ z.literal('team'),
+ ];
+ 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',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ linkAccess: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('off'),
+ z.literal('view'),
+ z.literal('comment'),
+ z.literal('edit'),
+ ];
+ 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',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ teamAccess: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('off'),
+ z.literal('view'),
+ z.literal('comment'),
+ z.literal('edit'),
+ ];
+ 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',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ channels: z
+ .union([
+ z.array(
+ z.object({
+ channelId: z.string().uuid(),
+ access: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('off'),
+ z.literal('view'),
+ z.literal('comment'),
+ z.literal('edit'),
+ ];
+ 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',
+ });
+ }
+ }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+});
+
+export const UpdateSharingResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ entityId: z.string().uuid(),
+ message: z.string(),
+});
+
export const UpdateThreadLabels = z.object({
thread_id: z.string().uuid(),
label_id: z.string().uuid(),
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.ts
index 5245fcc41e..6fc80dda96 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
@@ -51,10 +51,18 @@ type ToolParserMap = {
call: types.CreateChannel;
response: types.CreateChannelResponse;
};
+ CreateCompany: {
+ call: types.CreateCompany;
+ response: types.CreateCompanyResponse;
+ };
CreateConfirmedCalendarEvent: {
call: types.CreateConfirmedCalendarEvent;
response: types.ToolCalendarEvent;
};
+ CreateContact: {
+ call: types.CreateContact;
+ response: types.CreateContactResponse;
+ };
CreateDocument: {
call: types.CreateDocument;
response: types.CreateDocumentResponse;
@@ -73,16 +81,29 @@ type ToolParserMap = {
response: types.CreateProjectResponse;
};
CreateRoutine: { call: types.CreateRoutine; response: types.RoutineInfo };
+ CreateSkill: { call: types.CreateSkill; response: types.CreateSkillResponse };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };
DeleteCalendarEvent: {
call: types.DeleteCalendarEvent;
response: types.DeleteCalendarEventResponse;
};
+ DeleteCallRecord: {
+ call: types.DeleteCallRecord;
+ response: types.DeleteCallRecordResponse;
+ };
+ DeleteChannelMessage: {
+ call: types.DeleteChannelMessage;
+ response: types.DeleteChannelMessageResponse;
+ };
DeleteDatabaseView: {
call: types.DeleteDatabaseView;
response: types.DeletedDatabaseView;
};
+ DeleteDocumentComment: {
+ call: types.DeleteDocumentComment;
+ response: types.DeleteDocumentCommentResponse;
+ };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -91,6 +112,7 @@ type ToolParserMap = {
call: types.DeleteInitiative;
response: types.ProjectOperationComplete;
};
+ DeleteRoutine: { call: types.DeleteRoutine; response: types.DeletedRoutine };
DeleteTag: { call: types.DeleteTag; response: types.DeleteTagResponse };
DescribeDatabase: {
call: types.DescribeDatabase;
@@ -108,14 +130,26 @@ type ToolParserMap = {
call: types.DisplayResults;
response: types.DisplayResultsResponse;
};
+ DuplicateItem: {
+ call: types.DuplicateItem;
+ response: types.DuplicateItemResponse;
+ };
EditBookingLink: {
call: types.EditBookingLink;
response: types.BookingLinkResult;
};
+ EditChannelMessage: {
+ call: types.EditChannelMessage;
+ response: types.EditChannelMessageResponse;
+ };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
};
+ EditDocumentComment: {
+ call: types.EditDocumentComment;
+ response: types.EditDocumentCommentResponse;
+ };
EditForm: { call: types.EditForm; response: types.MutationResult };
EditPresentation: {
call: types.EditPresentation;
@@ -238,11 +272,24 @@ type ToolParserMap = {
call: types.MoveToProject;
response: types.MoveToProjectResponse;
};
+ MoveToTrash: { call: types.MoveToTrash; response: types.MoveToTrashResponse };
+ MuteNotifications: {
+ call: types.MuteNotifications;
+ response: types.MuteNotificationsResponse;
+ };
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
+ OpenDirectMessage: {
+ call: types.OpenDirectMessage;
+ response: types.OpenDirectMessageResponse;
+ };
QueryDatabase: {
call: types.QueryDatabase;
response: types.QueryDatabaseResponse;
};
+ ReactToChannelMessage: {
+ call: types.ReactToChannelMessage;
+ response: types.ReactToChannelMessageResponse;
+ };
ReadActivity: {
call: types.ReadActivity;
response: types.ReadActivityResponse;
@@ -315,10 +362,12 @@ type ToolParserMap = {
call: types.RenameDocument;
response: types.RenameDocumentResponse;
};
+ RenameItem: { call: types.RenameItem; response: types.RenameItemResponse };
ResolveDocumentComment: {
call: types.ResolveDocumentComment;
response: types.ResolveDocumentCommentResponse;
};
+ RunRoutine: { call: types.RunRoutine; response: types.RoutineRunStarted };
SaveDatabaseQuery: {
call: types.SaveDatabaseQuery;
response: types.SaveDatabaseQueryResponse;
@@ -352,6 +401,7 @@ type ToolParserMap = {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
};
+ SetFavorite: { call: types.SetFavorite; response: types.SetFavoriteResponse };
SetFormAccess: { call: types.SetFormAccess; response: types.MutationResult };
SetSenderPolicy: {
call: types.SetSenderPolicy;
@@ -374,6 +424,10 @@ type ToolParserMap = {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
};
+ UpdateCallRecord: {
+ call: types.UpdateCallRecord;
+ response: types.UpdateCallRecordResponse;
+ };
UpdateInitiative: {
call: types.UpdateInitiative;
response: types.ProjectDetails;
@@ -383,6 +437,10 @@ type ToolParserMap = {
response: types.ProjectDetails;
};
UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };
+ UpdateSharing: {
+ call: types.UpdateSharing;
+ response: types.UpdateSharingResponse;
+ };
UpdateThreadLabels: {
call: types.UpdateThreadLabels;
response: types.UpdateThreadLabelsResponse;
@@ -435,10 +493,18 @@ const toolParserMap = {
call: schemas.CreateChannel,
response: schemas.CreateChannelResponse,
},
+ CreateCompany: {
+ call: schemas.CreateCompany,
+ response: schemas.CreateCompanyResponse,
+ },
CreateConfirmedCalendarEvent: {
call: schemas.CreateConfirmedCalendarEvent,
response: schemas.ToolCalendarEvent,
},
+ CreateContact: {
+ call: schemas.CreateContact,
+ response: schemas.CreateContactResponse,
+ },
CreateDocument: {
call: schemas.CreateDocument,
response: schemas.CreateDocumentResponse,
@@ -457,16 +523,32 @@ const toolParserMap = {
response: schemas.CreateProjectResponse,
},
CreateRoutine: { call: schemas.CreateRoutine, response: schemas.RoutineInfo },
+ CreateSkill: {
+ call: schemas.CreateSkill,
+ response: schemas.CreateSkillResponse,
+ },
CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },
DeleteBot: { call: schemas.DeleteBot, response: schemas.DeleteBotResponse },
DeleteCalendarEvent: {
call: schemas.DeleteCalendarEvent,
response: schemas.DeleteCalendarEventResponse,
},
+ DeleteCallRecord: {
+ call: schemas.DeleteCallRecord,
+ response: schemas.DeleteCallRecordResponse,
+ },
+ DeleteChannelMessage: {
+ call: schemas.DeleteChannelMessage,
+ response: schemas.DeleteChannelMessageResponse,
+ },
DeleteDatabaseView: {
call: schemas.DeleteDatabaseView,
response: schemas.DeletedDatabaseView,
},
+ DeleteDocumentComment: {
+ call: schemas.DeleteDocumentComment,
+ response: schemas.DeleteDocumentCommentResponse,
+ },
DeleteImportEntity: {
call: schemas.DeleteImportEntity,
response: schemas.DeleteImportEntityResponse,
@@ -475,6 +557,10 @@ const toolParserMap = {
call: schemas.DeleteInitiative,
response: schemas.ProjectOperationComplete,
},
+ DeleteRoutine: {
+ call: schemas.DeleteRoutine,
+ response: schemas.DeletedRoutine,
+ },
DeleteTag: { call: schemas.DeleteTag, response: schemas.DeleteTagResponse },
DescribeDatabase: {
call: schemas.DescribeDatabase,
@@ -492,14 +578,26 @@ const toolParserMap = {
call: schemas.DisplayResults,
response: schemas.DisplayResultsResponse,
},
+ DuplicateItem: {
+ call: schemas.DuplicateItem,
+ response: schemas.DuplicateItemResponse,
+ },
EditBookingLink: {
call: schemas.EditBookingLink,
response: schemas.BookingLinkResult,
},
+ EditChannelMessage: {
+ call: schemas.EditChannelMessage,
+ response: schemas.EditChannelMessageResponse,
+ },
EditDocument: {
call: schemas.EditDocument,
response: schemas.EditDocumentResponse,
},
+ EditDocumentComment: {
+ call: schemas.EditDocumentComment,
+ response: schemas.EditDocumentCommentResponse,
+ },
EditForm: { call: schemas.EditForm, response: schemas.MutationResult },
EditPresentation: {
call: schemas.EditPresentation,
@@ -640,14 +738,30 @@ const toolParserMap = {
call: schemas.MoveToProject,
response: schemas.MoveToProjectResponse,
},
+ MoveToTrash: {
+ call: schemas.MoveToTrash,
+ response: schemas.MoveToTrashResponse,
+ },
+ MuteNotifications: {
+ call: schemas.MuteNotifications,
+ response: schemas.MuteNotificationsResponse,
+ },
NameSearch: {
call: schemas.NameSearch,
response: schemas.SearchToolResponse,
},
+ OpenDirectMessage: {
+ call: schemas.OpenDirectMessage,
+ response: schemas.OpenDirectMessageResponse,
+ },
QueryDatabase: {
call: schemas.QueryDatabase,
response: schemas.QueryDatabaseResponse,
},
+ ReactToChannelMessage: {
+ call: schemas.ReactToChannelMessage,
+ response: schemas.ReactToChannelMessageResponse,
+ },
ReadActivity: {
call: schemas.ReadActivity,
response: schemas.ReadActivityResponse,
@@ -729,10 +843,15 @@ const toolParserMap = {
call: schemas.RenameDocument,
response: schemas.RenameDocumentResponse,
},
+ RenameItem: {
+ call: schemas.RenameItem,
+ response: schemas.RenameItemResponse,
+ },
ResolveDocumentComment: {
call: schemas.ResolveDocumentComment,
response: schemas.ResolveDocumentCommentResponse,
},
+ RunRoutine: { call: schemas.RunRoutine, response: schemas.RoutineRunStarted },
SaveDatabaseQuery: {
call: schemas.SaveDatabaseQuery,
response: schemas.SaveDatabaseQueryResponse,
@@ -769,6 +888,10 @@ const toolParserMap = {
call: schemas.SetEntityProperty,
response: schemas.SetEntityPropertyResponse,
},
+ SetFavorite: {
+ call: schemas.SetFavorite,
+ response: schemas.SetFavoriteResponse,
+ },
SetFormAccess: {
call: schemas.SetFormAccess,
response: schemas.MutationResult,
@@ -794,6 +917,10 @@ const toolParserMap = {
call: schemas.UpdateCalendarEvent,
response: schemas.ToolCalendarEvent,
},
+ UpdateCallRecord: {
+ call: schemas.UpdateCallRecord,
+ response: schemas.UpdateCallRecordResponse,
+ },
UpdateInitiative: {
call: schemas.UpdateInitiative,
response: schemas.ProjectDetails,
@@ -803,6 +930,10 @@ const toolParserMap = {
response: schemas.ProjectDetails,
},
UpdateRoutine: { call: schemas.UpdateRoutine, response: schemas.RoutineInfo },
+ UpdateSharing: {
+ call: schemas.UpdateSharing,
+ response: schemas.UpdateSharingResponse,
+ },
UpdateThreadLabels: {
call: schemas.UpdateThreadLabels,
response: schemas.UpdateThreadLabelsResponse,
@@ -866,10 +997,18 @@ type ToolDataMap = {
call: types.CreateChannel;
response: types.CreateChannelResponse;
};
+ CreateCompany: {
+ call: types.CreateCompany;
+ response: types.CreateCompanyResponse;
+ };
CreateConfirmedCalendarEvent: {
call: types.CreateConfirmedCalendarEvent;
response: types.ToolCalendarEvent;
};
+ CreateContact: {
+ call: types.CreateContact;
+ response: types.CreateContactResponse;
+ };
CreateDocument: {
call: types.CreateDocument;
response: types.CreateDocumentResponse;
@@ -888,16 +1027,29 @@ type ToolDataMap = {
response: types.CreateProjectResponse;
};
CreateRoutine: { call: types.CreateRoutine; response: types.RoutineInfo };
+ CreateSkill: { call: types.CreateSkill; response: types.CreateSkillResponse };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };
DeleteCalendarEvent: {
call: types.DeleteCalendarEvent;
response: types.DeleteCalendarEventResponse;
};
+ DeleteCallRecord: {
+ call: types.DeleteCallRecord;
+ response: types.DeleteCallRecordResponse;
+ };
+ DeleteChannelMessage: {
+ call: types.DeleteChannelMessage;
+ response: types.DeleteChannelMessageResponse;
+ };
DeleteDatabaseView: {
call: types.DeleteDatabaseView;
response: types.DeletedDatabaseView;
};
+ DeleteDocumentComment: {
+ call: types.DeleteDocumentComment;
+ response: types.DeleteDocumentCommentResponse;
+ };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -906,6 +1058,7 @@ type ToolDataMap = {
call: types.DeleteInitiative;
response: types.ProjectOperationComplete;
};
+ DeleteRoutine: { call: types.DeleteRoutine; response: types.DeletedRoutine };
DeleteTag: { call: types.DeleteTag; response: types.DeleteTagResponse };
DescribeDatabase: {
call: types.DescribeDatabase;
@@ -923,14 +1076,26 @@ type ToolDataMap = {
call: types.DisplayResults;
response: types.DisplayResultsResponse;
};
+ DuplicateItem: {
+ call: types.DuplicateItem;
+ response: types.DuplicateItemResponse;
+ };
EditBookingLink: {
call: types.EditBookingLink;
response: types.BookingLinkResult;
};
+ EditChannelMessage: {
+ call: types.EditChannelMessage;
+ response: types.EditChannelMessageResponse;
+ };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
};
+ EditDocumentComment: {
+ call: types.EditDocumentComment;
+ response: types.EditDocumentCommentResponse;
+ };
EditForm: { call: types.EditForm; response: types.MutationResult };
EditPresentation: {
call: types.EditPresentation;
@@ -1053,11 +1218,24 @@ type ToolDataMap = {
call: types.MoveToProject;
response: types.MoveToProjectResponse;
};
+ MoveToTrash: { call: types.MoveToTrash; response: types.MoveToTrashResponse };
+ MuteNotifications: {
+ call: types.MuteNotifications;
+ response: types.MuteNotificationsResponse;
+ };
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
+ OpenDirectMessage: {
+ call: types.OpenDirectMessage;
+ response: types.OpenDirectMessageResponse;
+ };
QueryDatabase: {
call: types.QueryDatabase;
response: types.QueryDatabaseResponse;
};
+ ReactToChannelMessage: {
+ call: types.ReactToChannelMessage;
+ response: types.ReactToChannelMessageResponse;
+ };
ReadActivity: {
call: types.ReadActivity;
response: types.ReadActivityResponse;
@@ -1130,10 +1308,12 @@ type ToolDataMap = {
call: types.RenameDocument;
response: types.RenameDocumentResponse;
};
+ RenameItem: { call: types.RenameItem; response: types.RenameItemResponse };
ResolveDocumentComment: {
call: types.ResolveDocumentComment;
response: types.ResolveDocumentCommentResponse;
};
+ RunRoutine: { call: types.RunRoutine; response: types.RoutineRunStarted };
SaveDatabaseQuery: {
call: types.SaveDatabaseQuery;
response: types.SaveDatabaseQueryResponse;
@@ -1167,6 +1347,7 @@ type ToolDataMap = {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
};
+ SetFavorite: { call: types.SetFavorite; response: types.SetFavoriteResponse };
SetFormAccess: { call: types.SetFormAccess; response: types.MutationResult };
SetSenderPolicy: {
call: types.SetSenderPolicy;
@@ -1189,6 +1370,10 @@ type ToolDataMap = {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
};
+ UpdateCallRecord: {
+ call: types.UpdateCallRecord;
+ response: types.UpdateCallRecordResponse;
+ };
UpdateInitiative: {
call: types.UpdateInitiative;
response: types.ProjectDetails;
@@ -1198,6 +1383,10 @@ type ToolDataMap = {
response: types.ProjectDetails;
};
UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };
+ UpdateSharing: {
+ call: types.UpdateSharing;
+ response: types.UpdateSharingResponse;
+ };
UpdateThreadLabels: {
call: types.UpdateThreadLabels;
response: types.UpdateThreadLabelsResponse;
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.ts
index 436d5b23ed..9612e62219 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
@@ -1043,6 +1043,10 @@ export type DiscoveryResult =
tools_truncated: boolean;
operation: 'inspect';
};
+/**
+ * The kind of item to duplicate.
+ */
+export type DuplicableEntityType = 'document' | 'chat';
/**
* Targeted layout operations. Removing placements always retains response columns.
*/
@@ -3723,6 +3727,14 @@ export type ParticipantAction = 'add' | 'remove';
* The kind of entity to move.
*/
export type MoveableEntityType = 'document' | 'chat' | 'email' | 'project';
+/**
+ * The kind of item to move to the trash.
+ */
+export type TrashableEntityType = 'document' | 'chat' | 'project';
+/**
+ * What to do with an item's notifications.
+ */
+export type MuteAction = 'mute' | 'snooze' | 'unmute';
/**
* Presentation hint for a query result; it does not affect SQL execution.
*/
@@ -3875,6 +3887,10 @@ export type SqlStatement =
to: string;
kind: 'alterColumnType';
};
+/**
+ * Whether to add or remove a reaction.
+ */
+export type ReactionAction = 'add' | 'remove';
/**
* One activity action returned to the AI.
*/
@@ -4242,6 +4258,10 @@ export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';
* The kind of an item inside a project.
*/
export type ProjectItemType = 'document' | 'chat' | 'project';
+/**
+ * The kind of item to rename.
+ */
+export type RenameableEntityType = 'project' | 'chat';
/**
* A sort direction. Empty cells sort last either way.
*/
@@ -4346,6 +4366,18 @@ export type ToolEntityType =
| 'user'
| 'company'
| 'contact';
+/**
+ * The kinds of item a user can favorite.
+ */
+export type FavoritableEntityType =
+ | 'document'
+ | 'project'
+ | 'chat'
+ | 'channel'
+ | 'email'
+ | 'call'
+ | 'crm_company'
+ | 'crm_contact';
/**
* An explicit channel grant delta; omitted channels stay unchanged.
*/
@@ -4440,6 +4472,18 @@ export type RoutineChange =
configuration: RoutineConfiguration;
type: 'configuration';
};
+/**
+ * The kind of item whose sharing changes.
+ */
+export type SharingEntityType = 'document' | 'chat' | 'project';
+/**
+ * Who an item's share link admits.
+ */
+export type ShareLinkScope = 'off' | 'public' | 'team';
+/**
+ * A share can be disabled or grant a non-owner permission.
+ */
+export type ShareAccess = 'off' | 'view' | 'comment' | 'edit';
/**
* Content of a web fetch response - either a successful result or an error
*/
@@ -6546,6 +6590,37 @@ export interface CreateChannelResponse {
*/
summary: string;
}
+/**
+ * Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
+ */
+export interface CreateCompany {
+ /**
+ * The company's display name, e.g. "Acme".
+ */
+ name: string;
+ /**
+ * The company's web domain, e.g. "acme.com" — no scheme or path. Contacts are matched to the company by this domain.
+ */
+ domain: string;
+}
+/**
+ * The created company.
+ */
+export interface CreateCompanyResponse {
+ /**
+ * The new CRM company id (usable with GetCompany, CreateContact, and
+ * SetEntityProperty).
+ */
+ companyId: string;
+ /**
+ * The company's display name.
+ */
+ name?: string | null;
+ /**
+ * The company's domains.
+ */
+ domains: string[];
+}
/**
* Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet or Macro call, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.
*/
@@ -6597,6 +6672,44 @@ export interface CreateConfirmedCalendarEvent {
*/
userConfirmation: string;
}
+/**
+ * Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany.
+ */
+export interface CreateContact {
+ /**
+ * The CRM company id to add the contact to.
+ */
+ companyId: string;
+ /**
+ * The contact's name.
+ */
+ name: string;
+ /**
+ * The contact's email address, e.g. "[email protected]".
+ */
+ email: string;
+}
+/**
+ * The created contact.
+ */
+export interface CreateContactResponse {
+ /**
+ * The new CRM contact id.
+ */
+ contactId: string;
+ /**
+ * The company the contact belongs to.
+ */
+ companyId: string;
+ /**
+ * The contact's email.
+ */
+ email: string;
+ /**
+ * The contact's display name.
+ */
+ name?: string | null;
+}
/**
* Create a plaintext document or a native Macro spreadsheet. For a workbook use fileExtension spreadsheet, empty fileContent, and isTask false; then ReadSpreadsheet and EditSpreadsheet to populate cells, formulas and sheets. Works without an open editor.
*/
@@ -7207,6 +7320,32 @@ export interface RoutineInfo {
*/
nextRunAt?: string | null;
}
+/**
+ * Create a skill: a markdown document of reusable instructions that AI reads and follows when the skill is referenced, as Compose Skill in the app does. Write the instructions as the markdown body. Edit an existing skill with EditDocument; find skills with ListSkills or SearchSkills.
+ */
+export interface CreateSkill {
+ /**
+ * The skill's name.
+ */
+ skillName: string;
+ /**
+ * The skill's instructions, in markdown.
+ */
+ markdown: string;
+ /**
+ * The id of the project (shown as a folder in the app UI) to create the skill in. Requires edit access to the project. Omit to create it at the top level of the user's files.
+ */
+ projectId?: string | null;
+}
+/**
+ * The created skill.
+ */
+export interface CreateSkillResponse {
+ /**
+ * The id of the skill document.
+ */
+ documentId: string;
+}
/**
* Create a new tag — a colored label the user can apply to documents, emails, tasks, AI chats, and projects — in the user's personal set or their team's shared set. The set is provisioned automatically the first time a tag is created. Tags are matched by label, so call ListTags first and avoid creating one whose label duplicates an existing tag in the same set. Returns the new tag's id and its set's propertyDefinitionId, which you can pass straight to SetEntityProperty (add_option_ids) to apply the tag to an item. Use this only to create a brand-new tag; to apply an existing tag to an item, use ListTags then SetEntityProperty instead.
*/
@@ -7303,6 +7442,54 @@ export interface DeleteCalendarEventResponse {
*/
summary: string;
}
+/**
+ * Permanently delete a finished call with its recording and transcript, as Delete on a call does. This cannot be undone. Requires edit access to the call; calls still in progress cannot be deleted. Use only when the user explicitly asks to delete a call.
+ */
+export interface DeleteCallRecord {
+ /**
+ * The id of the call to delete.
+ */
+ callId: string;
+}
+/**
+ * The deleted call.
+ */
+export interface DeleteCallRecordResponse {
+ /**
+ * The deleted call.
+ */
+ callId: string;
+}
+/**
+ * Delete a channel message or thread reply. The channel keeps a 'message deleted' placeholder; this cannot be undone. Users can delete their own messages and messages sent by bots; channel admins and owners can delete any message. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user explicitly asks to delete a message.
+ */
+export interface DeleteChannelMessage {
+ /**
+ * Channel id containing the message.
+ */
+ channelId: string;
+ /**
+ * Id of the message to delete.
+ */
+ messageId: string;
+}
+/**
+ * Response from [`DeleteChannelMessage`].
+ */
+export interface DeleteChannelMessageResponse {
+ /**
+ * Channel containing the message.
+ */
+ channelId: string;
+ /**
+ * Deleted message.
+ */
+ messageId: string;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Delete a saved table or board view of a Macro database by its id, from DescribeDatabase. Views are shared with everyone who can open the database, so deleting one needs edit access and removes it for everyone. The table and its records stay; a board's hand-arranged card order goes with it. Only do it when the user asked for that view to go.
*/
@@ -7337,6 +7524,36 @@ export interface DeletedDatabaseView {
*/
name: string;
}
+/**
+ * Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead.
+ */
+export interface DeleteDocumentComment {
+ /**
+ * The id of the document the comment is on.
+ */
+ documentId: string;
+ /**
+ * The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread.
+ */
+ commentId: string;
+}
+/**
+ * The deleted comment.
+ */
+export interface DeleteDocumentCommentResponse {
+ /**
+ * The document the comment was on.
+ */
+ documentId: string;
+ /**
+ * The deleted comment.
+ */
+ commentId: string;
+ /**
+ * Whether the whole thread was deleted.
+ */
+ deletedThread: boolean;
+}
/**
* Decline a staged import candidate on the user's behalf. The item is remembered as declined so it won't be proposed again; only the user's own staged items can be declined.
*/
@@ -7377,6 +7594,24 @@ export interface ProjectOperationComplete {
*/
success: boolean;
}
+/**
+ * Permanently delete a routine owned by the authenticated user, stopping all future runs. This cannot be undone; to stop it temporarily, pause it with UpdateRoutine instead. Use only when the user explicitly asks to delete a routine.
+ */
+export interface DeleteRoutine {
+ /**
+ * Routine UUID.
+ */
+ routineId: string;
+}
+/**
+ * The deleted routine.
+ */
+export interface DeletedRoutine {
+ /**
+ * Routine UUID.
+ */
+ routineId: string;
+}
/**
* Permanently delete a tag from the user's personal set or their team's shared set. This removes the tag from every item it is currently applied to, so it is destructive and cannot be undone — confirm with the user first. Both ids come from a ListTags result: `id` is the tag's option id, and `property_definition_id` is the propertyDefinitionId of the set that contains it. To simply remove a tag from a single item without deleting the tag itself, use SetEntityProperty with remove_option_ids instead.
*/
@@ -7643,6 +7878,38 @@ export interface DisplayResults {
export interface DisplayResultsResponse {
message: string;
}
+/**
+ * Make a copy of a document (including a task) or an AI chat, owned by the user, as the Duplicate action in the app does. Requires view access to the original. Returns the copy's id.
+ */
+export interface DuplicateItem {
+ entityType: DuplicableEntityType;
+ /**
+ * The id of the item to duplicate.
+ */
+ entityId: string;
+ /**
+ * Name for the copy of a document. Omit to use "<original name> copy". AI chat copies always keep the original name.
+ */
+ name?: string | null;
+}
+/**
+ * The duplicate item response.
+ */
+export interface DuplicateItemResponse {
+ entityType: DuplicableEntityType;
+ /**
+ * The id of the original item.
+ */
+ sourceId: string;
+ /**
+ * The id of the new copy.
+ */
+ copyId: string;
+ /**
+ * A human-readable result message.
+ */
+ message: string;
+}
/**
* Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
*/
@@ -7666,6 +7933,40 @@ export interface EditBookingLink {
*/
userConfirmation: string;
}
+/**
+ * Replace the content of an existing channel message or thread reply. Only the message's author can edit it, so this edits messages the user sent and messages this assistant sent for them; channel admins and owners may also edit others' messages. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to edit or correct a message.
+ */
+export interface EditChannelMessage {
+ /**
+ * Channel id containing the message.
+ */
+ channelId: string;
+ /**
+ * Id of the message to edit.
+ */
+ messageId: string;
+ /**
+ * The full replacement message content in macro markdown format. This replaces the whole message, not a fragment of it.
+ */
+ content: string;
+}
+/**
+ * Response from [`EditChannelMessage`].
+ */
+export interface EditChannelMessageResponse {
+ /**
+ * Channel containing the message.
+ */
+ channelId: string;
+ /**
+ * Edited message.
+ */
+ messageId: string;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.
*/
@@ -7694,6 +7995,36 @@ export interface EditDocumentResponse {
*/
clarification?: string | null;
}
+/**
+ * Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment.
+ */
+export interface EditDocumentComment {
+ /**
+ * The id of the document the comment is on.
+ */
+ documentId: string;
+ /**
+ * The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id.
+ */
+ commentId: string;
+ /**
+ * The full replacement text of the comment, in markdown.
+ */
+ content: string;
+}
+/**
+ * The edited comment.
+ */
+export interface EditDocumentCommentResponse {
+ /**
+ * The document the comment is on.
+ */
+ documentId: string;
+ /**
+ * The edited comment.
+ */
+ commentId: string;
+}
/**
* Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/screeners and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep screeners after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
*/
@@ -9632,6 +9963,10 @@ export interface ListEntities {
* Filter returned items to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails. Macro tasks are returned as document items, so use includeTypes=["document"] with df subtype task for task requests. This is folded into the AST and applied as part of cursor-level filtering.
*/
includeTypes?: ItemType[] | null;
+ /**
+ * Only return items the user has favorited (starred). Use for requests like "my favorites" or "what have I starred". Combine with includeTypes and the other filters as usual. Favorite or unfavorite an item with SetFavorite.
+ */
+ favoritesOnly?: boolean;
sortBy?: SortBy;
/**
* Full soup AST document filter (df). Use the same shape as /items/soup/ast, e.g. {"l":{"id":"..."}}. For Macro tasks, use {"l":{"dst":"task"}}; for skills, {"l":{"dst":"skill"}}. For "completed yesterday", AND the task subtype with updatedAt bounds, e.g. {"&":[{"l":{"dst":"task"}},{"&":[{"l":{"ua":{"gte":"<start>"}}},{"l":{"ua":{"lt":"<end>"}}}]}]} using ISO timestamps.
@@ -10398,6 +10733,59 @@ export interface MoveToProjectResponse {
*/
message: string;
}
+/**
+ * Delete a document (including a task), an AI chat, or a project (folder) by moving it to the trash, as the Delete action in the app does. Trashing a project also trashes everything inside it. Only the item's owner can trash it. Use only when the user explicitly asks to delete an item. Channels, email threads, and calendar events are not deleted with this tool.
+ */
+export interface MoveToTrash {
+ entityType: TrashableEntityType;
+ /**
+ * The id of the item to move to the trash.
+ */
+ entityId: string;
+}
+/**
+ * The move to trash response.
+ */
+export interface MoveToTrashResponse {
+ entityType: TrashableEntityType;
+ /**
+ * The trashed item's id.
+ */
+ entityId: string;
+ /**
+ * A human-readable result message.
+ */
+ message: string;
+}
+/**
+ * Mute, snooze, or unmute notifications about one item for the user only, as Mute and Snooze in the app do. Muting never changes anyone else's notifications or the item itself. Use the entity type and id from ListNotifications or other tools.
+ */
+export interface MuteNotifications {
+ entityType: NotificationEntityType;
+ /**
+ * The item's id.
+ */
+ entityId: string;
+ action: MuteAction;
+ /**
+ * When notifications resume, as an ISO 8601 timestamp in the future. Required for snooze; omit otherwise.
+ */
+ snoozeUntil?: string | null;
+}
+/**
+ * The item's notification state after the change.
+ */
+export interface MuteNotificationsResponse {
+ /**
+ * The item's id.
+ */
+ entityId: string;
+ action: MuteAction;
+ /**
+ * When a snooze ends.
+ */
+ snoozeUntil?: string | null;
+}
/**
* Search items by their name or title: document name, email subject, chat title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).
*/
@@ -10421,6 +10809,36 @@ export interface NameSearch {
tags?: TagFilter[] | null;
tagsMatch?: TagMatch;
}
+/**
+ * Find the user's direct-message conversation with one or more people, creating it if it does not exist yet, and return its channel id. One person opens a 1:1 DM; several open a group DM with exactly that set of people. Use this before SendChannelMessage when the user asks to message someone directly and no channel id is known. Find people with ListTeamMembers.
+ */
+export interface OpenDirectMessage {
+ /**
+ * The other people in the conversation, as Macro user ids (`macro|<email>`) or emails. Do not include the user.
+ */
+ participants: string[];
+}
+/**
+ * Response from [`OpenDirectMessage`].
+ */
+export interface OpenDirectMessageResponse {
+ /**
+ * The direct-message channel.
+ */
+ channelId: string;
+ /**
+ * Whether the conversation was newly created.
+ */
+ created: boolean;
+ /**
+ * Canonical ids of the other participants.
+ */
+ participants: string[];
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Run SQL against the current user's Macro databases — the only way to read or change their rows. SELECT to answer a question, INSERT/UPDATE/DELETE to change data, CREATE/ALTER/DROP to edit schema. One statement per call.
*
@@ -10600,6 +11018,46 @@ export interface SelectOption {
*/
label: string;
}
+/**
+ * Add or remove the user's own emoji reaction on a channel message or thread reply. The reaction is shown as coming from the user. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to react to a message.
+ */
+export interface ReactToChannelMessage {
+ /**
+ * Channel id containing the message.
+ */
+ channelId: string;
+ /**
+ * Id of the message to react to.
+ */
+ messageId: string;
+ /**
+ * The emoji itself as a Unicode character, for example 👍 or 🎉 — not a shortcode like :thumbsup:.
+ */
+ emoji: string;
+ action?: ReactionAction & string;
+}
+/**
+ * Response from [`ReactToChannelMessage`].
+ */
+export interface ReactToChannelMessageResponse {
+ /**
+ * Channel containing the message.
+ */
+ channelId: string;
+ /**
+ * Message reacted to.
+ */
+ messageId: string;
+ /**
+ * Emoji added or removed.
+ */
+ emoji: string;
+ action: ReactionAction;
+ /**
+ * How many people reacted with this emoji after the change.
+ */
+ count: number;
+}
/**
* Read actions attributed to the authenticated user within a time range, newest first. Use this for questions about what the user did, including actions an agent performed on their behalf. Property changes include propertyName/propertyType plus fromLabels/toLabels for resolved select and tag values; use those human-readable fields in the answer and never expose property or option ids. Do not use this for organization-wide updates or everything that happened to entities the user can access; use ListEntities for those. Returns at most 100 activities and reports when the result was truncated.
*/
@@ -12044,6 +12502,34 @@ export interface RenameDocumentResponse {
*/
message: string;
}
+/**
+ * Rename a project (shown as a folder in the app) or an AI chat. Renaming a project requires edit access; renaming an AI chat requires owning it. Use RenameDocument for documents and tasks, and RenameChannel for channels.
+ */
+export interface RenameItem {
+ entityType: RenameableEntityType;
+ /**
+ * The id of the item to rename.
+ */
+ entityId: string;
+ /**
+ * The new name.
+ */
+ name: string;
+}
+/**
+ * The rename item response.
+ */
+export interface RenameItemResponse {
+ entityType: RenameableEntityType;
+ /**
+ * The renamed item's id.
+ */
+ entityId: string;
+ /**
+ * The new name.
+ */
+ name: string;
+}
/**
* Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns.
*/
@@ -12078,6 +12564,30 @@ export interface ResolveDocumentCommentResponse {
*/
resolved: boolean;
}
+/**
+ * Start a routine owned by the authenticated user now, outside its schedule, as Run Now in the app does. The run continues after this returns; check its result later with ReadRoutine. Fails if the routine is already running.
+ */
+export interface RunRoutine {
+ /**
+ * Routine UUID.
+ */
+ routineId: string;
+}
+/**
+ * A run started on demand; it continues after the call returns.
+ */
+export interface RoutineRunStarted {
+ /**
+ * The routine that is running.
+ */
+ routineId: string;
+ /**
+ * The chat or agent session the run writes to, when the scheduler reports one.
+ */
+ resource?: {
+ [k: string]: unknown;
+ };
+}
/**
* Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim, into your reply or into a document with CreateDocument/EditDocument, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
*
@@ -12533,6 +13043,34 @@ export interface SetEntityPropertyResponse {
success: boolean;
message: string;
}
+/**
+ * Add an item to the user's favorites (shown starred in the app sidebar) or remove it, as the Favorite action does. Requires view access to add an item. List favorites with ListEntities and favoritesOnly.
+ */
+export interface SetFavorite {
+ entityType: FavoritableEntityType;
+ /**
+ * The id of the item.
+ */
+ entityId: string;
+ /**
+ * True to add the item to favorites, false to remove it.
+ */
+ favorite: boolean;
+}
+/**
+ * The item's favorite state after the change.
+ */
+export interface SetFavoriteResponse {
+ entityType: FavoritableEntityType;
+ /**
+ * The item's id.
+ */
+ entityId: string;
+ /**
+ * Whether the item is now a favorite.
+ */
+ favorite: boolean;
+}
/**
* Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Public allows anonymous responses. View allows responding without database access; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open.
*/
@@ -12799,6 +13337,36 @@ export interface UpdateCalendarEvent {
*/
outOfOffice?: OutOfOfficeInput | null;
}
+/**
+ * Rename a recorded call or change whether it is shared with the team, as the call's header menu does. Requires edit access to the call; only the call's creator can change team sharing on a finished call. Find calls with ListEntities or NameSearch.
+ */
+export interface UpdateCallRecord {
+ /**
+ * The id of the call.
+ */
+ callId: string;
+ /**
+ * New display name for the call. An empty string clears the custom name. Omit to leave it unchanged.
+ */
+ name?: string | null;
+ /**
+ * True to share the call with the creator's team (view access), false to stop sharing it. Omit to leave it unchanged.
+ */
+ shareWithTeam?: boolean | null;
+}
+/**
+ * The changed call.
+ */
+export interface UpdateCallRecordResponse {
+ /**
+ * The changed call.
+ */
+ callId: string;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Rename a project with edit access, or replace its collaboration member list as the owner. Members control sharing independently of the assignee property. Assigning a user grants collaboration access; removing an assignment retains that access. For status, priority, assignees and due date use SetEntityProperty with entity_type='initiative'.
*/
@@ -12861,6 +13429,56 @@ export interface UpdateRoutine {
routineId: string;
change: RoutineChange;
}
+/**
+ * Change who can access a document (including a task), an AI chat, or a project (folder), as the Share menu in the app does: link sharing, team access, and per-channel access. Each omitted field stays unchanged; off disables that share. Requires edit access to a document, or owning an AI chat or project; only the owner can change team access. Use ShareWithChannel to post an item into a channel, and UpdateInitiativeSharing for Tasks projects (initiatives).
+ */
+export interface UpdateSharing {
+ entityType: SharingEntityType;
+ /**
+ * The id of the item whose sharing changes.
+ */
+ entityId: string;
+ /**
+ * Who the item's share link admits: public (anyone with the link), team (the owner's team members with the link), or off to disable link sharing.
+ */
+ linkScope?: ShareLinkScope | null;
+ /**
+ * Permission granted by an enabled share link. Off resets it to the default level.
+ */
+ linkAccess?: ShareAccess | null;
+ /**
+ * Access for everyone on the owner's team; off removes it.
+ */
+ teamAccess?: ShareAccess | null;
+ /**
+ * Individual channel grants to set or remove; other channel grants stay unchanged.
+ */
+ channels?: SharingChannel[] | null;
+}
+/**
+ * One channel's grant to set or remove.
+ */
+export interface SharingChannel {
+ /**
+ * Channel id to share with or revoke.
+ */
+ channelId: string;
+ access: ShareAccess;
+}
+/**
+ * The update sharing response.
+ */
+export interface UpdateSharingResponse {
+ entityType: SharingEntityType;
+ /**
+ * The item's id.
+ */
+ entityId: string;
+ /**
+ * A human-readable summary of the change.
+ */
+ message: string;
+}
/**
* Add or remove a single label from every message in a Gmail thread. In Gmail, nearly all inbox operations are just label add/remove operations, so this tool is the primitive for archiving, marking read/unread, starring, trashing, marking important/spam, and applying or removing custom labels.
*
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index a5adebe5cd..ed08c6aac3 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
test-support = []
[dependencies]
+favorites = { path = "../favorites", features = ["ai_tools", "postgres"] }
forms = { path = "../forms", features = ["ai_tools", "gateway", "postgres", "scheduling"] }
routines = { path = "../routines" }
macro_auth = { path = "../macro_auth" }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index df62ec90f2..f7340c1496 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -269,17 +269,21 @@ pub async fn build_tool_service_context_from_env(
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
PgGithubPullRequestRepo::new(pool.clone()),
);
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(ReadOnlyPool(pool.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- ),
- crm::domain::service::NoOpCrmService,
- github_pull_request_service,
- ));
+ let favorites_service = crate::tool_context::build_favorites_service(pool.clone());
+ let soup_service = Arc::new(
+ SoupImpl::new(
+ PgSoupRepo::new(ReadOnlyPool(pool.clone())),
+ frecency_service,
+ ReadonlyEmailPreviewAdapter(email_service),
+ channels_service,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
+ crm::domain::service::NoOpCrmService,
+ github_pull_request_service,
+ )
+ .with_favorites(favorites_service.clone()),
+ );
let s3_client = macro_aws_config::s3_client().await;
let document_files = documents::outbound::s3_document_files::S3DocumentFiles::new(
@@ -618,6 +622,8 @@ pub async fn build_tool_service_context_from_env(
environment,
),
notification_tool_context,
+ item_notification_preference_tool_context:
+ crate::tool_context::build_item_notification_preference_tool_context(pool.clone()),
databases_tool_context,
forms_tool_context,
databases_sql_tool_context,
@@ -636,6 +642,10 @@ pub async fn build_tool_service_context_from_env(
env.internal_api_key.to_string(),
)?,
project_tool_context,
+ favorites_tool_context: crate::tool_context::build_favorites_tool_context(
+ favorites_service,
+ entity_access_service.clone(),
+ ),
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()),
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 5bb213e5dc..825230fc9b 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -41,9 +41,10 @@ use databases_sql::toolset::{QueryDatabase, databases_sql_toolset};
use display_results::DisplayResults;
use documents::inbound::toolset::document_toolset;
use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};
+use favorites::inbound::toolset::favorites_toolset;
use import::inbound::toolset::import_toolset;
use initiative::inbound::toolset::initiative_toolset;
-use notification::inbound::ai_tool::notification_toolset;
+use notification::inbound::ai_tool::{item_notification_preference_toolset, notification_toolset};
use projects::inbound::toolset::project_toolset;
use properties::inbound::toolset::properties_toolset;
use schemas::read;
@@ -77,21 +78,23 @@ pub use tool_context::{
ToolCrmService, ToolCrmToolContext, ToolDatabasesService, ToolDatabasesSqlToolContext,
ToolDatabasesToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,
ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
- ToolEntityCreator, ToolForeignEntityService, ToolFormsToolContext, ToolFrecencyService,
- ToolGithubPullRequestService, ToolImageGenerationToolContext, ToolImportService,
- ToolImportToolContext, ToolInitiativeToolContext, ToolMcpSelector, ToolNotificationQueue,
- ToolNotificationService, ToolNotificationToolContext, ToolPipedreamConnection,
- ToolProjectService, ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,
- ToolServiceContext, ToolSkillService, ToolSkillToolContext, ToolSoupService,
- ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,
+ ToolEntityCreator, ToolFavoritesService, ToolFavoritesToolContext, ToolForeignEntityService,
+ ToolFormsToolContext, ToolFrecencyService, ToolGithubPullRequestService,
+ ToolImageGenerationToolContext, ToolImportService, ToolImportToolContext,
+ ToolInitiativeToolContext, ToolItemNotificationPreferenceToolContext, ToolMcpSelector,
+ ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
+ ToolPipedreamConnection, 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,
build_calendar_tool_context, build_channel_tool_context_with_dispatcher,
build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
build_coding_agent_tool_context, build_crm_tool_context, build_databases_sql_tool_context,
- build_databases_tool_context, build_forms_tool_context, build_image_generation_tool_context,
- build_initiative_tool_context, build_message_service_with_side_effects,
+ 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,
@@ -149,6 +152,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
image_generation::inbound::toolset::image_generation_toolset(),
)
.add_subtoolset::<ToolProjectToolContext>(project_toolset())
+ .add_subtoolset::<ToolFavoritesToolContext>(favorites_toolset())
.add_subtoolset::<ToolInitiativeToolContext>(initiative_toolset())
.add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
.add_subtoolset::<ToolCallToolContext>(call_toolset())
@@ -236,6 +240,9 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
let toolset = subagent_toolset()
.add_subtoolset::<ToolBookingManagementToolContext>(booking_management_toolset())
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
+ .add_subtoolset::<ToolItemNotificationPreferenceToolContext>(
+ item_notification_preference_toolset(),
+ )
.add_subtoolset::<ToolTeamCalendarToolContext>(team_calendar_toolset())
.add_subtoolset::<RoutineToolContext>(routines::inbound::routine_toolset());
let toolset = match host {
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index ca4b655ae3..31d584a9cb 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -149,6 +149,49 @@ fn project_workflows_are_available_in_every_host_alongside_folder_and_property_t
}
}
+/// Every host, including MCP, can take the item actions the app's menus
+/// offer: editing channel messages and comments, trashing, duplicating,
+/// renaming, sharing, favoriting, and muting items, DMs, CRM records, calls,
+/// skills, and routines.
+#[test]
+fn app_item_actions_are_available_in_every_host() {
+ let names = [
+ "EditChannelMessage",
+ "DeleteChannelMessage",
+ "ReactToChannelMessage",
+ "OpenDirectMessage",
+ "EditDocumentComment",
+ "DeleteDocumentComment",
+ "CreateSkill",
+ "MoveToTrash",
+ "DuplicateItem",
+ "RenameItem",
+ "UpdateSharing",
+ "SetFavorite",
+ "MuteNotifications",
+ "RunRoutine",
+ "DeleteRoutine",
+ "CreateCompany",
+ "CreateContact",
+ "UpdateCallRecord",
+ "DeleteCallRecord",
+ ];
+ for host in [
+ AiHost::Chat,
+ AiHost::AgentSession,
+ AiHost::ChannelBot,
+ AiHost::Mcp,
+ ] {
+ let tools = tools_for(host);
+ for name in names {
+ assert!(
+ tools.toolset.tools.contains_key(name),
+ "{host:?} must expose {name}"
+ );
+ }
+ }
+}
+
/// Every host reads the design files the native engines open, and its
/// prompt says which tool reads which format.
#[test]
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index b22530ccd1..daea595bc5 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1162,6 +1162,21 @@ pub type ToolNotificationService = notification::domain::service::NotificationRe
/// Type alias for the notification tool context.
pub type ToolNotificationToolContext = NotificationToolContext<ToolNotificationService>;
+/// Type alias for the user's per-item notification mute and snooze tool context.
+pub type ToolItemNotificationPreferenceToolContext =
+ notification::inbound::ai_tool::ItemNotificationPreferenceToolContext<
+ notification::outbound::item_preferences::PgItemNotificationPreferenceRepository,
+ >;
+
+/// Build the per-item notification preference tool context.
+pub fn build_item_notification_preference_tool_context(
+ pool: sqlx::PgPool,
+) -> ToolItemNotificationPreferenceToolContext {
+ notification::inbound::ai_tool::ItemNotificationPreferenceToolContext::new(
+ notification::outbound::item_preferences::PgItemNotificationPreferenceRepository(pool),
+ )
+}
+
/// Table-changed fan-out for AI tool hosts, the databases crate's publisher.
pub use databases::outbound::gateway_event_publisher::MaybeGatewayTableEventPublisher as ToolTableEventPublisher;
@@ -1297,6 +1312,41 @@ pub fn build_project_tool_context(
)
}
+/// Type alias for the favorites service used by AI tools and soup's
+/// favorites-only filter.
+pub type ToolFavoritesService = favorites::domain::service::FavoritesServiceImpl<
+ favorites::outbound::pg_favorites_repo::PgFavoritesRepo,
+>;
+
+/// Type alias for the favorites tool context.
+pub type ToolFavoritesToolContext = favorites::inbound::toolset::FavoritesToolContext<
+ favorites::domain::mutation_service::FavoritesMutationServiceImpl<
+ ToolFavoritesService,
+ ToolEntityAccessService,
+ >,
+>;
+
+/// Build the favorites service shared by the favorites tools and soup.
+pub fn build_favorites_service(pool: sqlx::PgPool) -> Arc<ToolFavoritesService> {
+ Arc::new(favorites::domain::service::FavoritesServiceImpl::new(
+ favorites::outbound::pg_favorites_repo::PgFavoritesRepo::new(pool),
+ ))
+}
+
+/// Build the favorites tool context, authorizing favorites with the same
+/// entity access service as the other tools.
+pub fn build_favorites_tool_context(
+ favorites: Arc<ToolFavoritesService>,
+ entity_access_service: Arc<ToolEntityAccessService>,
+) -> ToolFavoritesToolContext {
+ favorites::inbound::toolset::FavoritesToolContext::new(Arc::new(
+ favorites::domain::mutation_service::FavoritesMutationServiceImpl::new(
+ favorites,
+ entity_access_service,
+ ),
+ ))
+}
+
/// Type alias for the chat tool context
pub type ToolChatToolContext = ChatToolContext<ToolChatService, ToolEntityAccessService>;
@@ -1661,6 +1711,8 @@ pub struct ToolServiceContext {
/// Calendar-service-backed booking administration.
pub booking_management_tool_context: ToolBookingManagementToolContext,
pub notification_tool_context: ToolNotificationToolContext,
+ /// The user's own per-item notification mutes and snoozes.
+ pub item_notification_preference_tool_context: ToolItemNotificationPreferenceToolContext,
pub databases_tool_context: ToolDatabasesToolContext,
pub forms_tool_context: ToolFormsToolContext,
pub databases_sql_tool_context: ToolDatabasesSqlToolContext,
@@ -1676,6 +1728,8 @@ pub struct ToolServiceContext {
pub bot_tool_context: ToolBotToolContext,
pub coding_agent_tool_context: ToolCodingAgentToolContext,
pub project_tool_context: ToolProjectToolContext,
+ /// Favorite toggles; the same favorites back `soup_service`'s favorites filter.
+ pub favorites_tool_context: ToolFavoritesToolContext,
/// Native task project lifecycle, properties, sharing and history.
pub initiative_tool_context: ToolInitiativeToolContext,
pub team_tool_context: ToolTeamToolContext,
diff --git a/crates/call/src/inbound/toolset.rs b/crates/call/src/inbound/toolset.rs
index 85bfe6ecdc..a9c10a74ba 100644
--- a/crates/call/src/inbound/toolset.rs
+++ b/crates/call/src/inbound/toolset.rs
@@ -1,16 +1,21 @@
//! Toolset inbound adapter for calls.
+mod delete_call_record;
mod read_call_record;
+mod update_call_record;
#[cfg(test)]
mod test;
-use crate::domain::ports::CallService;
-use ai_toolset::AsyncToolCollection;
-use entity_access::domain::ports::EntityAccessService;
+use crate::domain::{models::CallError, ports::CallService};
+use ai_toolset::{AsyncToolCollection, ToolCallError};
+use entity_access::domain::{models::AccessError, ports::EntityAccessService};
+use entity_mutation::DeleteEntityPermanently;
use std::sync::Arc;
+use delete_call_record::DeleteCallRecord;
use read_call_record::ReadCallRecord;
+use update_call_record::UpdateCallRecord;
/// Service context for call AI tools.
pub struct CallToolContext<CSvc, ESvc>
@@ -51,11 +56,49 @@ where
}
}
+/// Map a failure to mint a call receipt onto an actionable tool error.
+fn call_access_error(err: AccessError) -> ToolCallError {
+ let description = match err {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ "you need edit access to the call"
+ }
+ AccessError::NotFound(_) => "call not found",
+ AccessError::BadRequest(_) => "invalid call id",
+ AccessError::Unavailable(_) | AccessError::Internal(_) => {
+ "failed to verify access to the call"
+ }
+ };
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: err.into(),
+ }
+}
+
+/// Map a call domain failure onto an actionable tool error.
+fn call_error(action: &'static str) -> impl FnOnce(CallError) -> ToolCallError {
+ move |err| {
+ let description = match &err {
+ CallError::InvalidRequest(message)
+ | CallError::Forbidden(message)
+ | CallError::Conflict(message) => message.clone(),
+ CallError::NotFound(_) => "call not found".to_string(),
+ _ => format!("failed to {action}"),
+ };
+ ToolCallError {
+ description,
+ internal_error: err.into(),
+ }
+ }
+}
+
/// Create a call toolset.
pub fn call_toolset<CSvc, ESvc>() -> AsyncToolCollection<CallToolContext<CSvc, ESvc>>
where
- CSvc: CallService,
+ CSvc: CallService + DeleteEntityPermanently,
ESvc: EntityAccessService,
{
- AsyncToolCollection::new().add_tool::<ReadCallRecord, CallToolContext<CSvc, ESvc>>()
+ AsyncToolCollection::new()
+ .add_tool::<ReadCallRecord, CallToolContext<CSvc, ESvc>>()
+ .add_tool::<UpdateCallRecord, CallToolContext<CSvc, ESvc>>()
+ .add_tool::<DeleteCallRecord, CallToolContext<CSvc, ESvc>>()
}
diff --git a/crates/call/src/inbound/toolset/delete_call_record.rs b/crates/call/src/inbound/toolset/delete_call_record.rs
new file mode 100644
index 0000000000..9aa78aed2f
--- /dev/null
+++ b/crates/call/src/inbound/toolset/delete_call_record.rs
@@ -0,0 +1,92 @@
+//! DeleteCallRecord tool for permanently deleting a finished call.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::models::EntityType;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{DeleteEntityPermanently, EntityMutationErrorCode};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{CallToolContext, call_access_error};
+use crate::domain::ports::CallService;
+
+/// Permanently delete a finished call.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteCallRecord",
+ description = "Permanently delete a finished call with its recording and transcript, as Delete on a call does. This cannot be undone. Requires edit access to the call; calls still in progress cannot be deleted. Use only when the user explicitly asks to delete a call."
+)]
+pub struct DeleteCallRecord {
+ /// The call to delete.
+ #[schemars(description = "The id of the call to delete.")]
+ pub call_id: Uuid,
+}
+
+/// The deleted call.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteCallRecordResponse {
+ /// The deleted call.
+ pub call_id: Uuid,
+}
+
+impl ToolAnnotated for DeleteCallRecord {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Delete call").with_idempotent();
+}
+
+#[async_trait]
+impl<CSvc, ESvc> AsyncTool<CallToolContext<CSvc, ESvc>> for DeleteCallRecord
+where
+ CSvc: CallService + DeleteEntityPermanently,
+ ESvc: EntityAccessService,
+{
+ type Output = DeleteCallRecordResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, call_id=%self.call_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CallToolContext<CSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity = EntityType::Call.with_entity_string(self.call_id.to_string());
+ let receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<CSvc::Receipt>(
+ &request_context.user_id,
+ None,
+ &entity.entity_id,
+ entity.entity_type,
+ )
+ .await
+ .map_err(call_access_error)?;
+ service_context
+ .service
+ .delete_entity_permanently(entity, receipt)
+ .await
+ .map_err(|code| {
+ let description = match code {
+ EntityMutationErrorCode::Conflict(_) => {
+ "the call is still in progress; only finished calls can be deleted"
+ }
+ EntityMutationErrorCode::Forbidden(_) => {
+ "you need edit access to the call to delete it"
+ }
+ EntityMutationErrorCode::NotFound(_) => "call not found",
+ _ => "failed to delete the call",
+ };
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::anyhow!("delete call failed: {code:?}"),
+ }
+ })?;
+
+ Ok(DeleteCallRecordResponse {
+ call_id: self.call_id,
+ })
+ }
+}
diff --git a/crates/call/src/inbound/toolset/test.rs b/crates/call/src/inbound/toolset/test.rs
index 148ed91630..d21a5dee2b 100644
--- a/crates/call/src/inbound/toolset/test.rs
+++ b/crates/call/src/inbound/toolset/test.rs
@@ -16,3 +16,14 @@ fn test_read_call_record_schema_validation() {
"Description should contain expected text"
);
}
+
+#[test]
+fn test_call_mutation_schema_validation() {
+ use super::{delete_call_record::DeleteCallRecord, update_call_record::UpdateCallRecord};
+
+ let update = generate_validated_input_schema::<UpdateCallRecord>().expect("valid schema");
+ assert_eq!(update.name, "UpdateCallRecord");
+ let delete = generate_validated_input_schema::<DeleteCallRecord>().expect("valid schema");
+ assert_eq!(delete.name, "DeleteCallRecord");
+ assert!(delete.description.contains("cannot be undone"));
+}
diff --git a/crates/call/src/inbound/toolset/update_call_record.rs b/crates/call/src/inbound/toolset/update_call_record.rs
new file mode 100644
index 0000000000..4e765cd1be
--- /dev/null
+++ b/crates/call/src/inbound/toolset/update_call_record.rs
@@ -0,0 +1,116 @@
+//! UpdateCallRecord tool for renaming a call and sharing it with the team.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::models::{EditAccessLevel, EntityType};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{CallToolContext, call_access_error, call_error};
+use crate::domain::models::EditCallRecordRequest;
+use crate::domain::ports::CallService;
+
+/// Change a call's name or team sharing.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "UpdateCallRecord",
+ description = "Rename a recorded call or change whether it is shared with the team, as the call's header menu does. Requires edit access to the call; only the call's creator can change team sharing on a finished call. Find calls with ListEntities or NameSearch."
+)]
+pub struct UpdateCallRecord {
+ /// The call to change.
+ #[schemars(description = "The id of the call.")]
+ pub call_id: Uuid,
+ /// New display name.
+ #[schemars(
+ description = "New display name for the call. An empty string clears the custom name. Omit to leave it unchanged."
+ )]
+ #[serde(default)]
+ pub name: Option<String>,
+ /// Team sharing.
+ #[schemars(
+ description = "True to share the call with the creator's team (view access), false to stop sharing it. Omit to leave it unchanged."
+ )]
+ #[serde(default)]
+ pub share_with_team: Option<bool>,
+}
+
+/// The changed call.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateCallRecordResponse {
+ /// The changed call.
+ pub call_id: Uuid,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+impl ToolAnnotated for UpdateCallRecord {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Update call").with_idempotent();
+}
+
+#[async_trait]
+impl<CSvc, ESvc> AsyncTool<CallToolContext<CSvc, ESvc>> for UpdateCallRecord
+where
+ CSvc: CallService,
+ ESvc: EntityAccessService,
+{
+ type Output = UpdateCallRecordResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, call_id=%self.call_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CallToolContext<CSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.name.is_none() && self.share_with_team.is_none() {
+ return Err(ToolCallError {
+ description: "nothing to change: set name or shareWithTeam".to_string(),
+ internal_error: anyhow::anyhow!("empty call record update"),
+ });
+ }
+ let receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &request_context.user_id,
+ None,
+ &self.call_id.to_string(),
+ EntityType::Call,
+ )
+ .await
+ .map_err(call_access_error)?;
+ let name = self.name.as_deref().map(str::trim).map(str::to_string);
+ service_context
+ .service
+ .edit_call_record(
+ receipt,
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: self.share_with_team,
+ custom_name: name.clone(),
+ },
+ )
+ .await
+ .map_err(call_error("update the call"))?;
+
+ let mut changes = Vec::new();
+ match name.as_deref() {
+ Some("") => changes.push("cleared its custom name".to_string()),
+ Some(name) => changes.push(format!("renamed it to `{name}`")),
+ None => {}
+ }
+ match self.share_with_team {
+ Some(true) => changes.push("shared it with the team".to_string()),
+ Some(false) => changes.push("stopped sharing it with the team".to_string()),
+ None => {}
+ }
+ Ok(UpdateCallRecordResponse {
+ call_id: self.call_id,
+ summary: format!("Updated the call: {}.", changes.join(" and ")),
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rs
index b868fdc746..9c7f199958 100644
--- a/crates/channels/src/inbound/toolset.rs
+++ b/crates/channels/src/inbound/toolset.rs
@@ -1,7 +1,11 @@
//! AI tools for reading channel messages and mutating channel membership.
mod create_channel;
+mod delete_channel_message;
+mod edit_channel_message;
mod manage_channel_participants;
+mod open_direct_message;
+mod react_to_channel_message;
mod read_channel_message_context;
mod read_channel_messages;
mod read_channel_thread;
@@ -16,7 +20,10 @@ mod test;
use crate::{
domain::{models::Sender, ports::ChannelMutationErr, ports::ChannelService},
inbound::toolset::{
- create_channel::CreateChannel, manage_channel_participants::ManageChannelParticipants,
+ create_channel::CreateChannel, delete_channel_message::DeleteChannelMessage,
+ edit_channel_message::EditChannelMessage,
+ manage_channel_participants::ManageChannelParticipants,
+ open_direct_message::OpenDirectMessage, react_to_channel_message::ReactToChannelMessage,
rename_channel::RenameChannel, send_channel_message::SendChannelMessage,
share_with_channel::ShareWithChannel,
},
@@ -33,6 +40,7 @@ use entity_access::domain::{
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::MessageServiceApi,
+ ports::MessageError,
service::{MessageView, MessageWrite},
};
use std::sync::Arc;
@@ -118,6 +126,51 @@ where
self
}
+ /// Mint the requesting user's own channel write capability, for actions
+ /// the app attributes to the user rather than to the tool actor bot.
+ pub async fn require_user_message_write(
+ &self,
+ request_context: &RequestContext,
+ channel_id: Uuid,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
+ self.entity_access_service
+ .generate_entity_access_receipt::<MessageWrite>(
+ &request_context.user_id,
+ None,
+ &channel_id.to_string(),
+ EntityType::Channel,
+ )
+ .await
+ .map_err(channel_access_error)
+ }
+
+ /// Mint the write capability for changing an existing message as its
+ /// author: messages the tool actor bot posted are changed as the bot, and
+ /// every other message as the user, so the message service applies the
+ /// same authorship and moderation rules as in the app.
+ pub async fn require_message_author_write(
+ &self,
+ request_context: &RequestContext,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
+ let view = self
+ .require_channel_member(request_context, channel_id)
+ .await?;
+ let message = self
+ .messages
+ .get(view, message_id)
+ .await
+ .map_err(message_mutation_error("read the message"))?;
+ if message.sender_id == Sender::new_from_bot(self.actor) {
+ self.require_channel_message_write(request_context, channel_id)
+ .await
+ } else {
+ self.require_user_message_write(request_context, channel_id)
+ .await
+ }
+ }
+
/// Require that the request user is an active member of the channel before
/// reading it, minting the read capability the message reads take.
pub async fn require_channel_member(
@@ -252,6 +305,24 @@ fn channel_mutation_error(action: &'static str, err: ChannelMutationErr) -> Tool
}
}
+/// Map a message mutation failure onto an actionable tool error.
+fn message_mutation_error(action: &'static str) -> impl FnOnce(MessageError) -> ToolCallError {
+ move |err| {
+ let description = match &err {
+ MessageError::NotFound => "message not found in this channel".to_string(),
+ MessageError::Forbidden => format!(
+ "not allowed to {action}: only the message's author or a channel admin or owner can change it"
+ ),
+ MessageError::Invalid(message) => (*message).to_string(),
+ MessageError::Conflict | MessageError::Repository(_) => format!("failed to {action}"),
+ };
+ ToolCallError {
+ description,
+ internal_error: anyhow::Error::new(err),
+ }
+ }
+}
+
const MAX_CHANNEL_NAME_CHARS: usize = 255;
fn channel_name(name: &str) -> Result<String, ToolCallError> {
@@ -334,4 +405,8 @@ where
.add_tool::<CreateChannel, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<RenameChannel, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<ManageChannelParticipants, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<EditChannelMessage, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<DeleteChannelMessage, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<ReactToChannelMessage, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<OpenDirectMessage, ChannelToolContext<Svc, AccessSvc>>()
}
diff --git a/crates/channels/src/inbound/toolset/delete_channel_message.rs b/crates/channels/src/inbound/toolset/delete_channel_message.rs
new file mode 100644
index 0000000000..acfeecc6f9
--- /dev/null
+++ b/crates/channels/src/inbound/toolset/delete_channel_message.rs
@@ -0,0 +1,78 @@
+use super::{ChannelToolContext, message_mutation_error};
+use crate::domain::ports::ChannelService;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Response from [`DeleteChannelMessage`].
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteChannelMessageResponse {
+ /// Channel containing the message.
+ pub channel_id: Uuid,
+ /// Deleted message.
+ pub message_id: Uuid,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Delete a channel message.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteChannelMessage",
+ description = "Delete a channel message or thread reply. The channel keeps a 'message deleted' placeholder; this cannot be undone. Users can delete their own messages and messages sent by bots; channel admins and owners can delete any message. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user explicitly asks to delete a message."
+)]
+pub struct DeleteChannelMessage {
+ /// Channel containing the message.
+ #[schemars(description = "Channel id containing the message.")]
+ pub channel_id: Uuid,
+ /// Message to delete.
+ #[schemars(description = "Id of the message to delete.")]
+ pub message_id: Uuid,
+}
+
+impl ToolAnnotated for DeleteChannelMessage {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Delete channel message").with_idempotent();
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for DeleteChannelMessage
+where
+ Svc: ChannelService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = DeleteChannelMessageResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id, message_id=%self.message_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let access = service_context
+ .require_message_author_write(&request_context, self.channel_id, self.message_id)
+ .await?;
+ service_context
+ .messages
+ .delete(access, self.message_id, None)
+ .await
+ .map_err(message_mutation_error("delete this message"))?;
+
+ Ok(DeleteChannelMessageResponse {
+ channel_id: self.channel_id,
+ message_id: self.message_id,
+ summary: "Deleted the message.".to_string(),
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset/edit_channel_message.rs b/crates/channels/src/inbound/toolset/edit_channel_message.rs
new file mode 100644
index 0000000000..9caf7d4226
--- /dev/null
+++ b/crates/channels/src/inbound/toolset/edit_channel_message.rs
@@ -0,0 +1,100 @@
+use super::{ChannelToolContext, message_mutation_error};
+use crate::domain::ports::ChannelService;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use messages::domain::ports::MessagePatch;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Response from [`EditChannelMessage`].
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EditChannelMessageResponse {
+ /// Channel containing the message.
+ pub channel_id: Uuid,
+ /// Edited message.
+ pub message_id: Uuid,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Replace the content of an existing channel message.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "EditChannelMessage",
+ description = "Replace the content of an existing channel message or thread reply. Only the message's author can edit it, so this edits messages the user sent and messages this assistant sent for them; channel admins and owners may also edit others' messages. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to edit or correct a message."
+)]
+pub struct EditChannelMessage {
+ /// Channel containing the message.
+ #[schemars(description = "Channel id containing the message.")]
+ pub channel_id: Uuid,
+ /// Message to edit.
+ #[schemars(description = "Id of the message to edit.")]
+ pub message_id: Uuid,
+ /// Replacement body.
+ #[schemars(
+ description = "The full replacement message content in macro markdown format. This replaces the whole message, not a fragment of it."
+ )]
+ pub content: String,
+}
+
+impl ToolAnnotated for EditChannelMessage {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Edit channel message").with_idempotent();
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for EditChannelMessage
+where
+ Svc: ChannelService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = EditChannelMessageResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id, message_id=%self.message_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.content.trim().is_empty() {
+ return Err(ToolCallError {
+ description:
+ "message content must not be empty; use DeleteChannelMessage to remove a message"
+ .to_string(),
+ internal_error: anyhow::anyhow!("empty channel message edit"),
+ });
+ }
+ let access = service_context
+ .require_message_author_write(&request_context, self.channel_id, self.message_id)
+ .await?;
+ service_context
+ .messages
+ .patch(
+ access,
+ self.message_id,
+ MessagePatch {
+ content: Some(self.content.clone()),
+ ..MessagePatch::default()
+ },
+ )
+ .await
+ .map_err(message_mutation_error("edit this message"))?;
+
+ Ok(EditChannelMessageResponse {
+ channel_id: self.channel_id,
+ message_id: self.message_id,
+ summary: "Edited the message.".to_string(),
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset/open_direct_message.rs b/crates/channels/src/inbound/toolset/open_direct_message.rs
new file mode 100644
index 0000000000..7f2cc82955
--- /dev/null
+++ b/crates/channels/src/inbound/toolset/open_direct_message.rs
@@ -0,0 +1,118 @@
+use super::{ChannelToolContext, channel_mutation_error, parse_participants};
+use crate::domain::{
+ models::{GetOrCreateAction, GetOrCreateDmRequest, GetOrCreatePrivateRequest},
+ ports::ChannelService,
+};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Response from [`OpenDirectMessage`].
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct OpenDirectMessageResponse {
+ /// The direct-message channel.
+ pub channel_id: Uuid,
+ /// Whether the conversation was newly created.
+ pub created: bool,
+ /// Canonical ids of the other participants.
+ pub participants: Vec<String>,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Find or start the user's direct-message conversation with other people.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "OpenDirectMessage",
+ description = "Find the user's direct-message conversation with one or more people, creating it if it does not exist yet, and return its channel id. One person opens a 1:1 DM; several open a group DM with exactly that set of people. Use this before SendChannelMessage when the user asks to message someone directly and no channel id is known. Find people with ListTeamMembers."
+)]
+pub struct OpenDirectMessage {
+ /// Other participants.
+ #[schemars(
+ description = "The other people in the conversation, as Macro user ids (`macro|<email>`) or emails. Do not include the user."
+ )]
+ pub participants: Vec<String>,
+}
+
+impl ToolAnnotated for OpenDirectMessage {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::additive("Open direct message").with_idempotent();
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for OpenDirectMessage
+where
+ Svc: ChannelService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = OpenDirectMessageResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let user_id = request_context.user_id.clone();
+ let participants: Vec<_> = parse_participants(&self.participants)?
+ .into_iter()
+ .filter(|participant| participant.as_ref() != user_id.as_ref())
+ .collect();
+ let actor = crate::domain::models::Sender::new_from_user(user_id);
+ let response = match participants.as_slice() {
+ [] => {
+ return Err(ToolCallError {
+ description: "participants must name at least one person other than the user"
+ .to_string(),
+ internal_error: anyhow::anyhow!("no direct message recipients"),
+ });
+ }
+ [recipient] => service_context
+ .service
+ .get_or_create_dm(
+ actor,
+ GetOrCreateDmRequest {
+ recipient_id: recipient.clone(),
+ },
+ )
+ .await
+ .map_err(|error| channel_mutation_error("open the direct message", error))?,
+ _ => service_context
+ .service
+ .get_or_create_private(
+ actor,
+ GetOrCreatePrivateRequest {
+ recipients: participants.iter().cloned().collect(),
+ },
+ )
+ .await
+ .map_err(|error| channel_mutation_error("open the group message", error))?,
+ };
+ let channel_id = Uuid::parse_str(&response.channel_id).map_err(|error| ToolCallError {
+ description: "failed to open the direct message".to_string(),
+ internal_error: error.into(),
+ })?;
+ let created = matches!(response.action, GetOrCreateAction::Create);
+ let participants = super::participant_id_strings(&participants);
+ let summary = format!(
+ "{} the conversation with {}.",
+ if created { "Started" } else { "Found" },
+ participants.join(", ")
+ );
+
+ Ok(OpenDirectMessageResponse {
+ channel_id,
+ created,
+ participants,
+ summary,
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset/react_to_channel_message.rs b/crates/channels/src/inbound/toolset/react_to_channel_message.rs
new file mode 100644
index 0000000000..d1c003d161
--- /dev/null
+++ b/crates/channels/src/inbound/toolset/react_to_channel_message.rs
@@ -0,0 +1,125 @@
+use super::{ChannelToolContext, message_mutation_error};
+use crate::domain::ports::ChannelService;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Whether to add or remove a reaction.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ReactionAction {
+ /// Add the user's reaction.
+ #[default]
+ Add,
+ /// Remove the user's reaction.
+ Remove,
+}
+
+/// Response from [`ReactToChannelMessage`].
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReactToChannelMessageResponse {
+ /// Channel containing the message.
+ pub channel_id: Uuid,
+ /// Message reacted to.
+ pub message_id: Uuid,
+ /// Emoji added or removed.
+ pub emoji: String,
+ /// Whether the reaction was added or removed.
+ pub action: ReactionAction,
+ /// How many people reacted with this emoji after the change.
+ pub count: usize,
+}
+
+/// Add or remove the user's emoji reaction on a channel message.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReactToChannelMessage",
+ description = "Add or remove the user's own emoji reaction on a channel message or thread reply. The reaction is shown as coming from the user. Find message ids with ReadChannelMessages or ReadChannelThread. Use only when the user asks to react to a message."
+)]
+pub struct ReactToChannelMessage {
+ /// Channel containing the message.
+ #[schemars(description = "Channel id containing the message.")]
+ pub channel_id: Uuid,
+ /// Message to react to.
+ #[schemars(description = "Id of the message to react to.")]
+ pub message_id: Uuid,
+ /// The emoji character.
+ #[schemars(
+ description = "The emoji itself as a Unicode character, for example 👍 or 🎉 — not a shortcode like :thumbsup:."
+ )]
+ pub emoji: String,
+ /// Add or remove.
+ #[schemars(description = "Whether to add or remove the user's reaction. Defaults to add.")]
+ #[serde(default)]
+ pub action: ReactionAction,
+}
+
+impl ToolAnnotated for ReactToChannelMessage {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("React to channel message").with_idempotent();
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReactToChannelMessage
+where
+ Svc: ChannelService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ReactToChannelMessageResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id, message_id=%self.message_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let emoji = self.emoji.trim();
+ if emoji.is_empty() || emoji.starts_with(':') {
+ return Err(ToolCallError {
+ description:
+ "emoji must be a Unicode emoji character such as 👍, not empty or a :shortcode:"
+ .to_string(),
+ internal_error: anyhow::anyhow!("invalid reaction emoji"),
+ });
+ }
+ let access = service_context
+ .require_user_message_write(&request_context, self.channel_id)
+ .await?;
+ let message = service_context
+ .messages
+ .react(
+ access,
+ self.message_id,
+ emoji.to_string(),
+ self.action == ReactionAction::Add,
+ None,
+ )
+ .await
+ .map_err(message_mutation_error("react to this message"))?;
+ let count = message
+ .reactions
+ .iter()
+ .find(|reaction| reaction.emoji == emoji)
+ .map_or(0, |reaction| reaction.users.len());
+
+ Ok(ReactToChannelMessageResponse {
+ channel_id: self.channel_id,
+ message_id: self.message_id,
+ emoji: emoji.to_string(),
+ action: self.action,
+ count,
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 70a82b8814..bd93f9ad83 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -2,8 +2,12 @@ use super::{
ChannelToolContext, ReadChannelMessageContext, ReadChannelMessages, ReadChannelThread,
channel_mutation_error, channel_name,
create_channel::{CreateChannel, NewChannelType},
+ delete_channel_message::DeleteChannelMessage,
+ edit_channel_message::EditChannelMessage,
manage_channel_participants::{ManageChannelParticipants, ParticipantAction},
+ open_direct_message::OpenDirectMessage,
parse_participants,
+ react_to_channel_message::{ReactToChannelMessage, ReactionAction},
rename_channel::RenameChannel,
send_channel_message::SendChannelMessage,
share_with_channel::{ChannelShareEntityType, ShareWithChannel},
@@ -11,8 +15,9 @@ use super::{
use crate::domain::{
models::{
AddParticipantsRequest, ChannelMetadata, ChannelType, CreateChannelRequest,
- CreateChannelResponse, PatchChannelRequest, ReferenceShareOutcome, ReferenceShareResult,
- ReferencedShareItem, RemoveParticipantsRequest, Sender,
+ CreateChannelResponse, GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,
+ GetOrCreatePrivateRequest, PatchChannelRequest, ReferenceShareOutcome,
+ ReferenceShareResult, ReferencedShareItem, RemoveParticipantsRequest, Sender,
},
ports::{ChannelMutationErr, ChannelService},
};
@@ -42,9 +47,73 @@ type PostedSharedMessage = (
messages::domain::models::PostMessage,
);
+type MessageWriteReceipt = EntityAccessReceipt<messages::domain::service::MessageWrite>;
+type RecordedPatch = (
+ MessageWriteReceipt,
+ Uuid,
+ messages::domain::ports::MessagePatch,
+);
+type RecordedReaction = (MessageWriteReceipt, Uuid, String, bool);
+
#[derive(Clone, Default)]
struct RecordingMessages {
posts: Arc<Mutex<Vec<PostedSharedMessage>>>,
+ /// Author of the message `get` returns; the requesting user when unset.
+ stored_sender: Option<Sender>,
+ patches: Arc<Mutex<Vec<RecordedPatch>>>,
+ deletes: Arc<Mutex<Vec<(MessageWriteReceipt, Uuid)>>>,
+ reacts: Arc<Mutex<Vec<RecordedReaction>>>,
+ /// Error every mutation returns instead of succeeding.
+ mutation_error: Option<fn() -> messages::domain::ports::MessageError>,
+}
+
+impl RecordingMessages {
+ fn stored_message(
+ &self,
+ channel_id: &str,
+ id: Uuid,
+ reactions: Vec<messages::domain::models::CountedReaction>,
+ ) -> messages::domain::models::Message {
+ messages::domain::models::Message {
+ id,
+ parent: messages::domain::models::MessageParent::parse("channel", channel_id).unwrap(),
+ thread_id: None,
+ sender_id: self
+ .stored_sender
+ .clone()
+ .unwrap_or_else(|| Sender::new_from_user(user_id())),
+ imported_author: None,
+ bot_profile: None,
+ mentions: vec![],
+ triggered_by: None,
+ content: "stored".to_string(),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions,
+ }
+ }
+
+ fn mutation_result(
+ &self,
+ access: &MessageWriteReceipt,
+ id: Uuid,
+ reactions: Vec<messages::domain::models::CountedReaction>,
+ ) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
+ match self.mutation_error {
+ Some(error) => Err(error()),
+ None => Ok(self.stored_message(&access.entity().entity_id, id, reactions)),
+ }
+ }
+}
+
+fn is_bot_receipt(access: &MessageWriteReceipt) -> bool {
+ matches!(
+ access.auth(),
+ entity_access::domain::models::EntityAccessAuth::Bot(_)
+ )
}
#[async_trait::async_trait]
@@ -96,29 +165,43 @@ impl messages::domain::api::MessageCommands for RecordingMessages {
}
async fn patch(
&self,
- _: EntityAccessReceipt<messages::domain::service::MessageWrite>,
- _: Uuid,
- _: messages::domain::ports::MessagePatch,
+ access: EntityAccessReceipt<messages::domain::service::MessageWrite>,
+ id: Uuid,
+ patch: messages::domain::ports::MessagePatch,
) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
- unimplemented!()
+ let result = self.mutation_result(&access, id, vec![]);
+ self.patches.lock().unwrap().push((access, id, patch));
+ result
}
async fn delete(
&self,
- _: EntityAccessReceipt<messages::domain::service::MessageWrite>,
- _: Uuid,
+ access: EntityAccessReceipt<messages::domain::service::MessageWrite>,
+ id: Uuid,
_: Option<String>,
) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
- unimplemented!()
+ let result = self.mutation_result(&access, id, vec![]);
+ self.deletes.lock().unwrap().push((access, id));
+ result
}
async fn react(
&self,
- _: EntityAccessReceipt<messages::domain::service::MessageWrite>,
- _: Uuid,
- _: String,
- _: bool,
+ access: EntityAccessReceipt<messages::domain::service::MessageWrite>,
+ id: Uuid,
+ emoji: String,
+ add: bool,
_: Option<String>,
) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
- unimplemented!()
+ let reactions = if add {
+ vec![messages::domain::models::CountedReaction {
+ emoji: emoji.clone(),
+ users: vec![TEST_USER_ID.to_string()],
+ }]
+ } else {
+ vec![]
+ };
+ let result = self.mutation_result(&access, id, reactions);
+ self.reacts.lock().unwrap().push((access, id, emoji, add));
+ result
}
async fn typing(
&self,
@@ -151,10 +234,10 @@ impl messages::domain::api::MessageCommands for RecordingMessages {
impl messages::domain::api::MessageReader for RecordingMessages {
async fn get(
&self,
- _: EntityAccessReceipt<messages::domain::service::MessageView>,
- _: Uuid,
+ access: EntityAccessReceipt<messages::domain::service::MessageView>,
+ id: Uuid,
) -> Result<messages::domain::models::Message, messages::domain::ports::MessageError> {
- unimplemented!("read path unused by mutation tools")
+ Ok(self.stored_message(&access.entity().entity_id, id, vec![]))
}
async fn get_thread(
&self,
@@ -221,6 +304,8 @@ type RemoveParticipantsCall = (Sender, Uuid, RemoveParticipantsRequest);
#[derive(Clone, Default)]
struct ToolTestChannelService {
+ dms: Arc<Mutex<Vec<(Sender, GetOrCreateDmRequest)>>>,
+ group_dms: Arc<Mutex<Vec<(Sender, GetOrCreatePrivateRequest)>>>,
created: Arc<Mutex<Option<CreatedChannelCall>>>,
created_id: Option<Uuid>,
create_error: Option<String>,
@@ -251,6 +336,33 @@ impl ToolTestChannelService {
}
impl ChannelService for ToolTestChannelService {
+ async fn get_or_create_dm(
+ &self,
+ actor: Sender,
+ req: GetOrCreateDmRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ self.dms.lock().expect("dm lock").push((actor, req));
+ Ok(GetOrCreateChannelResponse {
+ channel_id: self.created_id.unwrap_or_else(Uuid::new_v4).to_string(),
+ action: GetOrCreateAction::Get,
+ })
+ }
+
+ async fn get_or_create_private(
+ &self,
+ actor: Sender,
+ req: GetOrCreatePrivateRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ self.group_dms
+ .lock()
+ .expect("group dm lock")
+ .push((actor, req));
+ Ok(GetOrCreateChannelResponse {
+ channel_id: self.created_id.unwrap_or_else(Uuid::new_v4).to_string(),
+ action: GetOrCreateAction::Create,
+ })
+ }
+
async fn set_channel_picture(
&self,
_access: entity_access::domain::models::EntityAccessReceipt<
@@ -1260,3 +1372,350 @@ async fn manage_participants_distinguishes_missing_channels() {
assert_eq!(error.description, "channel not found");
}
+
+fn message_tool_context(messages: RecordingMessages) -> ServiceContext<ToolChannelContext> {
+ ServiceContext(ChannelToolContext::new(
+ Arc::new(messages),
+ ToolTestChannelService::default(),
+ ToolTestAccessService::default(),
+ ))
+}
+
+type ToolChannelContext = ChannelToolContext<ToolTestChannelService, ToolTestAccessService>;
+
+#[test]
+fn message_mutation_schemas_are_valid() {
+ for (name, result) in [
+ (
+ "EditChannelMessage",
+ generate_validated_input_schema::<EditChannelMessage>(),
+ ),
+ (
+ "DeleteChannelMessage",
+ generate_validated_input_schema::<DeleteChannelMessage>(),
+ ),
+ (
+ "ReactToChannelMessage",
+ generate_validated_input_schema::<ReactToChannelMessage>(),
+ ),
+ (
+ "OpenDirectMessage",
+ generate_validated_input_schema::<OpenDirectMessage>(),
+ ),
+ ] {
+ let validated = result.unwrap_or_else(|error| panic!("{name}: {error:?}"));
+ assert_eq!(validated.name, name);
+ }
+}
+
+#[tokio::test]
+async fn edit_channel_message_edits_the_users_own_message_as_the_user() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let messages = RecordingMessages::default();
+ let patches = messages.patches.clone();
+
+ EditChannelMessage {
+ channel_id,
+ message_id,
+ content: "fixed typo".to_string(),
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect("author can edit");
+
+ let patches = patches.lock().unwrap();
+ let [(access, id, patch)] = patches.as_slice() else {
+ panic!("expected one patch, got {}", patches.len());
+ };
+ assert!(!is_bot_receipt(access));
+ assert_eq!(access.entity().entity_id, channel_id.to_string());
+ assert_eq!(*id, message_id);
+ assert_eq!(patch.content.as_deref(), Some("fixed typo"));
+ assert!(patch.mentions.is_none(), "edits keep the stored mentions");
+}
+
+#[tokio::test]
+async fn edit_channel_message_edits_the_assistants_message_as_the_bot() {
+ let messages = RecordingMessages {
+ stored_sender: Some(Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID)),
+ ..RecordingMessages::default()
+ };
+ let patches = messages.patches.clone();
+
+ EditChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ content: "corrected".to_string(),
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect("the assistant can edit its own message");
+
+ let patches = patches.lock().unwrap();
+ assert!(is_bot_receipt(&patches[0].0));
+}
+
+#[tokio::test]
+async fn edit_channel_message_rejects_empty_content_before_any_access_check() {
+ let messages = RecordingMessages::default();
+ let patches = messages.patches.clone();
+
+ let error = EditChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ content: " ".to_string(),
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect_err("empty edits are refused");
+
+ assert!(error.description.contains("DeleteChannelMessage"));
+ assert!(patches.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn edit_channel_message_explains_a_forbidden_edit() {
+ let messages = RecordingMessages {
+ stored_sender: Some(Sender::new_from_user(
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ )),
+ mutation_error: Some(|| messages::domain::ports::MessageError::Forbidden),
+ ..RecordingMessages::default()
+ };
+
+ let error = EditChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ content: "rewrite".to_string(),
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect_err("only the author can edit");
+
+ assert!(
+ error.description.contains("author"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn delete_channel_message_deletes_as_the_author() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let messages = RecordingMessages::default();
+ let deletes = messages.deletes.clone();
+
+ DeleteChannelMessage {
+ channel_id,
+ message_id,
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect("author can delete");
+
+ let deletes = deletes.lock().unwrap();
+ let [(access, id)] = deletes.as_slice() else {
+ panic!("expected one delete, got {}", deletes.len());
+ };
+ assert!(!is_bot_receipt(access));
+ assert_eq!(*id, message_id);
+}
+
+#[tokio::test]
+async fn delete_channel_message_requires_membership() {
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ ToolTestChannelService::default(),
+ ToolTestAccessService {
+ receipt_error: Some(ReceiptFail::Unauthorized),
+ ..ToolTestAccessService::default()
+ },
+ );
+
+ let error = DeleteChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("non-members cannot delete");
+
+ assert!(error.description.contains("not a member"));
+}
+
+#[tokio::test]
+async fn react_to_channel_message_reacts_as_the_user() {
+ let message_id = Uuid::new_v4();
+ let messages = RecordingMessages {
+ stored_sender: Some(Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID)),
+ ..RecordingMessages::default()
+ };
+ let reacts = messages.reacts.clone();
+
+ let response = ReactToChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id,
+ emoji: " 👍 ".to_string(),
+ action: ReactionAction::Add,
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect("members can react");
+
+ assert_eq!(response.emoji, "👍");
+ assert_eq!(response.count, 1);
+ let reacts = reacts.lock().unwrap();
+ let [(access, id, emoji, add)] = reacts.as_slice() else {
+ panic!("expected one reaction, got {}", reacts.len());
+ };
+ assert!(!is_bot_receipt(access), "reactions belong to the user");
+ assert_eq!(*id, message_id);
+ assert_eq!(emoji, "👍");
+ assert!(*add);
+}
+
+#[tokio::test]
+async fn react_to_channel_message_removes_a_reaction() {
+ let messages = RecordingMessages::default();
+ let reacts = messages.reacts.clone();
+
+ let response = ReactToChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ emoji: "🎉".to_string(),
+ action: ReactionAction::Remove,
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect("members can remove their reaction");
+
+ assert_eq!(response.count, 0);
+ assert!(!reacts.lock().unwrap()[0].3);
+}
+
+#[tokio::test]
+async fn react_to_channel_message_rejects_shortcodes() {
+ let messages = RecordingMessages::default();
+ let reacts = messages.reacts.clone();
+
+ let error = ReactToChannelMessage {
+ channel_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ emoji: ":thumbsup:".to_string(),
+ action: ReactionAction::Add,
+ }
+ .call(
+ message_tool_context(messages),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect_err("shortcodes are not emoji");
+
+ assert!(error.description.contains("shortcode"));
+ assert!(reacts.lock().unwrap().is_empty());
+}
+
+#[test]
+fn react_to_channel_message_defaults_to_adding() {
+ let tool: ReactToChannelMessage = serde_json::from_value(serde_json::json!({
+ "channelId": Uuid::nil(),
+ "messageId": Uuid::nil(),
+ "emoji": "👍",
+ }))
+ .expect("valid input");
+ assert_eq!(tool.action, ReactionAction::Add);
+}
+
+#[tokio::test]
+async fn open_direct_message_opens_a_one_to_one_dm_as_the_user() {
+ let channel_id = Uuid::new_v4();
+ let service = ToolTestChannelService {
+ created_id: Some(channel_id),
+ ..ToolTestChannelService::default()
+ };
+ let dms = service.dms.clone();
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ service,
+ ToolTestAccessService::default(),
+ );
+
+ let response = OpenDirectMessage {
+ participants: vec!["[email protected]".to_string(), TEST_USER_ID.to_string()],
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("dm opens");
+
+ assert_eq!(response.channel_id, channel_id);
+ assert!(!response.created);
+ assert_eq!(response.participants, vec!["macro|[email protected]"]);
+ let dms = dms.lock().unwrap();
+ let [(actor, request)] = dms.as_slice() else {
+ panic!("expected one dm, got {}", dms.len());
+ };
+ assert_eq!(actor.as_user(), Some(&user_id()));
+ assert_eq!(request.recipient_id.as_ref(), "macro|[email protected]");
+}
+
+#[tokio::test]
+async fn open_direct_message_opens_a_group_dm_for_several_people() {
+ let service = ToolTestChannelService::default();
+ let group_dms = service.group_dms.clone();
+ let dms = service.dms.clone();
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ service,
+ ToolTestAccessService::default(),
+ );
+
+ let response = OpenDirectMessage {
+ participants: vec!["[email protected]".to_string(), "[email protected]".to_string()],
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("group dm opens");
+
+ assert!(response.created);
+ assert!(dms.lock().unwrap().is_empty());
+ let group_dms = group_dms.lock().unwrap();
+ assert_eq!(group_dms[0].1.recipients.len(), 2);
+}
+
+#[tokio::test]
+async fn open_direct_message_needs_someone_besides_the_user() {
+ let error = OpenDirectMessage {
+ participants: vec![TEST_USER_ID.to_string()],
+ }
+ .call(
+ message_tool_context(RecordingMessages::default()),
+ RequestContext::new(user_id()),
+ )
+ .await
+ .expect_err("a dm with only the user is refused");
+
+ assert!(error.description.contains("other than the user"));
+}
diff --git a/crates/crm/src/inbound/toolset.rs b/crates/crm/src/inbound/toolset.rs
index fc6838a5be..ecf0e5d501 100644
--- a/crates/crm/src/inbound/toolset.rs
+++ b/crates/crm/src/inbound/toolset.rs
@@ -1,13 +1,18 @@
//! Toolset inbound adapter for the CRM domain.
//!
-//! Exposes team-scoped CRM company tools (`ListCompanies`, `GetCompany`)
-//! to AI agents. Property writes (stage moves, revenue, owner, custom
+//! 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`.
+mod create_company;
+mod create_contact;
mod get_company;
mod list_companies;
+#[cfg(test)]
+mod test;
+
use std::collections::HashMap;
use std::sync::Arc;
@@ -30,10 +35,14 @@ use system_properties::{StageOption, SystemPropertyKey};
use uuid::Uuid;
use crate::domain::{
- auth::CrmTeamReceipt, model::CrmError, service::CrmService,
+ auth::{CrmCompanyReceipt, CrmTeamReceipt},
+ model::CrmError,
+ service::CrmService,
stages::CRM_TEAM_STAGE_DEFINITION_NAME,
};
+pub use create_company::{CreateCompany, CreateCompanyResponse};
+pub use create_contact::{CreateContact, CreateContactResponse};
pub use get_company::{GetCompany, GetCompanyResponse};
pub use list_companies::{ListCompanies, ListCompaniesResponse};
@@ -96,6 +105,8 @@ where
AsyncToolCollection::new()
.add_tool::<ListCompanies, CrmToolContext<CSvc, ESvc, PSvc>>()
.add_tool::<GetCompany, CrmToolContext<CSvc, ESvc, PSvc>>()
+ .add_tool::<CreateCompany, CrmToolContext<CSvc, ESvc, PSvc>>()
+ .add_tool::<CreateContact, CrmToolContext<CSvc, ESvc, PSvc>>()
}
/// A company's pipeline stage: the select option id currently set plus its
@@ -360,6 +371,67 @@ where
Ok((receipt, team_info.role))
}
+/// Resolve the caller's permission on a CRM company (derived from their
+/// role on the owning team) and mint a view receipt for it, returning the
+/// owning team id. Access failures collapse to "not found" so company ids
+/// can't be probed across teams.
+pub(crate) async fn company_view_receipt<ESvc>(
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ company_id: Uuid,
+) -> Result<(CrmCompanyReceipt<ViewAccessLevel>, Uuid), ToolCallError>
+where
+ ESvc: EntityAccessService,
+{
+ let company_id = company_id.to_string();
+ let (permission, team_id, team_role) = match entity_access_service
+ .get_crm_entity_permission_with_team(
+ Some(&request_context.user_id),
+ &company_id,
+ EntityType::CrmCompany,
+ )
+ .await
+ {
+ Ok(triple) => triple,
+ Err(
+ AccessError::Unauthorized
+ | AccessError::UnauthorizedWithMessage(_)
+ | AccessError::NotFound(_),
+ ) => return Err(company_not_found()),
+ Err(e) => {
+ return Err(ToolCallError {
+ description: "failed to verify access to the CRM company".to_string(),
+ internal_error: e.into(),
+ });
+ }
+ };
+
+ if !permission.satisfies::<ViewAccessLevel>() {
+ return Err(company_not_found());
+ }
+
+ let receipt = EntityAccessReceipt::try_new_authenticated_user(
+ request_context.user_id.clone(),
+ Entity {
+ entity_id: company_id,
+ entity_type: EntityType::CrmCompany,
+ },
+ permission,
+ )
+ .map_err(|e| ToolCallError {
+ description: "failed to verify access to the CRM company".to_string(),
+ internal_error: e.into(),
+ })?;
+ Ok((CrmCompanyReceipt::new(receipt, team_id, team_role), team_id))
+}
+
+fn company_not_found() -> ToolCallError {
+ ToolCallError {
+ description: "CRM company not found or not accessible to the caller's team".to_string(),
+ internal_error: anyhow::anyhow!("crm company not found or not accessible"),
+ }
+}
+
/// Map an [`AccessError`] into an actionable tool error.
pub(crate) fn team_access_error(err: AccessError) -> ToolCallError {
let description = match err {
@@ -389,6 +461,16 @@ pub(crate) fn crm_error(err: CrmError) -> ToolCallError {
"CRM contact not found for the caller's team".to_string()
}
CrmError::InvalidRequest(msg) => msg.clone(),
+ CrmError::CrmDisabledForTeam => "CRM is turned off for the caller's team".to_string(),
+ CrmError::CompanyAlreadyExistsForTeam => {
+ "the team already tracks a company with that domain".to_string()
+ }
+ CrmError::ContactAlreadyExistsForCompany => {
+ "the company already has a contact with that email".to_string()
+ }
+ CrmError::ContactEmailDomainMismatch => {
+ "the contact's email domain must be one of the company's domains".to_string()
+ }
CrmError::StageEditRoleRequired(role) => format!(
"editing deal stages requires the {} team role",
role.as_db_str()
diff --git a/crates/crm/src/inbound/toolset/create_company.rs b/crates/crm/src/inbound/toolset/create_company.rs
new file mode 100644
index 0000000000..a3e3ac3a03
--- /dev/null
+++ b/crates/crm/src/inbound/toolset/create_company.rs
@@ -0,0 +1,85 @@
+//! CreateCompany tool: manually add a company to the team CRM.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use properties::PropertiesService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::domain::service::CrmService;
+
+use super::{CrmToolContext, caller_team_receipt, crm_error};
+
+/// The created company.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateCompanyResponse {
+ /// The new CRM company id (usable with GetCompany, CreateContact, and
+ /// SetEntityProperty).
+ pub company_id: Uuid,
+ /// The company's display name.
+ pub name: Option<String>,
+ /// The company's domains.
+ pub domains: Vec<String>,
+}
+
+/// Manually add a company to the caller's team CRM.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateCompany",
+ description = "Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company)."
+)]
+pub struct CreateCompany {
+ /// Display name.
+ #[schemars(description = "The company's display name, e.g. \"Acme\".")]
+ pub name: String,
+ /// Primary domain.
+ #[schemars(
+ description = "The company's web domain, e.g. \"acme.com\" — no scheme or path. Contacts are matched to the company by this domain."
+ )]
+ pub domain: String,
+}
+
+impl ToolAnnotated for CreateCompany {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create CRM company");
+}
+
+#[async_trait]
+impl<CSvc, ESvc, PSvc> AsyncTool<CrmToolContext<CSvc, ESvc, PSvc>> for CreateCompany
+where
+ CSvc: CrmService,
+ ESvc: EntityAccessService,
+ PSvc: PropertiesService,
+{
+ type Output = CreateCompanyResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CrmToolContext<CSvc, ESvc, PSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let (team, _) =
+ caller_team_receipt(&*service_context.entity_access_service, &request_context).await?;
+ let created = service_context
+ .service
+ .create_company(&team, self.name.trim(), self.domain.trim())
+ .await
+ .map_err(crm_error)?;
+
+ Ok(CreateCompanyResponse {
+ company_id: created.company.id,
+ name: created.name,
+ domains: created
+ .company
+ .domains
+ .into_iter()
+ .map(|domain| domain.domain)
+ .collect(),
+ })
+ }
+}
diff --git a/crates/crm/src/inbound/toolset/create_contact.rs b/crates/crm/src/inbound/toolset/create_contact.rs
new file mode 100644
index 0000000000..3a43bb1960
--- /dev/null
+++ b/crates/crm/src/inbound/toolset/create_contact.rs
@@ -0,0 +1,87 @@
+//! CreateContact tool: manually add a contact to a CRM company.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use properties::PropertiesService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::domain::service::CrmService;
+
+use super::{CrmToolContext, company_view_receipt, crm_error};
+
+/// The created contact.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateContactResponse {
+ /// The new CRM contact id.
+ pub contact_id: Uuid,
+ /// The company the contact belongs to.
+ pub company_id: Uuid,
+ /// The contact's email.
+ pub email: String,
+ /// The contact's display name.
+ pub name: Option<String>,
+}
+
+/// Manually add a contact to a CRM company.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateContact",
+ description = "Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany."
+)]
+pub struct CreateContact {
+ /// Company to add the contact to.
+ #[schemars(description = "The CRM company id to add the contact to.")]
+ pub company_id: Uuid,
+ /// Display name.
+ #[schemars(description = "The contact's name.")]
+ pub name: String,
+ /// Email address.
+ #[schemars(description = "The contact's email address, e.g. \"[email protected]\".")]
+ pub email: String,
+}
+
+impl ToolAnnotated for CreateContact {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create CRM contact");
+}
+
+#[async_trait]
+impl<CSvc, ESvc, PSvc> AsyncTool<CrmToolContext<CSvc, ESvc, PSvc>> for CreateContact
+where
+ CSvc: CrmService,
+ ESvc: EntityAccessService,
+ PSvc: PropertiesService,
+{
+ type Output = CreateContactResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, company_id=%self.company_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CrmToolContext<CSvc, ESvc, PSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let (company, _) = company_view_receipt(
+ &*service_context.entity_access_service,
+ &request_context,
+ self.company_id,
+ )
+ .await?;
+ let contact = service_context
+ .service
+ .create_contact(&company, self.name.trim(), self.email.trim())
+ .await
+ .map_err(crm_error)?;
+
+ Ok(CreateContactResponse {
+ contact_id: contact.id,
+ company_id: contact.company_id,
+ email: contact.email,
+ name: contact.name,
+ })
+ }
+}
diff --git a/crates/crm/src/inbound/toolset/get_company.rs b/crates/crm/src/inbound/toolset/get_company.rs
index 7d0ed7de8a..0517feec98 100644
--- a/crates/crm/src/inbound/toolset/get_company.rs
+++ b/crates/crm/src/inbound/toolset/get_company.rs
@@ -6,8 +6,7 @@ use async_trait::async_trait;
use chrono::{DateTime, Utc};
use entity_access::domain::{
models::{
- AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType, TeamRole,
- ViewAccessLevel,
+ Entity, EntityAccessReceipt, EntityPermission, EntityType, TeamRole, ViewAccessLevel,
},
ports::EntityAccessService,
};
@@ -20,13 +19,12 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::domain::{
- auth::CrmCompanyReceipt,
model::{CrmContact, CrmError},
service::CrmService,
};
use super::{
- CrmToolContext, ToolCompanyStage, crm_error, extract_company_crm_props,
+ CrmToolContext, ToolCompanyStage, company_view_receipt, crm_error, extract_company_crm_props,
load_stage_option_catalog,
};
@@ -159,49 +157,12 @@ where
let company_id = self.company_id.to_string();
- // Resolve the caller's permission on this company (derived from
- // their role on the owning team). Access failures collapse to
- // "not found" so company ids can't be probed across teams.
- let (permission, team_id, team_role) = match service_context
- .entity_access_service
- .get_crm_entity_permission_with_team(
- Some(&request_context.user_id),
- &company_id,
- EntityType::CrmCompany,
- )
- .await
- {
- Ok(triple) => triple,
- Err(
- AccessError::Unauthorized
- | AccessError::UnauthorizedWithMessage(_)
- | AccessError::NotFound(_),
- ) => return Err(not_found()),
- Err(e) => {
- return Err(ToolCallError {
- description: "failed to verify access to the CRM company".to_string(),
- internal_error: e.into(),
- });
- }
- };
-
- if !permission.satisfies::<ViewAccessLevel>() {
- return Err(not_found());
- }
-
- let receipt = EntityAccessReceipt::try_new_authenticated_user(
- request_context.user_id.clone(),
- Entity {
- entity_id: company_id.clone(),
- entity_type: EntityType::CrmCompany,
- },
- permission,
+ let (receipt, team_id) = company_view_receipt(
+ &*service_context.entity_access_service,
+ &request_context,
+ self.company_id,
)
- .map_err(|e| ToolCallError {
- description: "failed to verify access to the CRM company".to_string(),
- internal_error: e.into(),
- })?;
- let receipt = CrmCompanyReceipt::new(receipt, team_id, team_role);
+ .await?;
let record = service_context
.service
@@ -211,7 +172,7 @@ where
.ok_or_else(|| crm_error(CrmError::CompanyNotFoundForTeam))?;
// Asserted rather than minted: view access to this company was just
- // verified above via `get_crm_entity_permission_with_team`.
+ // verified by `company_view_receipt`.
let properties_access =
EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
request_context.user_id.clone(),
@@ -227,7 +188,7 @@ where
internal_error: e.into(),
})?;
- // `get_crm_entity_permission_with_team` resolved `team_id` from the
+ // `company_view_receipt` resolved `team_id` from the
// ownership row that granted access, so the caller's membership of
// that team is proven; Member is the floor every member satisfies.
let team_receipt = EntityAccessReceipt::try_new_authenticated_user(
@@ -291,13 +252,6 @@ where
}
}
-fn not_found() -> ToolCallError {
- ToolCallError {
- description: "CRM company not found or not accessible to the caller's team".to_string(),
- internal_error: anyhow::anyhow!("crm company not found or not accessible"),
- }
-}
-
fn to_property_item(prop: EntityPropertyWithDefinition) -> CompanyPropertyItem {
let data_type = match prop.definition.data_type {
DataType::Boolean => "boolean",
diff --git a/crates/crm/src/inbound/toolset/test.rs b/crates/crm/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..81a41d6452
--- /dev/null
+++ b/crates/crm/src/inbound/toolset/test.rs
@@ -0,0 +1,28 @@
+use ai_toolset::schema::generate_validated_input_schema;
+
+use super::{CreateCompany, CreateContact, crm_error};
+use crate::domain::model::CrmError;
+
+#[test]
+fn create_tools_have_valid_schemas() {
+ let company = generate_validated_input_schema::<CreateCompany>().expect("valid schema");
+ assert_eq!(company.name, "CreateCompany");
+ let contact = generate_validated_input_schema::<CreateContact>().expect("valid schema");
+ assert_eq!(contact.name, "CreateContact");
+}
+
+#[test]
+fn creation_conflicts_explain_what_to_change() {
+ for (error, expected) in [
+ (CrmError::CompanyAlreadyExistsForTeam, "already tracks"),
+ (
+ CrmError::ContactAlreadyExistsForCompany,
+ "already has a contact",
+ ),
+ (CrmError::ContactEmailDomainMismatch, "company's domains"),
+ (CrmError::CrmDisabledForTeam, "turned off"),
+ ] {
+ let description = crm_error(error).description;
+ assert!(description.contains(expected), "{description}");
+ }
+}
diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rs
index 18739589b7..c55cf3ad2d 100644
--- a/crates/documents/src/inbound/toolset.rs
+++ b/crates/documents/src/inbound/toolset.rs
@@ -2,8 +2,11 @@
mod comment_on_document;
mod create_document;
+mod create_skill;
+mod delete_document_comment;
mod design;
mod edit_document;
+mod edit_document_comment;
mod illustrator;
mod photoshop;
mod presentation;
@@ -34,8 +37,11 @@ use crate::{
inbound::toolset::{
comment_on_document::CommentOnDocument,
create_document::CreateDocument,
+ create_skill::CreateSkill,
+ delete_document_comment::DeleteDocumentComment,
design::ReadDesign,
edit_document::EditDocument,
+ edit_document_comment::EditDocumentComment,
illustrator::ReadIllustratorDocument,
photoshop::ReadPhotoshopDocument,
presentation::{EditPresentation, ReadPresentation},
@@ -60,7 +66,11 @@ use entity_access::domain::{
};
use lexical_client::LexicalClient;
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{api::MessageServiceApi, ports::MessageError, service::MessageWrite};
+use messages::domain::{
+ api::MessageServiceApi,
+ ports::MessageError,
+ service::{MessageView, MessageWrite},
+};
use model_owner::CreationPrincipal;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
@@ -340,6 +350,47 @@ impl<
.map_err(comment_access_error)
}
+ /// Mint the write capability for changing an existing comment as its
+ /// author: comments the tool actor bot posted are changed as the bot, and
+ /// every other comment as the user, so the message service applies the
+ /// same authorship and moderation rules as the web composer.
+ pub async fn require_comment_author_write(
+ &self,
+ request_context: &RequestContext,
+ document_id: Uuid,
+ comment_id: Uuid,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
+ let view = self
+ .entity_access_service
+ .generate_entity_access_receipt::<MessageView>(
+ &request_context.user_id,
+ None,
+ &document_id.to_string(),
+ EntityType::Document,
+ )
+ .await
+ .map_err(comment_access_error)?;
+ let comment = self
+ .messages
+ .get(view, comment_id)
+ .await
+ .map_err(comment_error("unable to read the comment"))?;
+ if comment.sender_id.as_ref() == self.actor.into_storage_id().as_ref() {
+ return self
+ .require_comment_write(request_context, document_id)
+ .await;
+ }
+ self.entity_access_service
+ .generate_entity_access_receipt::<MessageWrite>(
+ &request_context.user_id,
+ None,
+ &document_id.to_string(),
+ EntityType::Document,
+ )
+ .await
+ .map_err(comment_access_error)
+ }
+
/// Who these tools create entities as when acting for `user`.
pub fn creation_principal(&self, user: MacroUserIdStr<'static>) -> CreationPrincipal {
CreationPrincipal::BotForUser {
@@ -361,11 +412,14 @@ where
.add_tool::<ReadMetadata, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<ReadContent, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<CreateDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
+ .add_tool::<CreateSkill, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<UploadFile, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<RenameDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<EditDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<CommentOnDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<ResolveDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
+ .add_tool::<EditDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
+ .add_tool::<DeleteDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<ReadSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<CalculateSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<EditSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>()
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index 8a91ab0ecb..4c01f7c83b 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -24,7 +24,9 @@ use crate::domain::permission_token::decode_permission_token;
use super::{
DocumentToolContext,
comment_on_document::CommentOnDocument,
+ delete_document_comment::DeleteDocumentComment,
edit_document::test::{FakeDocumentService, FakeEditingWorker, FakeEntityAccessService},
+ edit_document_comment::EditDocumentComment,
resolve_document_comment::ResolveDocumentComment,
};
@@ -41,6 +43,47 @@ pub(in crate::inbound::toolset) struct FakeMessages {
fail_posts: bool,
posts: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, PostMessage)>>>,
thread_patches: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, ThreadPatch)>>>,
+ /// Author of the stored comment `get` returns; reads panic when unset.
+ comment_author: Option<ChannelSender<'static>>,
+ /// Whether the stored comment is a reply rather than a thread's first comment.
+ comment_is_reply: bool,
+ /// Refuse every comment edit or delete as the message service refuses a non-author.
+ forbid_changes: bool,
+ comment_patches: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, MessagePatch)>>>,
+ comment_deletes: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid)>>>,
+}
+
+impl FakeMessages {
+ fn with_comment_by(author: ChannelSender<'static>) -> Self {
+ Self {
+ comment_author: Some(author),
+ ..Self::default()
+ }
+ }
+
+ fn stored_comment(&self, id: Uuid) -> Message {
+ let at = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();
+ Message {
+ id,
+ parent: MessageParent::parse("document", &DOCUMENT.to_string()).unwrap(),
+ thread_id: self.comment_is_reply.then_some(THREAD),
+ sender_id: self
+ .comment_author
+ .clone()
+ .expect("test configured a stored comment"),
+ imported_author: None,
+ bot_profile: None,
+ mentions: vec![],
+ triggered_by: None,
+ content: "stored comment".to_owned(),
+ created_at: at,
+ updated_at: at,
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
+ }
+ }
}
impl Default for FakeMessages {
@@ -50,6 +93,11 @@ impl Default for FakeMessages {
fail_posts: false,
posts: Arc::default(),
thread_patches: Arc::default(),
+ comment_author: None,
+ comment_is_reply: false,
+ forbid_changes: false,
+ comment_patches: Arc::default(),
+ comment_deletes: Arc::default(),
}
}
}
@@ -59,9 +107,9 @@ impl MessageReader for FakeMessages {
async fn get(
&self,
_access: EntityAccessReceipt<MessageView>,
- _id: Uuid,
+ id: Uuid,
) -> Result<Message, MessageError> {
- panic!("unexpected get call")
+ Ok(self.stored_comment(id))
}
async fn get_thread(
&self,
@@ -153,19 +201,30 @@ impl MessageCommands for FakeMessages {
}
async fn patch(
&self,
- _access: EntityAccessReceipt<MessageWrite>,
- _id: Uuid,
- _input: MessagePatch,
+ access: EntityAccessReceipt<MessageWrite>,
+ id: Uuid,
+ input: MessagePatch,
) -> Result<Message, MessageError> {
- panic!("unexpected patch call")
+ if self.forbid_changes {
+ return Err(MessageError::Forbidden);
+ }
+ self.comment_patches
+ .lock()
+ .unwrap()
+ .push((access, id, input));
+ Ok(self.stored_comment(id))
}
async fn delete(
&self,
- _access: EntityAccessReceipt<MessageWrite>,
- _id: Uuid,
+ access: EntityAccessReceipt<MessageWrite>,
+ id: Uuid,
_nonce: Option<String>,
) -> Result<Message, MessageError> {
- panic!("unexpected delete call")
+ if self.forbid_changes {
+ return Err(MessageError::Forbidden);
+ }
+ self.comment_deletes.lock().unwrap().push((access, id));
+ Ok(self.stored_comment(id))
}
async fn react(
&self,
@@ -818,3 +877,142 @@ fn comment_optional_fields_can_be_omitted() {
assert!(tool.quote.is_none());
assert!(tool.occurrence.is_none());
}
+
+fn user_sender() -> ChannelSender<'static> {
+ ChannelSender::try_from(USER.to_owned()).unwrap()
+}
+
+fn bot_sender() -> ChannelSender<'static> {
+ ChannelSender::try_from(bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()).unwrap()
+}
+
+fn assert_user_on_document(access: &EntityAccessReceipt<MessageWrite>) {
+ assert_eq!(access.entity().entity_id, DOCUMENT.to_string());
+ assert!(matches!(access.auth(), EntityAccessAuth::Authenticated(_)));
+}
+
+#[tokio::test]
+async fn edit_comment_rewrites_the_users_own_comment_as_the_user() {
+ let messages = FakeMessages::with_comment_by(user_sender());
+ let patches = messages.comment_patches.clone();
+
+ EditDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ content: "clearer wording".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect("the author can edit their comment");
+
+ let patches = patches.lock().unwrap();
+ let [(access, id, patch)] = patches.as_slice() else {
+ panic!("expected one edit, got {}", patches.len());
+ };
+ assert_user_on_document(access);
+ assert_eq!(*id, THREAD);
+ assert_eq!(patch.content.as_deref(), Some("clearer wording"));
+}
+
+#[tokio::test]
+async fn edit_comment_rewrites_the_assistants_comment_as_the_bot() {
+ let messages = FakeMessages::with_comment_by(bot_sender());
+ let patches = messages.comment_patches.clone();
+
+ EditDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ content: "corrected".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect("the assistant can edit its own comment");
+
+ assert_bot_on_document(&patches.lock().unwrap()[0].0);
+}
+
+#[tokio::test]
+async fn edit_comment_explains_that_only_the_author_can_edit() {
+ let messages = FakeMessages {
+ forbid_changes: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+
+ let error = EditDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ content: "rewrite".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect_err("the message service refused the edit");
+
+ assert!(
+ error.description.contains("author"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn edit_comment_rejects_empty_text() {
+ let error = EditDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ content: " ".to_owned(),
+ }
+ .call(
+ context(AccessLevel::Comment, FakeMessages::default()),
+ request(),
+ )
+ .await
+ .expect_err("empty edits are refused");
+
+ assert!(error.description.contains("DeleteDocumentComment"));
+}
+
+#[tokio::test]
+async fn delete_comment_reports_whether_the_thread_went_with_it() {
+ let root = FakeMessages::with_comment_by(user_sender());
+ let root_deletes = root.comment_deletes.clone();
+ let response = DeleteDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ }
+ .call(context(AccessLevel::Comment, root), request())
+ .await
+ .expect("the author can delete their comment");
+ assert!(response.deleted_thread);
+ assert_user_on_document(&root_deletes.lock().unwrap()[0].0);
+
+ let reply = FakeMessages {
+ comment_is_reply: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+ let response = DeleteDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: Uuid::from_u128(8),
+ }
+ .call(context(AccessLevel::Comment, reply), request())
+ .await
+ .expect("the author can delete their reply");
+ assert!(!response.deleted_thread);
+}
+
+#[tokio::test]
+async fn delete_comment_explains_who_can_delete() {
+ let messages = FakeMessages {
+ forbid_changes: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+
+ let error = DeleteDocumentComment {
+ document_id: DOCUMENT,
+ comment_id: THREAD,
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect_err("the message service refused the delete");
+
+ assert!(error.description.contains("owner"), "{}", error.description);
+}
diff --git a/crates/documents/src/inbound/toolset/create_skill.rs b/crates/documents/src/inbound/toolset/create_skill.rs
new file mode 100644
index 0000000000..f87ad4bc46
--- /dev/null
+++ b/crates/documents/src/inbound/toolset/create_skill.rs
@@ -0,0 +1,128 @@
+//! CreateSkill tool for writing a new skill document.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::models::{EditAccessLevel, EntityType};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::DocumentToolContext;
+use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};
+use crate::domain::models::DocumentError;
+use crate::domain::ports::{
+ DocumentService, create::DocumentCreationService, editing::EditingWorkerService,
+};
+
+/// The created skill.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateSkillResponse {
+ /// The id of the skill document.
+ pub document_id: Uuid,
+}
+
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateSkill",
+ description = "Create a skill: a markdown document of reusable instructions that AI reads and follows when the skill is referenced, as Compose Skill in the app does. Write the instructions as the markdown body. Edit an existing skill with EditDocument; find skills with ListSkills or SearchSkills."
+)]
+pub struct CreateSkill {
+ #[schemars(description = "The skill's name.")]
+ pub skill_name: String,
+
+ #[schemars(description = "The skill's instructions, in markdown.")]
+ pub markdown: String,
+
+ #[schemars(
+ description = "The id of the project (shown as a folder in the app UI) to create the skill in. Requires edit access to the project. Omit to create it at the top level of the user's files."
+ )]
+ #[serde(default)]
+ pub project_id: Option<Uuid>,
+}
+
+impl ToolAnnotated for CreateSkill {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create skill");
+}
+
+fn failed_to_create_skill(error: DocumentError) -> ToolCallError {
+ let description = match &error {
+ DocumentError::BadRequest(message) => message.clone(),
+ DocumentError::NameTooLong { max } => format!("name too long (max {max} characters)"),
+ _ => "failed to create the skill".to_string(),
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
+#[async_trait]
+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CreateSkill
+where
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+ EDSvc: EditingWorkerService,
+{
+ type Output = CreateSkillResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let skill_name = self.skill_name.trim();
+ if skill_name.is_empty() {
+ return Err(ToolCallError {
+ description: "skillName must not be empty".to_string(),
+ internal_error: anyhow::anyhow!("empty skill name"),
+ });
+ }
+ // Mirrors the create_skill route's project body extractor.
+ if let Some(project_id) = self.project_id {
+ service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &request_context.user_id,
+ None,
+ &project_id.to_string(),
+ EntityType::Project,
+ )
+ .await
+ .map_err(|error| ToolCallError {
+ description: "you need edit access to the target project, or it does not exist"
+ .to_string(),
+ internal_error: error.into(),
+ })?;
+ }
+
+ let mut metadata = NewDocumentMetadata::builder(skill_name.to_string());
+ if let Some(project_id) = self.project_id {
+ metadata = metadata.project_id(project_id);
+ }
+ let principal = service_context.creation_principal(request_context.user_id.clone());
+ let created = service_context
+ .creator
+ .create_markdown_text(
+ &principal,
+ NewMarkdownTextDocument {
+ metadata: metadata.build(),
+ markdown: self.markdown.clone(),
+ subtype: MarkdownSubtype::Skill,
+ },
+ )
+ .await
+ .map_err(failed_to_create_skill)?;
+ let document_id =
+ Uuid::parse_str(created.document_id()).map_err(|error| ToolCallError {
+ description: "the skill was created but returned an invalid id".to_string(),
+ internal_error: error.into(),
+ })?;
+
+ Ok(CreateSkillResponse { document_id })
+ }
+}
diff --git a/crates/documents/src/inbound/toolset/delete_document_comment.rs b/crates/documents/src/inbound/toolset/delete_document_comment.rs
new file mode 100644
index 0000000000..ecfacdad0e
--- /dev/null
+++ b/crates/documents/src/inbound/toolset/delete_document_comment.rs
@@ -0,0 +1,87 @@
+//! DeleteDocumentComment tool for deleting a comment, reply, or whole thread.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use messages::domain::ports::MessageError;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DocumentToolContext, comment_error};
+use crate::domain::ports::{
+ DocumentService, create::DocumentCreationService, editing::EditingWorkerService,
+};
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteDocumentComment",
+ description = "Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead."
+)]
+pub struct DeleteDocumentComment {
+ #[schemars(description = "The id of the document the comment is on.")]
+ pub document_id: Uuid,
+
+ #[schemars(
+ description = "The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread."
+ )]
+ pub comment_id: Uuid,
+}
+
+/// The deleted comment.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteDocumentCommentResponse {
+ /// The document the comment was on.
+ pub document_id: Uuid,
+ /// The deleted comment.
+ pub comment_id: Uuid,
+ /// Whether the whole thread was deleted.
+ pub deleted_thread: bool,
+}
+
+impl ToolAnnotated for DeleteDocumentComment {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Delete document comment").with_idempotent();
+}
+
+#[async_trait]
+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for DeleteDocumentComment
+where
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+ EDSvc: EditingWorkerService,
+{
+ type Output = DeleteDocumentCommentResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, document_id=%self.document_id, comment_id=%self.comment_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let access = service_context
+ .require_comment_author_write(&request_context, self.document_id, self.comment_id)
+ .await?;
+ let deleted = service_context
+ .messages
+ .delete(access, self.comment_id, None)
+ .await
+ .map_err(|error| match error {
+ MessageError::Forbidden => ToolCallError {
+ description: "only the comment's author or the document owner can delete it"
+ .to_string(),
+ internal_error: anyhow::Error::new(error),
+ },
+ error => comment_error("unable to delete the comment")(error),
+ })?;
+
+ Ok(DeleteDocumentCommentResponse {
+ document_id: self.document_id,
+ comment_id: self.comment_id,
+ deleted_thread: deleted.thread_id.is_none(),
+ })
+ }
+}
diff --git a/crates/documents/src/inbound/toolset/edit_document_comment.rs b/crates/documents/src/inbound/toolset/edit_document_comment.rs
new file mode 100644
index 0000000000..27b0f85ab2
--- /dev/null
+++ b/crates/documents/src/inbound/toolset/edit_document_comment.rs
@@ -0,0 +1,101 @@
+//! EditDocumentComment tool for rewriting a comment or reply on a document.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use messages::domain::ports::{MessageError, MessagePatch};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DocumentToolContext, comment_error};
+use crate::domain::ports::{
+ DocumentService, create::DocumentCreationService, editing::EditingWorkerService,
+};
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "EditDocumentComment",
+ description = "Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment."
+)]
+pub struct EditDocumentComment {
+ #[schemars(description = "The id of the document the comment is on.")]
+ pub document_id: Uuid,
+
+ #[schemars(
+ description = "The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id."
+ )]
+ pub comment_id: Uuid,
+
+ #[schemars(description = "The full replacement text of the comment, in markdown.")]
+ pub content: String,
+}
+
+/// The edited comment.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EditDocumentCommentResponse {
+ /// The document the comment is on.
+ pub document_id: Uuid,
+ /// The edited comment.
+ pub comment_id: Uuid,
+}
+
+impl ToolAnnotated for EditDocumentComment {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Edit document comment").with_idempotent();
+}
+
+#[async_trait]
+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for EditDocumentComment
+where
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+ EDSvc: EditingWorkerService,
+{
+ type Output = EditDocumentCommentResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, document_id=%self.document_id, comment_id=%self.comment_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.content.trim().is_empty() {
+ return Err(ToolCallError {
+ description:
+ "comment text must not be empty; use DeleteDocumentComment to remove a comment"
+ .to_string(),
+ internal_error: anyhow::anyhow!("empty comment edit"),
+ });
+ }
+ let access = service_context
+ .require_comment_author_write(&request_context, self.document_id, self.comment_id)
+ .await?;
+ service_context
+ .messages
+ .patch(
+ access,
+ self.comment_id,
+ MessagePatch {
+ content: Some(self.content.clone()),
+ ..MessagePatch::default()
+ },
+ )
+ .await
+ .map_err(|error| match error {
+ MessageError::Forbidden => ToolCallError {
+ description: "only the comment's author can edit it".to_string(),
+ internal_error: anyhow::Error::new(error),
+ },
+ error => comment_error("unable to edit the comment")(error),
+ })?;
+
+ Ok(EditDocumentCommentResponse {
+ document_id: self.document_id,
+ comment_id: self.comment_id,
+ })
+ }
+}
diff --git a/crates/documents/src/inbound/toolset/test.rs b/crates/documents/src/inbound/toolset/test.rs
index 97aa4f0256..468ed3d6fe 100644
--- a/crates/documents/src/inbound/toolset/test.rs
+++ b/crates/documents/src/inbound/toolset/test.rs
@@ -122,3 +122,24 @@ fn test_comment_on_document_schema_fields() {
);
assert!(response["properties"].get("markedText").is_some());
}
+
+#[test]
+fn test_comment_mutation_and_skill_schema_validation() {
+ for (name, result) in [
+ (
+ "EditDocumentComment",
+ generate_validated_input_schema::<EditDocumentComment>(),
+ ),
+ (
+ "DeleteDocumentComment",
+ generate_validated_input_schema::<DeleteDocumentComment>(),
+ ),
+ (
+ "CreateSkill",
+ generate_validated_input_schema::<CreateSkill>(),
+ ),
+ ] {
+ let validated = result.unwrap_or_else(|error| panic!("{name}: {error:?}"));
+ assert_eq!(validated.name, name);
+ }
+}
diff --git a/crates/favorites/Cargo.toml b/crates/favorites/Cargo.toml
index 0b46bdc43a..0d3231348f 100644
--- a/crates/favorites/Cargo.toml
+++ b/crates/favorites/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[features]
default = []
+ai_tools = ["dep:ai_toolset", "dep:async-trait", "dep:schemars", "dep:uuid", "ports"]
inbound = [
"dep:axum",
"dep:axum-extra",
@@ -21,7 +22,9 @@ ports = ["dep:entity_access", "dep:tokio", "dep:tracing"]
postgres = ["dep:sqlx", "outbound"]
[dependencies]
+ai_toolset = { path = "../ai_toolset", optional = true }
anyhow = { workspace = true }
+async-trait = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
# `query` brings `axum_extra::extract::Query`, whose deserializer collects
# repeated query keys into a vector; `axum::extract::Query` keeps only one.
@@ -34,12 +37,14 @@ macro_user_id = { path = "../macro_user_id" }
mockall = { workspace = true, optional = true }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
+schemars = { workspace = true, optional = true }
serde = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
tokio = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
utoipa = { workspace = true, optional = true }
+uuid = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
diff --git a/crates/favorites/src/inbound.rs b/crates/favorites/src/inbound.rs
index 6ce8fb9476..f2edd3649a 100644
--- a/crates/favorites/src/inbound.rs
+++ b/crates/favorites/src/inbound.rs
@@ -1,3 +1,6 @@
//! Inbound (driving) adapters for favorites.
+#[cfg(feature = "inbound")]
pub mod axum_router;
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/crates/favorites/src/inbound/toolset.rs b/crates/favorites/src/inbound/toolset.rs
new file mode 100644
index 0000000000..38173a2145
--- /dev/null
+++ b/crates/favorites/src/inbound/toolset.rs
@@ -0,0 +1,174 @@
+//! AI toolset for adding items to and removing them from the user's favorites.
+
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use ai_toolset::{
+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,
+ ToolCallError, ToolResult,
+};
+use async_trait::async_trait;
+use model_entity::EntityType;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{FavoritesError, FavoritesMutationActor},
+ ports::FavoritesMutationService,
+};
+
+/// Service context for favorites AI tools.
+pub struct FavoritesToolContext<M: FavoritesMutationService> {
+ /// Authorized favorite mutations.
+ pub service: Arc<M>,
+}
+
+impl<M: FavoritesMutationService> Clone for FavoritesToolContext<M> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+impl<M: FavoritesMutationService> FavoritesToolContext<M> {
+ /// Create a favorites tool context.
+ pub fn new(service: Arc<M>) -> Self {
+ Self { service }
+ }
+}
+
+/// Create the favorites toolset.
+pub fn favorites_toolset<M: FavoritesMutationService>()
+-> AsyncToolCollection<FavoritesToolContext<M>> {
+ AsyncToolCollection::new().add_tool::<SetFavorite, FavoritesToolContext<M>>()
+}
+
+/// The kinds of item a user can favorite.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum FavoritableEntityType {
+ /// A document (includes tasks).
+ Document,
+ /// A project (folder).
+ Project,
+ /// An AI chat conversation.
+ Chat,
+ /// A channel.
+ Channel,
+ /// An email thread.
+ Email,
+ /// A call record.
+ Call,
+ /// A CRM company.
+ CrmCompany,
+ /// A CRM contact.
+ CrmContact,
+}
+
+impl FavoritableEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Document => EntityType::Document,
+ Self::Project => EntityType::Project,
+ Self::Chat => EntityType::Chat,
+ Self::Channel => EntityType::Channel,
+ Self::Email => EntityType::EmailThread,
+ Self::Call => EntityType::Call,
+ Self::CrmCompany => EntityType::CrmCompany,
+ Self::CrmContact => EntityType::CrmContact,
+ }
+ }
+}
+
+/// Favorite or unfavorite an item.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "SetFavorite",
+ description = "Add an item to the user's favorites (shown starred in the app sidebar) or remove it, as the Favorite action does. Requires view access to add an item. List favorites with ListEntities and favoritesOnly."
+)]
+pub struct SetFavorite {
+ /// The kind of item.
+ #[schemars(description = "The kind of item to favorite or unfavorite.")]
+ pub entity_type: FavoritableEntityType,
+ /// The item's id.
+ #[schemars(description = "The id of the item.")]
+ pub entity_id: Uuid,
+ /// Whether the item should be a favorite.
+ #[schemars(description = "True to add the item to favorites, false to remove it.")]
+ pub favorite: bool,
+}
+
+/// The item's favorite state after the change.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SetFavoriteResponse {
+ /// The kind of item.
+ pub entity_type: FavoritableEntityType,
+ /// The item's id.
+ pub entity_id: Uuid,
+ /// Whether the item is now a favorite.
+ pub favorite: bool,
+}
+
+impl ToolAnnotated for SetFavorite {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Set favorite").with_idempotent();
+}
+
+fn favorite_error(error: FavoritesError) -> ToolCallError {
+ let description = match &error {
+ FavoritesError::NotFound => "item not found".to_string(),
+ FavoritesError::Unauthorized => {
+ "you need view access to an item to favorite it".to_string()
+ }
+ FavoritesError::UnsupportedEntityType(entity_type) => {
+ format!("items of type {entity_type} cannot be favorited")
+ }
+ FavoritesError::BadRequest(message) => message.clone(),
+ FavoritesError::Internal(_) => "failed to update favorites".to_string(),
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
+#[async_trait]
+impl<M: FavoritesMutationService> AsyncTool<FavoritesToolContext<M>> for SetFavorite {
+ type Output = SetFavoriteResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=%self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<FavoritesToolContext<M>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let result = service_context
+ .service
+ .set_favorite(
+ FavoritesMutationActor {
+ user_id: request_context.user_id,
+ organization_id: None,
+ },
+ entity,
+ self.favorite,
+ )
+ .await
+ .map_err(favorite_error)?;
+
+ Ok(SetFavoriteResponse {
+ entity_type: self.entity_type,
+ entity_id: self.entity_id,
+ favorite: result.favorite.is_some(),
+ })
+ }
+}
diff --git a/crates/favorites/src/inbound/toolset/test.rs b/crates/favorites/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..8dff38e18a
--- /dev/null
+++ b/crates/favorites/src/inbound/toolset/test.rs
@@ -0,0 +1,140 @@
+use std::sync::{Arc, Mutex};
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, schema::generate_validated_input_schema,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use uuid::Uuid;
+
+use super::{FavoritableEntityType, FavoritesToolContext, SetFavorite};
+use crate::domain::{
+ models::{Favorite, FavoritesError, FavoritesMutationActor, SetFavoriteResult},
+ ports::FavoritesMutationService,
+};
+
+const USER: &str = "macro|[email protected]";
+
+#[derive(Default)]
+struct RecordingFavorites {
+ calls: Mutex<Vec<(FavoritesMutationActor, Entity<'static>, bool)>>,
+ unauthorized: bool,
+}
+
+impl FavoritesMutationService for RecordingFavorites {
+ async fn set_favorite(
+ &self,
+ actor: FavoritesMutationActor,
+ entity: Entity<'static>,
+ favorite: bool,
+ ) -> Result<SetFavoriteResult, FavoritesError> {
+ if self.unauthorized {
+ return Err(FavoritesError::Unauthorized);
+ }
+ self.calls
+ .lock()
+ .unwrap()
+ .push((actor, entity.clone(), favorite));
+ Ok(SetFavoriteResult {
+ favorite: favorite.then(|| Favorite {
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.to_string(),
+ sort_order: 1.0,
+ created_at: chrono::Utc::now(),
+ file_type: None,
+ document_sub_type: None,
+ channel_type: None,
+ channel_id: None,
+ }),
+ entity,
+ })
+ }
+
+ async fn reorder_favorites(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _ordered: Vec<Entity<'static>>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ unimplemented!("the favorites toolset never reorders")
+ }
+}
+
+fn request() -> RequestContext {
+ RequestContext::new(MacroUserIdStr::try_from(USER.to_owned()).unwrap())
+}
+
+#[test]
+fn set_favorite_schema_is_valid() {
+ let validated = generate_validated_input_schema::<SetFavorite>().expect("valid schema");
+ assert_eq!(validated.name, "SetFavorite");
+}
+
+#[tokio::test]
+async fn set_favorite_favorites_the_item_for_the_user() {
+ let service = Arc::new(RecordingFavorites::default());
+ let entity_id = Uuid::now_v7();
+
+ let response = SetFavorite {
+ entity_type: FavoritableEntityType::Email,
+ entity_id,
+ favorite: true,
+ }
+ .call(
+ ServiceContext(FavoritesToolContext::new(service.clone())),
+ request(),
+ )
+ .await
+ .expect("viewers can favorite");
+
+ assert!(response.favorite);
+ let calls = service.calls.lock().unwrap();
+ let [(actor, entity, favorite)] = calls.as_slice() else {
+ panic!("expected one call, got {}", calls.len());
+ };
+ assert_eq!(actor.user_id.as_ref(), USER);
+ assert_eq!(entity.entity_type, EntityType::EmailThread);
+ assert_eq!(entity.entity_id, entity_id.to_string());
+ assert!(*favorite);
+}
+
+#[tokio::test]
+async fn set_favorite_false_unfavorites() {
+ let service = Arc::new(RecordingFavorites::default());
+
+ let response = SetFavorite {
+ entity_type: FavoritableEntityType::Document,
+ entity_id: Uuid::now_v7(),
+ favorite: false,
+ }
+ .call(
+ ServiceContext(FavoritesToolContext::new(service.clone())),
+ request(),
+ )
+ .await
+ .expect("unfavoriting succeeds");
+
+ assert!(!response.favorite);
+ assert!(!service.calls.lock().unwrap()[0].2);
+}
+
+#[tokio::test]
+async fn set_favorite_explains_missing_access() {
+ let service = Arc::new(RecordingFavorites {
+ unauthorized: true,
+ ..RecordingFavorites::default()
+ });
+
+ let error = SetFavorite {
+ entity_type: FavoritableEntityType::Project,
+ entity_id: Uuid::now_v7(),
+ favorite: true,
+ }
+ .call(
+ ServiceContext(FavoritesToolContext::new(service)),
+ request(),
+ )
+ .await
+ .expect_err("no access");
+
+ assert!(error.description.contains("view access"));
+}
diff --git a/crates/favorites/src/lib.rs b/crates/favorites/src/lib.rs
index b4f3241eb4..66ace709e5 100644
--- a/crates/favorites/src/lib.rs
+++ b/crates/favorites/src/lib.rs
@@ -5,12 +5,12 @@
//! # Architecture
//!
//! - **domain**: domain models, ports, and the service implementation.
-//! - **inbound**: driving adapters (Axum HTTP router).
+//! - **inbound**: driving adapters (Axum HTTP router and AI toolset).
//! - **outbound**: driven adapters (Postgres repository).
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
#[cfg(feature = "outbound")]
diff --git a/crates/notification/src/inbound/ai_tool.rs b/crates/notification/src/inbound/ai_tool.rs
index bdbdcb4f64..68d62446ab 100644
--- a/crates/notification/src/inbound/ai_tool.rs
+++ b/crates/notification/src/inbound/ai_tool.rs
@@ -1,8 +1,14 @@
//! This module provides the inbound adapter for ai tools using the notifications service
+mod mute_notifications;
#[cfg(test)]
mod test;
+pub use mute_notifications::{
+ ItemNotificationPreferenceToolContext, MuteAction, MuteNotifications,
+ MuteNotificationsResponse, item_notification_preference_toolset,
+};
+
use crate::domain::{
models::{
UserNotificationRow,
diff --git a/crates/notification/src/inbound/ai_tool/mute_notifications.rs b/crates/notification/src/inbound/ai_tool/mute_notifications.rs
new file mode 100644
index 0000000000..1e8fa05962
--- /dev/null
+++ b/crates/notification/src/inbound/ai_tool/mute_notifications.rs
@@ -0,0 +1,179 @@
+//! MuteNotifications tool: mute, snooze, or unmute notifications for one item.
+
+use super::NotificationEntityType;
+use crate::domain::item_preferences::{
+ ItemNotificationPreferenceError, ItemNotificationPreferenceRepository,
+ ItemNotificationPreferenceService,
+};
+use ai_toolset::{
+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,
+ ToolCallError, ToolResult,
+};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use model_entity::EntityType;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+#[cfg(test)]
+mod test;
+
+/// Service context for the user's per-item notification preferences.
+pub struct ItemNotificationPreferenceToolContext<R> {
+ /// The user's mute and snooze preferences.
+ pub service: Arc<ItemNotificationPreferenceService<R>>,
+}
+
+impl<R> Clone for ItemNotificationPreferenceToolContext<R> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+impl<R: ItemNotificationPreferenceRepository> ItemNotificationPreferenceToolContext<R> {
+ /// Create a context over the user's preference repository.
+ pub fn new(repository: R) -> Self {
+ Self {
+ service: Arc::new(ItemNotificationPreferenceService::new(repository)),
+ }
+ }
+}
+
+/// Create the item notification preference toolset.
+pub fn item_notification_preference_toolset<R>()
+-> AsyncToolCollection<ItemNotificationPreferenceToolContext<R>>
+where
+ R: ItemNotificationPreferenceRepository + 'static,
+{
+ AsyncToolCollection::new()
+ .add_tool::<MuteNotifications, ItemNotificationPreferenceToolContext<R>>()
+}
+
+/// What to do with an item's notifications.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum MuteAction {
+ /// Stop notifications for the item until it is unmuted.
+ Mute,
+ /// Stop notifications for the item until `snoozeUntil`.
+ Snooze,
+ /// Resume notifications for the item.
+ Unmute,
+}
+
+/// Mute, snooze, or unmute one item's notifications for the user.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "MuteNotifications",
+ description = "Mute, snooze, or unmute notifications about one item for the user only, as Mute and Snooze in the app do. Muting never changes anyone else's notifications or the item itself. Use the entity type and id from ListNotifications or other tools."
+)]
+pub struct MuteNotifications {
+ /// The item's type.
+ #[schemars(description = "The item's entity type.")]
+ pub entity_type: NotificationEntityType,
+ /// The item's id.
+ #[schemars(description = "The item's id.")]
+ pub entity_id: String,
+ /// What to do.
+ #[schemars(
+ description = "mute stops notifications until unmuted, snooze stops them until snoozeUntil, unmute resumes them."
+ )]
+ pub action: MuteAction,
+ /// When a snooze ends.
+ #[schemars(
+ description = "When notifications resume, as an ISO 8601 timestamp in the future. Required for snooze; omit otherwise."
+ )]
+ #[serde(default)]
+ pub snooze_until: Option<DateTime<Utc>>,
+}
+
+/// The item's notification state after the change.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct MuteNotificationsResponse {
+ /// The item's id.
+ pub entity_id: String,
+ /// What was done.
+ pub action: MuteAction,
+ /// When a snooze ends.
+ pub snooze_until: Option<DateTime<Utc>>,
+}
+
+impl ToolAnnotated for MuteNotifications {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Mute notifications").with_idempotent();
+}
+
+fn invalid(description: &str) -> ToolCallError {
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::anyhow!("invalid MuteNotifications input: {description}"),
+ }
+}
+
+#[async_trait]
+impl<R> AsyncTool<ItemNotificationPreferenceToolContext<R>> for MuteNotifications
+where
+ R: ItemNotificationPreferenceRepository + 'static,
+{
+ type Output = MuteNotificationsResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, action=?self.action), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ItemNotificationPreferenceToolContext<R>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity_id = self.entity_id.trim();
+ if entity_id.is_empty() {
+ return Err(invalid("entityId must not be empty"));
+ }
+ let entity = EntityType::from(self.entity_type).with_entity_str(entity_id);
+ let user = request_context.user_id;
+ let until = match (self.action, self.snooze_until) {
+ (MuteAction::Snooze, None) => {
+ return Err(invalid("snooze needs snoozeUntil"));
+ }
+ (MuteAction::Mute | MuteAction::Unmute, Some(_)) => {
+ return Err(invalid("snoozeUntil only applies to snooze"));
+ }
+ (_, until) => until,
+ };
+
+ match self.action {
+ MuteAction::Mute | MuteAction::Snooze => service_context
+ .service
+ .set(user, entity, until, Utc::now())
+ .await
+ .map_err(|error| match error {
+ ItemNotificationPreferenceError::InvalidDeadline => {
+ invalid("snoozeUntil must be in the future")
+ }
+ error @ ItemNotificationPreferenceError::Repository(_) => ToolCallError {
+ description: "failed to update notification preferences".to_string(),
+ internal_error: anyhow::anyhow!("{error}"),
+ },
+ })?,
+ MuteAction::Unmute => {
+ service_context
+ .service
+ .remove(user, entity)
+ .await
+ .map_err(|error| ToolCallError {
+ description: "failed to update notification preferences".to_string(),
+ internal_error: anyhow::anyhow!("{error}"),
+ })?
+ }
+ }
+
+ Ok(MuteNotificationsResponse {
+ entity_id: entity_id.to_string(),
+ action: self.action,
+ snooze_until: until,
+ })
+ }
+}
diff --git a/crates/notification/src/inbound/ai_tool/mute_notifications/test.rs b/crates/notification/src/inbound/ai_tool/mute_notifications/test.rs
new file mode 100644
index 0000000000..306c6e7330
--- /dev/null
+++ b/crates/notification/src/inbound/ai_tool/mute_notifications/test.rs
@@ -0,0 +1,129 @@
+use super::*;
+use crate::domain::item_preferences::ItemNotificationPreference;
+use ai_toolset::schema::generate_validated_input_schema;
+use chrono::Duration;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use rootcause::Report;
+use std::sync::{Arc, Mutex};
+
+const USER: &str = "macro|[email protected]";
+
+type Sets = Arc<Mutex<Vec<(String, String, Option<DateTime<Utc>>)>>>;
+type Removes = Arc<Mutex<Vec<(String, String)>>>;
+
+#[derive(Default, Clone)]
+struct RecordingRepository {
+ sets: Sets,
+ removes: Removes,
+}
+
+impl ItemNotificationPreferenceRepository for RecordingRepository {
+ async fn list(&self, _: MacroUserIdStr<'_>) -> Result<Vec<ItemNotificationPreference>, Report> {
+ Ok(vec![])
+ }
+ async fn set(
+ &self,
+ user: MacroUserIdStr<'_>,
+ entity: Entity<'_>,
+ until: Option<DateTime<Utc>>,
+ ) -> Result<(), Report> {
+ self.sets
+ .lock()
+ .unwrap()
+ .push((user.to_string(), entity.entity_id.to_string(), until));
+ Ok(())
+ }
+ async fn remove(&self, user: MacroUserIdStr<'_>, entity: Entity<'_>) -> Result<(), Report> {
+ self.removes
+ .lock()
+ .unwrap()
+ .push((user.to_string(), entity.entity_id.to_string()));
+ Ok(())
+ }
+}
+
+fn context() -> (
+ ItemNotificationPreferenceToolContext<RecordingRepository>,
+ RecordingRepository,
+) {
+ let repository = RecordingRepository::default();
+ (
+ ItemNotificationPreferenceToolContext::new(repository.clone()),
+ repository,
+ )
+}
+
+fn request() -> RequestContext {
+ RequestContext::new(MacroUserIdStr::try_from(USER.to_owned()).unwrap())
+}
+
+fn tool(action: MuteAction, snooze_until: Option<DateTime<Utc>>) -> MuteNotifications {
+ MuteNotifications {
+ entity_type: NotificationEntityType::Channel,
+ entity_id: "0f6d9a0e-1b62-4f53-9f4c-0b9e2f6f0c11".to_owned(),
+ action,
+ snooze_until,
+ }
+}
+
+#[test]
+fn mute_notifications_schema_is_valid() {
+ let validated = generate_validated_input_schema::<MuteNotifications>().expect("valid schema");
+ assert_eq!(validated.name, "MuteNotifications");
+}
+
+#[tokio::test]
+async fn mute_saves_an_indefinite_mute_for_the_user() {
+ let (context, repository) = context();
+ tool(MuteAction::Mute, None)
+ .call(ServiceContext(context), request())
+ .await
+ .expect("mute succeeds");
+
+ let sets = repository.sets.lock().unwrap();
+ assert_eq!(sets.len(), 1);
+ assert_eq!(sets[0].0, USER);
+ assert_eq!(sets[0].1, "0f6d9a0e-1b62-4f53-9f4c-0b9e2f6f0c11");
+ assert_eq!(sets[0].2, None);
+}
+
+#[tokio::test]
+async fn snooze_saves_the_deadline() {
+ let until = Utc::now() + Duration::hours(2);
+ let (context, repository) = context();
+ let response = tool(MuteAction::Snooze, Some(until))
+ .call(ServiceContext(context), request())
+ .await
+ .expect("snooze succeeds");
+
+ assert_eq!(response.snooze_until, Some(until));
+ assert_eq!(repository.sets.lock().unwrap()[0].2, Some(until));
+}
+
+#[tokio::test]
+async fn snooze_needs_a_future_deadline() {
+ let missing = tool(MuteAction::Snooze, None)
+ .call(ServiceContext(context().0), request())
+ .await
+ .expect_err("snooze without a deadline");
+ assert!(missing.description.contains("snoozeUntil"));
+
+ let past = tool(MuteAction::Snooze, Some(Utc::now() - Duration::hours(1)))
+ .call(ServiceContext(context().0), request())
+ .await
+ .expect_err("snooze in the past");
+ assert!(past.description.contains("future"));
+}
+
+#[tokio::test]
+async fn unmute_removes_the_preference() {
+ let (context, repository) = context();
+ tool(MuteAction::Unmute, None)
+ .call(ServiceContext(context), request())
+ .await
+ .expect("unmute succeeds");
+
+ assert!(repository.sets.lock().unwrap().is_empty());
+ assert_eq!(repository.removes.lock().unwrap().len(), 1);
+}
diff --git a/crates/projects/src/inbound/toolset.rs b/crates/projects/src/inbound/toolset.rs
index 4919fe28f3..52709ad080 100644
--- a/crates/projects/src/inbound/toolset.rs
+++ b/crates/projects/src/inbound/toolset.rs
@@ -1,8 +1,13 @@
//! Toolset inbound adapter for projects.
mod create_project;
+mod duplicate_item;
+mod entity_receipts;
mod move_to_project;
+mod move_to_trash;
mod read_project;
+mod rename_item;
+mod update_sharing;
#[cfg(test)]
mod test;
@@ -12,34 +17,90 @@ use std::sync::Arc;
use ai_toolset::AsyncToolCollection;
use bot_id::BotId;
use entity_access::domain::ports::EntityAccessService;
-use entity_mutation::MoveEntity;
+use entity_mutation::{
+ DuplicateEntity, MoveEntity, RenameEntity, TrashEntity, UpdateEntitySharePolicy,
+};
use crate::domain::ports::ProjectService;
pub use create_project::{CreateProject, CreateProjectResponse};
+pub use duplicate_item::{DuplicableEntityType, DuplicateItem, DuplicateItemResponse};
pub use move_to_project::{MoveToProject, MoveToProjectResponse, MoveableEntityType};
+pub use move_to_trash::{MoveToTrash, MoveToTrashResponse, TrashableEntityType};
pub use read_project::{ProjectItem, ProjectItemType, ReadProject, ReadProjectResponse};
+pub use rename_item::{RenameItem, RenameItemResponse, RenameableEntityType};
+pub use update_sharing::{
+ ShareAccess, ShareLinkScope, SharingChannel, SharingEntityType, UpdateSharing,
+ UpdateSharingResponse,
+};
+
+/// The entity capabilities project tools dispatch projects to.
+pub trait ProjectCapabilities:
+ ProjectService + MoveEntity + RenameEntity + TrashEntity + UpdateEntitySharePolicy
+{
+}
+
+impl<T> ProjectCapabilities for T where
+ T: ProjectService + MoveEntity + RenameEntity + TrashEntity + UpdateEntitySharePolicy
+{
+}
+
+/// The entity capabilities project tools dispatch documents to.
+pub trait DocumentCapabilities:
+ MoveEntity + TrashEntity + DuplicateEntity + UpdateEntitySharePolicy + Send + Sync + 'static
+{
+}
+
+impl<T> DocumentCapabilities for T where
+ T: MoveEntity + TrashEntity + DuplicateEntity + UpdateEntitySharePolicy + Send + Sync + 'static
+{
+}
+
+/// The entity capabilities project tools dispatch AI chats to.
+pub trait ChatCapabilities:
+ MoveEntity
+ + RenameEntity
+ + TrashEntity
+ + DuplicateEntity
+ + UpdateEntitySharePolicy
+ + Send
+ + Sync
+ + 'static
+{
+}
+
+impl<T> ChatCapabilities for T where
+ T: MoveEntity
+ + RenameEntity
+ + TrashEntity
+ + DuplicateEntity
+ + UpdateEntitySharePolicy
+ + Send
+ + Sync
+ + 'static
+{
+}
/// Service context for project AI tools.
///
-/// The move services are the per-domain [`MoveEntity`] capability impls the
-/// `MoveToProject` tool dispatches to, mirroring the DSS entity-mutation
-/// router.
+/// The document and chat services are the per-domain entity-mutation
+/// capability impls the move, trash, duplicate, rename, and sharing tools
+/// dispatch to, mirroring the DSS entity-mutation router.
pub struct ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
/// The project service instance.
pub service: Arc<PSvc>,
/// The entity access service — used to mint access receipts.
pub entity_access_service: Arc<ESvc>,
- /// Move capability for documents.
+ /// Move, trash, duplicate, and sharing capabilities for documents.
pub document_move_service: Arc<DSvc>,
- /// Move capability for AI chats.
+ /// Move, rename, trash, duplicate, and sharing capabilities for AI chats.
pub chat_move_service: Arc<CSvc>,
/// Move capability for email threads.
pub email_move_service: Arc<EmSvc>,
@@ -50,10 +111,10 @@ where
impl<PSvc, ESvc, DSvc, CSvc, EmSvc> Clone for ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
fn clone(&self) -> Self {
@@ -70,10 +131,10 @@ where
impl<PSvc, ESvc, DSvc, CSvc, EmSvc> ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
/// Create a new project tool context.
@@ -105,14 +166,18 @@ where
pub fn project_toolset<PSvc, ESvc, DSvc, CSvc, EmSvc>()
-> AsyncToolCollection<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
AsyncToolCollection::new()
.add_tool::<CreateProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
.add_tool::<ReadProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
.add_tool::<MoveToProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<MoveToTrash, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<DuplicateItem, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<RenameItem, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<UpdateSharing, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
}
diff --git a/crates/projects/src/inbound/toolset/create_project.rs b/crates/projects/src/inbound/toolset/create_project.rs
index 3ffe6f37a6..05a7664f29 100644
--- a/crates/projects/src/inbound/toolset/create_project.rs
+++ b/crates/projects/src/inbound/toolset/create_project.rs
@@ -13,9 +13,8 @@ use model_owner::CreationPrincipal;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use super::ProjectToolContext;
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
use crate::domain::models::ProjectError;
-use crate::domain::ports::ProjectService;
fn failed_to_create_project(error: ProjectError) -> ToolCallError {
let description = match &error {
@@ -70,10 +69,10 @@ impl ToolAnnotated for CreateProject {
impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
for CreateProject
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
type Output = CreateProjectResponse;
diff --git a/crates/projects/src/inbound/toolset/duplicate_item.rs b/crates/projects/src/inbound/toolset/duplicate_item.rs
new file mode 100644
index 0000000000..570b2923fd
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/duplicate_item.rs
@@ -0,0 +1,168 @@
+//! DuplicateItem tool for copying documents and AI chats.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{DuplicateEntity, EntityMutationEffect, MoveEntity};
+use model_entity::{Entity, EntityType};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::entity_receipts::{first_updated, mutation_failed, user_receipt};
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
+
+/// The kind of item to duplicate.
+#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum DuplicableEntityType {
+ /// A document (includes tasks).
+ Document,
+ /// An AI chat conversation.
+ Chat,
+}
+
+impl DuplicableEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Document => EntityType::Document,
+ Self::Chat => EntityType::Chat,
+ }
+ }
+}
+
+const DUPLICATE_FORBIDDEN: &str = "you need at least view access to an item to duplicate it";
+
+/// Duplicate an entity through its domain capability, as the user.
+async fn duplicate_with<S, ESvc>(
+ service: &S,
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ entity: Entity<'static>,
+ name: Option<String>,
+) -> ToolResult<Vec<EntityMutationEffect>>
+where
+ S: DuplicateEntity,
+ ESvc: EntityAccessService,
+{
+ let receipt =
+ user_receipt::<S::Receipt, _>(entity_access_service, request_context, &entity).await?;
+ service
+ .duplicate_entity(entity, receipt, request_context.user_id.clone(), name)
+ .await
+ .map_err(mutation_failed("duplicate", DUPLICATE_FORBIDDEN))
+}
+
+/// The duplicate item response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DuplicateItemResponse {
+ /// The kind of item duplicated.
+ pub entity_type: DuplicableEntityType,
+ /// The id of the original item.
+ pub source_id: uuid::Uuid,
+ /// The id of the new copy.
+ pub copy_id: String,
+ /// A human-readable result message.
+ pub message: String,
+}
+
+/// DuplicateItem tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DuplicateItem",
+ description = "Make a copy of a document (including a task) or an AI chat, owned by the user, as the Duplicate action in the app does. Requires view access to the original. Returns the copy's id."
+)]
+pub struct DuplicateItem {
+ /// The kind of item to duplicate.
+ #[schemars(description = "The kind of item to duplicate.")]
+ pub entity_type: DuplicableEntityType,
+
+ /// The id of the item to duplicate.
+ #[schemars(description = "The id of the item to duplicate.")]
+ pub entity_id: uuid::Uuid,
+
+ /// Optional name for the copy.
+ #[schemars(
+ description = "Name for the copy of a document. Omit to use \"<original name> copy\". AI chat copies always keep the original name."
+ )]
+ #[serde(default)]
+ pub name: Option<String>,
+}
+
+impl ToolAnnotated for DuplicateItem {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Duplicate");
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for DuplicateItem
+where
+ PSvc: ProjectCapabilities,
+ ESvc: EntityAccessService,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = DuplicateItemResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=?self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let name = self
+ .name
+ .as_deref()
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .map(str::to_string);
+ let access = &*service_context.entity_access_service;
+ let effects = match self.entity_type {
+ DuplicableEntityType::Document => {
+ duplicate_with(
+ &*service_context.document_move_service,
+ access,
+ &request_context,
+ entity,
+ name,
+ )
+ .await?
+ }
+ // Chat copies keep the source name; the domain rejects a custom one.
+ DuplicableEntityType::Chat => {
+ duplicate_with(
+ &*service_context.chat_move_service,
+ access,
+ &request_context,
+ entity,
+ None,
+ )
+ .await?
+ }
+ };
+ let copy_id = first_updated(&effects)
+ .map(|copy| copy.entity_id.to_string())
+ .ok_or_else(|| ToolCallError {
+ description: "the item was duplicated but its copy could not be identified"
+ .to_string(),
+ internal_error: anyhow::anyhow!("duplicate returned no updated entity"),
+ })?;
+
+ Ok(DuplicateItemResponse {
+ entity_type: self.entity_type,
+ source_id: self.entity_id,
+ message: format!(
+ "Duplicated the {} as {copy_id}.",
+ self.entity_type.entity_type()
+ ),
+ copy_id,
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/entity_receipts.rs b/crates/projects/src/inbound/toolset/entity_receipts.rs
new file mode 100644
index 0000000000..962c4a7b35
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/entity_receipts.rs
@@ -0,0 +1,86 @@
+//! Receipt minting and error mapping shared by the entity lifecycle tools.
+
+use ai_toolset::{RequestContext, ToolCallError};
+use entity_access::domain::models::{AccessError, EntityAccessReceipt, RequiredPermission};
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{EntityMutationEffect, EntityMutationErrorCode};
+use model_entity::{Entity, EntityType};
+
+/// Mint the requesting user's receipt for an entity.
+///
+/// Lifecycle mutations (trash, duplicate, rename, sharing) run as the user,
+/// like their REST and GraphQL paths: several domains read the authenticated
+/// user off the receipt to record who deleted or now owns the entity.
+pub(super) async fn user_receipt<T, ESvc>(
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ entity: &Entity<'static>,
+) -> Result<EntityAccessReceipt<T>, ToolCallError>
+where
+ T: RequiredPermission,
+ ESvc: EntityAccessService,
+{
+ entity_access_service
+ .generate_entity_access_receipt::<T>(
+ &request_context.user_id,
+ None,
+ &entity.entity_id,
+ entity.entity_type,
+ )
+ .await
+ .map_err(|error| access_failed(entity.entity_type, error))
+}
+
+fn access_failed(entity_type: EntityType, error: AccessError) -> ToolCallError {
+ let description = match error {
+ AccessError::NotFound(_) => format!("{entity_type} not found"),
+ AccessError::BadRequest(_) => format!("invalid {entity_type} id"),
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ format!("you do not have the access this action requires on the {entity_type}")
+ }
+ AccessError::Unavailable(_) | AccessError::Internal(_) => {
+ format!("failed to verify access to the {entity_type}")
+ }
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
+/// Map a domain mutation failure onto an actionable tool error. `forbidden`
+/// states the access the action needs for each entity kind.
+pub(super) fn mutation_failed(
+ action: &'static str,
+ forbidden: &'static str,
+) -> impl FnOnce(EntityMutationErrorCode) -> ToolCallError {
+ move |code| {
+ let description = match code {
+ EntityMutationErrorCode::Forbidden(_) => forbidden.to_string(),
+ EntityMutationErrorCode::NotFound(_) => "the item was not found".to_string(),
+ EntityMutationErrorCode::Conflict(_) => {
+ format!("cannot {action} the item in its current state (it may already be deleted)")
+ }
+ EntityMutationErrorCode::InvalidInput(_) => {
+ format!("invalid request to {action} the item")
+ }
+ EntityMutationErrorCode::UnsupportedOperation(_) => {
+ format!("cannot {action} this kind of item")
+ }
+ EntityMutationErrorCode::Internal(_) => format!("failed to {action} the item"),
+ };
+ ToolCallError {
+ description,
+ internal_error: anyhow::anyhow!("{action} entity failed: {code:?}"),
+ }
+ }
+}
+
+/// The first entity a mutation reports as updated, for mutations whose first
+/// effect is the entity they produced.
+pub(super) fn first_updated(effects: &[EntityMutationEffect]) -> Option<&Entity<'static>> {
+ effects.iter().find_map(|effect| match effect {
+ EntityMutationEffect::Updated(entity) => Some(entity),
+ EntityMutationEffect::Deleted(_) => None,
+ })
+}
diff --git a/crates/projects/src/inbound/toolset/move_to_project.rs b/crates/projects/src/inbound/toolset/move_to_project.rs
index 82dc88f8f2..fd44fa91cf 100644
--- a/crates/projects/src/inbound/toolset/move_to_project.rs
+++ b/crates/projects/src/inbound/toolset/move_to_project.rs
@@ -14,8 +14,7 @@ use model_entity::{Entity, EntityType};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use super::ProjectToolContext;
-use crate::domain::ports::ProjectService;
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
/// The kind of entity to move.
#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
@@ -224,10 +223,10 @@ impl ToolAnnotated for MoveToProject {
impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
for MoveToProject
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
type Output = MoveToProjectResponse;
diff --git a/crates/projects/src/inbound/toolset/move_to_trash.rs b/crates/projects/src/inbound/toolset/move_to_trash.rs
new file mode 100644
index 0000000000..8b03d3c0b3
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/move_to_trash.rs
@@ -0,0 +1,146 @@
+//! MoveToTrash tool for deleting documents, AI chats, and projects to the trash.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{MoveEntity, TrashEntity};
+use model_entity::{Entity, EntityType};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::entity_receipts::{mutation_failed, user_receipt};
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
+
+/// The kind of item to move to the trash.
+#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum TrashableEntityType {
+ /// A document (includes tasks).
+ Document,
+ /// An AI chat conversation.
+ Chat,
+ /// A project (folder), with everything inside it.
+ Project,
+}
+
+impl TrashableEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Document => EntityType::Document,
+ Self::Chat => EntityType::Chat,
+ Self::Project => EntityType::Project,
+ }
+ }
+}
+
+const TRASH_FORBIDDEN: &str = "only the owner of an item can move it to the trash";
+
+/// Trash an entity through its domain capability, as the user.
+async fn trash_with<S, ESvc>(
+ service: &S,
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ entity: Entity<'static>,
+) -> ToolResult<()>
+where
+ S: TrashEntity,
+ ESvc: EntityAccessService,
+{
+ let receipt =
+ user_receipt::<S::Receipt, _>(entity_access_service, request_context, &entity).await?;
+ service
+ .trash_entity(entity, receipt)
+ .await
+ .map_err(mutation_failed("trash", TRASH_FORBIDDEN))?;
+ Ok(())
+}
+
+/// The move to trash response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct MoveToTrashResponse {
+ /// The kind of item trashed.
+ pub entity_type: TrashableEntityType,
+ /// The trashed item's id.
+ pub entity_id: uuid::Uuid,
+ /// A human-readable result message.
+ pub message: String,
+}
+
+/// MoveToTrash tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "MoveToTrash",
+ description = "Delete a document (including a task), an AI chat, or a project (folder) by moving it to the trash, as the Delete action in the app does. Trashing a project also trashes everything inside it. Only the item's owner can trash it. Use only when the user explicitly asks to delete an item. Channels, email threads, and calendar events are not deleted with this tool."
+)]
+pub struct MoveToTrash {
+ /// The kind of item to trash.
+ #[schemars(description = "The kind of item to move to the trash.")]
+ pub entity_type: TrashableEntityType,
+
+ /// The id of the item to trash.
+ #[schemars(description = "The id of the item to move to the trash.")]
+ pub entity_id: uuid::Uuid,
+}
+
+impl ToolAnnotated for MoveToTrash {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Move to trash").with_idempotent();
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for MoveToTrash
+where
+ PSvc: ProjectCapabilities,
+ ESvc: EntityAccessService,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = MoveToTrashResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=?self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let access = &*service_context.entity_access_service;
+ match self.entity_type {
+ TrashableEntityType::Document => {
+ trash_with(
+ &*service_context.document_move_service,
+ access,
+ &request_context,
+ entity,
+ )
+ .await?
+ }
+ TrashableEntityType::Chat => {
+ trash_with(
+ &*service_context.chat_move_service,
+ access,
+ &request_context,
+ entity,
+ )
+ .await?
+ }
+ TrashableEntityType::Project => {
+ trash_with(&*service_context.service, access, &request_context, entity).await?
+ }
+ }
+
+ Ok(MoveToTrashResponse {
+ entity_type: self.entity_type,
+ entity_id: self.entity_id,
+ message: format!("Moved the {} to the trash.", self.entity_type.entity_type()),
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/read_project.rs b/crates/projects/src/inbound/toolset/read_project.rs
index 5f99def498..9f98ec2b85 100644
--- a/crates/projects/src/inbound/toolset/read_project.rs
+++ b/crates/projects/src/inbound/toolset/read_project.rs
@@ -11,8 +11,7 @@ use model_entity::EntityType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use super::ProjectToolContext;
-use crate::domain::ports::ProjectService;
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
/// The kind of an item inside a project.
#[derive(Debug, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
@@ -108,10 +107,10 @@ impl ToolAnnotated for ReadProject {
impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
for ReadProject
where
- PSvc: ProjectService + MoveEntity,
+ PSvc: ProjectCapabilities,
ESvc: EntityAccessService,
- DSvc: MoveEntity + Send + Sync + 'static,
- CSvc: MoveEntity + Send + Sync + 'static,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
EmSvc: MoveEntity + Send + Sync + 'static,
{
type Output = ReadProjectResponse;
diff --git a/crates/projects/src/inbound/toolset/rename_item.rs b/crates/projects/src/inbound/toolset/rename_item.rs
new file mode 100644
index 0000000000..f2e2787b23
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/rename_item.rs
@@ -0,0 +1,154 @@
+//! RenameItem tool for renaming projects (folders) and AI chats.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{MoveEntity, RenameEntity};
+use model_entity::{Entity, EntityType};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::entity_receipts::{mutation_failed, user_receipt};
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
+
+/// The kind of item to rename.
+#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum RenameableEntityType {
+ /// A project (folder).
+ Project,
+ /// An AI chat conversation.
+ Chat,
+}
+
+impl RenameableEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Project => EntityType::Project,
+ Self::Chat => EntityType::Chat,
+ }
+ }
+}
+
+const RENAME_FORBIDDEN: &str =
+ "renaming a project requires edit access and renaming an AI chat requires owning it";
+
+/// Rename an entity through its domain capability, as the user.
+async fn rename_with<S, ESvc>(
+ service: &S,
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ entity: Entity<'static>,
+ name: String,
+) -> ToolResult<()>
+where
+ S: RenameEntity,
+ ESvc: EntityAccessService,
+{
+ let receipt =
+ user_receipt::<S::Receipt, _>(entity_access_service, request_context, &entity).await?;
+ service
+ .rename_entity(entity, receipt, name)
+ .await
+ .map_err(mutation_failed("rename", RENAME_FORBIDDEN))?;
+ Ok(())
+}
+
+/// The rename item response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RenameItemResponse {
+ /// The kind of item renamed.
+ pub entity_type: RenameableEntityType,
+ /// The renamed item's id.
+ pub entity_id: uuid::Uuid,
+ /// The new name.
+ pub name: String,
+}
+
+/// RenameItem tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "RenameItem",
+ description = "Rename a project (shown as a folder in the app) or an AI chat. Renaming a project requires edit access; renaming an AI chat requires owning it. Use RenameDocument for documents and tasks, and RenameChannel for channels."
+)]
+pub struct RenameItem {
+ /// The kind of item to rename.
+ #[schemars(description = "The kind of item to rename.")]
+ pub entity_type: RenameableEntityType,
+
+ /// The id of the item to rename.
+ #[schemars(description = "The id of the item to rename.")]
+ pub entity_id: uuid::Uuid,
+
+ /// The new name.
+ #[schemars(description = "The new name.")]
+ pub name: String,
+}
+
+impl ToolAnnotated for RenameItem {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Rename").with_idempotent();
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for RenameItem
+where
+ PSvc: ProjectCapabilities,
+ ESvc: EntityAccessService,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = RenameItemResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=?self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let name = self.name.trim().to_string();
+ if name.is_empty() {
+ return Err(ToolCallError {
+ description: "name must not be empty".to_string(),
+ internal_error: anyhow::anyhow!("empty rename"),
+ });
+ }
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let access = &*service_context.entity_access_service;
+ match self.entity_type {
+ RenameableEntityType::Project => {
+ rename_with(
+ &*service_context.service,
+ access,
+ &request_context,
+ entity,
+ name.clone(),
+ )
+ .await?
+ }
+ RenameableEntityType::Chat => {
+ rename_with(
+ &*service_context.chat_move_service,
+ access,
+ &request_context,
+ entity,
+ name.clone(),
+ )
+ .await?
+ }
+ }
+
+ Ok(RenameItemResponse {
+ entity_type: self.entity_type,
+ entity_id: self.entity_id,
+ name,
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/test.rs b/crates/projects/src/inbound/toolset/test.rs
index 9d11a613f3..6bd7f3e3ec 100644
--- a/crates/projects/src/inbound/toolset/test.rs
+++ b/crates/projects/src/inbound/toolset/test.rs
@@ -66,3 +66,118 @@ fn test_move_to_project_deserializes_entity_types() {
assert!(tool.project_id.is_none());
}
}
+
+#[test]
+fn test_entity_lifecycle_schema_validation() {
+ for (name, result) in [
+ (
+ "MoveToTrash",
+ generate_validated_input_schema::<MoveToTrash>(),
+ ),
+ (
+ "DuplicateItem",
+ generate_validated_input_schema::<DuplicateItem>(),
+ ),
+ (
+ "RenameItem",
+ generate_validated_input_schema::<RenameItem>(),
+ ),
+ (
+ "UpdateSharing",
+ generate_validated_input_schema::<UpdateSharing>(),
+ ),
+ ] {
+ let validated = result.unwrap_or_else(|error| panic!("{name}: {error:?}"));
+ assert_eq!(validated.name, name);
+ }
+}
+
+#[test]
+fn test_move_to_trash_rejects_untrashable_kinds() {
+ let tool = serde_json::from_value::<MoveToTrash>(serde_json::json!({
+ "entityType": "channel",
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ }));
+ assert!(tool.is_err(), "channels are not trashed with MoveToTrash");
+}
+
+fn sharing(input: serde_json::Value) -> UpdateSharing {
+ serde_json::from_value(input).expect("valid input")
+}
+
+#[test]
+fn test_update_sharing_maps_off_to_disabling_each_share() {
+ use models_permissions::share_permission::channel_share_permission::UpdateOperation;
+
+ let tool = sharing(serde_json::json!({
+ "entityType": "document",
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ "linkScope": "off",
+ "teamAccess": "off",
+ "channels": [{
+ "channelId": "0f6d9a0e-1b62-4f53-9f4c-0b9e2f6f0c11",
+ "access": "off",
+ }],
+ }));
+ let policy = tool.policy();
+
+ assert_eq!(policy.link_share, Some(None));
+ assert_eq!(policy.team_share_access_level, Some(None));
+ assert_eq!(
+ policy.link_share_access_level, None,
+ "omitted stays unchanged"
+ );
+ let channels = policy.channel_share_permissions.expect("channel change");
+ assert_eq!(channels[0].operation, UpdateOperation::Remove);
+ assert_eq!(channels[0].access_level, None);
+}
+
+#[test]
+fn test_update_sharing_maps_grants_to_levels() {
+ use models_permissions::share_permission::{
+ LinkShare, access_level::AccessLevel, channel_share_permission::UpdateOperation,
+ };
+
+ let tool = sharing(serde_json::json!({
+ "entityType": "chat",
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ "linkScope": "team",
+ "linkAccess": "comment",
+ "teamAccess": "edit",
+ "channels": [{
+ "channelId": "0f6d9a0e-1b62-4f53-9f4c-0b9e2f6f0c11",
+ "access": "view",
+ }],
+ }));
+ let policy = tool.policy();
+
+ assert_eq!(policy.link_share, Some(Some(LinkShare::Team)));
+ assert_eq!(
+ policy.link_share_access_level,
+ Some(Some(AccessLevel::Comment))
+ );
+ assert_eq!(
+ policy.team_share_access_level,
+ Some(Some(AccessLevel::Edit))
+ );
+ let channels = policy.channel_share_permissions.expect("channel change");
+ assert_eq!(channels[0].operation, UpdateOperation::Replace);
+ assert_eq!(channels[0].access_level, Some(AccessLevel::View));
+}
+
+#[test]
+fn test_update_sharing_detects_an_empty_change() {
+ let empty = sharing(serde_json::json!({
+ "entityType": "project",
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ "channels": [],
+ }));
+ assert!(empty.is_empty());
+
+ let change = sharing(serde_json::json!({
+ "entityType": "project",
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ "teamAccess": "view",
+ }));
+ assert!(!change.is_empty());
+}
diff --git a/crates/projects/src/inbound/toolset/update_sharing.rs b/crates/projects/src/inbound/toolset/update_sharing.rs
new file mode 100644
index 0000000000..0ee2ba9daf
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/update_sharing.rs
@@ -0,0 +1,277 @@
+//! UpdateSharing tool for changing link, team, and channel sharing on
+//! documents, AI chats, and projects.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{MoveEntity, UpdateEntitySharePolicy};
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::{
+ LinkShare, UpdateSharePermissionRequestV2,
+ access_level::AccessLevel,
+ channel_share_permission::{UpdateChannelSharePermission, UpdateOperation},
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::entity_receipts::{mutation_failed, user_receipt};
+use super::{ChatCapabilities, DocumentCapabilities, ProjectCapabilities, ProjectToolContext};
+
+/// The kind of item whose sharing changes.
+#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum SharingEntityType {
+ /// A document (includes tasks).
+ Document,
+ /// An AI chat conversation.
+ Chat,
+ /// A project (folder).
+ Project,
+}
+
+impl SharingEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Document => EntityType::Document,
+ Self::Chat => EntityType::Chat,
+ Self::Project => EntityType::Project,
+ }
+ }
+}
+
+/// A share can be disabled or grant a non-owner permission.
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ShareAccess {
+ /// Disable this share.
+ Off,
+ /// View only.
+ View,
+ /// View and comment.
+ Comment,
+ /// Edit.
+ Edit,
+}
+
+impl ShareAccess {
+ fn level(self) -> Option<AccessLevel> {
+ match self {
+ Self::Off => None,
+ Self::View => Some(AccessLevel::View),
+ Self::Comment => Some(AccessLevel::Comment),
+ Self::Edit => Some(AccessLevel::Edit),
+ }
+ }
+}
+
+/// Who an item's share link admits.
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ShareLinkScope {
+ /// Disable link sharing.
+ Off,
+ /// Anyone with the link.
+ Public,
+ /// Members of the owner's team with the link.
+ Team,
+}
+
+/// One channel's grant to set or remove.
+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SharingChannel {
+ /// Channel id to share with or revoke.
+ #[schemars(description = "Channel id to share with or revoke.")]
+ pub channel_id: Uuid,
+ /// Desired grant; off removes only this channel's grant.
+ #[schemars(description = "Desired grant; off removes only this channel's grant.")]
+ pub access: ShareAccess,
+}
+
+const SHARE_FORBIDDEN: &str = "changing sharing requires edit access to a document and owning an AI chat or project; only the owner can change team access";
+
+/// Apply a share-policy update through the domain capability, as the user.
+async fn share_with<S, ESvc>(
+ service: &S,
+ entity_access_service: &ESvc,
+ request_context: &RequestContext,
+ entity: Entity<'static>,
+ policy: UpdateSharePermissionRequestV2,
+) -> ToolResult<()>
+where
+ S: UpdateEntitySharePolicy,
+ ESvc: EntityAccessService,
+{
+ let receipt =
+ user_receipt::<S::Receipt, _>(entity_access_service, request_context, &entity).await?;
+ service
+ .update_share_policy(entity, receipt, policy)
+ .await
+ .map_err(mutation_failed("share", SHARE_FORBIDDEN))?;
+ Ok(())
+}
+
+/// The update sharing response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateSharingResponse {
+ /// The kind of item whose sharing changed.
+ pub entity_type: SharingEntityType,
+ /// The item's id.
+ pub entity_id: Uuid,
+ /// A human-readable summary of the change.
+ pub message: String,
+}
+
+/// UpdateSharing tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "UpdateSharing",
+ description = "Change who can access a document (including a task), an AI chat, or a project (folder), as the Share menu in the app does: link sharing, team access, and per-channel access. Each omitted field stays unchanged; off disables that share. Requires edit access to a document, or owning an AI chat or project; only the owner can change team access. Use ShareWithChannel to post an item into a channel, and UpdateInitiativeSharing for Tasks projects (initiatives)."
+)]
+pub struct UpdateSharing {
+ /// The kind of item whose sharing changes.
+ #[schemars(description = "The kind of item whose sharing changes.")]
+ pub entity_type: SharingEntityType,
+ /// The item's id.
+ #[schemars(description = "The id of the item whose sharing changes.")]
+ pub entity_id: Uuid,
+ /// Who the share link admits.
+ #[schemars(
+ description = "Who the item's share link admits: public (anyone with the link), team (the owner's team members with the link), or off to disable link sharing."
+ )]
+ #[serde(default)]
+ pub link_scope: Option<ShareLinkScope>,
+ /// Permission granted by an enabled link.
+ #[schemars(
+ description = "Permission granted by an enabled share link. Off resets it to the default level."
+ )]
+ #[serde(default)]
+ pub link_access: Option<ShareAccess>,
+ /// Explicit owner-team grant.
+ #[schemars(description = "Access for everyone on the owner's team; off removes it.")]
+ #[serde(default)]
+ pub team_access: Option<ShareAccess>,
+ /// Channel grants to set or remove.
+ #[schemars(
+ description = "Individual channel grants to set or remove; other channel grants stay unchanged."
+ )]
+ #[serde(default)]
+ pub channels: Option<Vec<SharingChannel>>,
+}
+
+impl UpdateSharing {
+ pub(super) fn policy(&self) -> UpdateSharePermissionRequestV2 {
+ UpdateSharePermissionRequestV2 {
+ link_share: self.link_scope.map(|scope| match scope {
+ ShareLinkScope::Off => None,
+ ShareLinkScope::Public => Some(LinkShare::Public),
+ ShareLinkScope::Team => Some(LinkShare::Team),
+ }),
+ link_share_access_level: self.link_access.map(ShareAccess::level),
+ team_share_access_level: self.team_access.map(ShareAccess::level),
+ channel_share_permissions: self.channels.as_ref().map(|channels| {
+ channels
+ .iter()
+ .map(|channel| UpdateChannelSharePermission {
+ operation: if channel.access == ShareAccess::Off {
+ UpdateOperation::Remove
+ } else {
+ UpdateOperation::Replace
+ },
+ channel_id: channel.channel_id.to_string(),
+ access_level: channel.access.level(),
+ })
+ .collect()
+ }),
+ }
+ }
+
+ pub(super) fn is_empty(&self) -> bool {
+ self.link_scope.is_none()
+ && self.link_access.is_none()
+ && self.team_access.is_none()
+ && self.channels.as_ref().is_none_or(Vec::is_empty)
+ }
+}
+
+impl ToolAnnotated for UpdateSharing {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Change sharing").with_idempotent();
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for UpdateSharing
+where
+ PSvc: ProjectCapabilities,
+ ESvc: EntityAccessService,
+ DSvc: DocumentCapabilities,
+ CSvc: ChatCapabilities,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = UpdateSharingResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=?self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.is_empty() {
+ return Err(ToolCallError {
+ description:
+ "nothing to change: set at least one of linkScope, linkAccess, teamAccess, or channels"
+ .to_string(),
+ internal_error: anyhow::anyhow!("empty sharing update"),
+ });
+ }
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let policy = self.policy();
+ let access = &*service_context.entity_access_service;
+ match self.entity_type {
+ SharingEntityType::Document => {
+ share_with(
+ &*service_context.document_move_service,
+ access,
+ &request_context,
+ entity,
+ policy,
+ )
+ .await?
+ }
+ SharingEntityType::Chat => {
+ share_with(
+ &*service_context.chat_move_service,
+ access,
+ &request_context,
+ entity,
+ policy,
+ )
+ .await?
+ }
+ SharingEntityType::Project => {
+ share_with(
+ &*service_context.service,
+ access,
+ &request_context,
+ entity,
+ policy,
+ )
+ .await?
+ }
+ }
+
+ Ok(UpdateSharingResponse {
+ entity_type: self.entity_type,
+ entity_id: self.entity_id,
+ message: format!("Updated sharing on the {}.", self.entity_type.entity_type()),
+ })
+ }
+}
diff --git a/crates/routines/src/domain.rs b/crates/routines/src/domain.rs
index 116641a76a..22a05fac11 100644
--- a/crates/routines/src/domain.rs
+++ b/crates/routines/src/domain.rs
@@ -146,6 +146,15 @@ pub struct RoutineDetails {
/// Most recent runs, up to fifty, including status and transcript references.
pub runs: Vec<serde_json::Value>,
}
+/// A run started on demand; it continues after the call returns.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RoutineRunStarted {
+ /// The routine that is running.
+ pub routine_id: Uuid,
+ /// The chat or agent session the run writes to, when the scheduler reports one.
+ pub resource: Option<serde_json::Value>,
+}
/// Owning-service capability: authorization remains in the scheduler, never the tools.
#[async_trait]
pub trait RoutineService: Send + Sync {
@@ -173,4 +182,8 @@ pub trait RoutineService: Send + Sync {
id: Uuid,
enabled: bool,
) -> Result<RoutineInfo>;
+ /// Permanently delete an owned routine and its schedule.
+ async fn delete(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<()>;
+ /// Start an owned routine now, outside its schedule.
+ async fn run_now(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<RoutineRunStarted>;
}
diff --git a/crates/routines/src/inbound.rs b/crates/routines/src/inbound.rs
index 494877c0b9..a6688f3e2d 100644
--- a/crates/routines/src/inbound.rs
+++ b/crates/routines/src/inbound.rs
@@ -1,6 +1,7 @@
//! AI workflow tools. Request identity is supplied by the host, never by the model.
use crate::domain::{
- RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineList, RoutineService,
+ RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineList, RoutineRunStarted,
+ RoutineService,
};
use ai_toolset::{
AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,
@@ -8,7 +9,7 @@ use ai_toolset::{
};
use async_trait::async_trait;
use schemars::JsonSchema;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;
@@ -40,6 +41,8 @@ pub fn routine_toolset() -> AsyncToolCollection<RoutineToolContext> {
.add_tool::<ListRoutines, RoutineToolContext>()
.add_tool::<ReadRoutine, RoutineToolContext>()
.add_tool::<UpdateRoutine, RoutineToolContext>()
+ .add_tool::<RunRoutine, RoutineToolContext>()
+ .add_tool::<DeleteRoutine, RoutineToolContext>()
}
/// Schedule future work.
#[derive(Deserialize, JsonSchema)]
@@ -197,3 +200,72 @@ impl AsyncTool<RoutineToolContext> for UpdateRoutine {
.map_err(error)
}
}
+/// Run an owned routine immediately.
+#[derive(Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "RunRoutine",
+ description = "Start a routine owned by the authenticated user now, outside its schedule, as Run Now in the app does. The run continues after this returns; check its result later with ReadRoutine. Fails if the routine is already running."
+)]
+pub struct RunRoutine {
+ /// Routine UUID.
+ pub routine_id: Uuid,
+}
+impl ToolAnnotated for RunRoutine {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Run routine");
+}
+#[async_trait]
+impl AsyncTool<RoutineToolContext> for RunRoutine {
+ type Output = RoutineRunStarted;
+ async fn call(
+ &self,
+ context: ServiceContext<RoutineToolContext>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ context
+ .service()?
+ .run_now(&request.user_id, self.routine_id)
+ .await
+ .map_err(error)
+ }
+}
+/// Delete an owned routine.
+#[derive(Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteRoutine",
+ description = "Permanently delete a routine owned by the authenticated user, stopping all future runs. This cannot be undone; to stop it temporarily, pause it with UpdateRoutine instead. Use only when the user explicitly asks to delete a routine."
+)]
+pub struct DeleteRoutine {
+ /// Routine UUID.
+ pub routine_id: Uuid,
+}
+/// The deleted routine.
+#[derive(Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeletedRoutine {
+ /// Routine UUID.
+ pub routine_id: Uuid,
+}
+impl ToolAnnotated for DeleteRoutine {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Delete routine").with_idempotent();
+}
+#[async_trait]
+impl AsyncTool<RoutineToolContext> for DeleteRoutine {
+ type Output = DeletedRoutine;
+ async fn call(
+ &self,
+ context: ServiceContext<RoutineToolContext>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ context
+ .service()?
+ .delete(&request.user_id, self.routine_id)
+ .await
+ .map_err(error)?;
+ Ok(DeletedRoutine {
+ routine_id: self.routine_id,
+ })
+ }
+}
diff --git a/crates/routines/src/outbound.rs b/crates/routines/src/outbound.rs
index 948e78f668..e3e9c9d263 100644
--- a/crates/routines/src/outbound.rs
+++ b/crates/routines/src/outbound.rs
@@ -1,6 +1,7 @@
//! Authenticated, bounded HTTP calls to the scheduled-action service.
use crate::domain::{
- RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineService, RoutineTarget,
+ RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineRunStarted, RoutineService,
+ RoutineTarget,
};
use anyhow::{Context, Result, bail, ensure};
use async_trait::async_trait;
@@ -53,6 +54,16 @@ impl RoutineClient {
path: &str,
body: Option<Value>,
) -> Result<T> {
+ let body = self.request_bytes(user, method, path, body).await?;
+ serde_json::from_slice(&body).context("Invalid routine service response")
+ }
+ async fn request_bytes(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ method: Method,
+ path: &str,
+ body: Option<Value>,
+ ) -> Result<Vec<u8>> {
let mut request = self
.client
.request(method, self.base.join(path)?)
@@ -79,12 +90,13 @@ impl RoutineClient {
);
body.extend_from_slice(&chunk);
}
- serde_json::from_slice(&body).context("Invalid routine service response")
+ Ok(body)
}
400 | 422 => bail!(
"Invalid routine configuration or unavailable model/agent. Check the schedule and select an accessible agent from ListAgents using its bot.botId."
),
401 | 403 | 404 => bail!("Routine or target is unavailable to this user."),
+ 402 => bail!("The user's AI allowance is exhausted, so the routine cannot run now."),
409 => bail!("Routine is running or changed. Read it again before editing."),
_ => bail!(
"Routine service is unavailable. Check ListRoutines before retrying a creation."
@@ -191,8 +203,38 @@ impl RoutineService for RoutineClient {
.await?
.into())
}
+ async fn delete(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<()> {
+ self.request_bytes(
+ user,
+ Method::DELETE,
+ &format!("scheduled-actions/{id}"),
+ None,
+ )
+ .await?;
+ Ok(())
+ }
+ async fn run_now(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<RoutineRunStarted> {
+ let execution = self
+ .request::<WireExecution>(
+ user,
+ Method::POST,
+ &format!("scheduled-actions/{id}/execute"),
+ None,
+ )
+ .await?;
+ Ok(RoutineRunStarted {
+ routine_id: execution.action_id,
+ resource: execution.resource,
+ })
+ }
}
+#[derive(Deserialize)]
+struct WireExecution {
+ action_id: Uuid,
+ #[serde(default)]
+ resource: Option<Value>,
+}
fn configuration_body(config: &RoutineConfiguration, now: DateTime<Utc>) -> Result<Value> {
config.validate(now)?;
let (schedule, timezone) = config.schedule.cron(now)?;
diff --git a/crates/routines/src/outbound/test.rs b/crates/routines/src/outbound/test.rs
index 118eae5990..731d34d02e 100644
--- a/crates/routines/src/outbound/test.rs
+++ b/crates/routines/src/outbound/test.rs
@@ -107,3 +107,98 @@ async fn requests_forward_authenticated_identity_and_preserve_target_and_activat
assert!(bodies[1].get("enabled").is_none());
assert_eq!(bodies[2], serde_json::json!({"enabled": false}));
}
+
+/// Serve one canned `(status, body)` per request and return the raw requests.
+fn serve_responses(
+ listener: tokio::net::TcpListener,
+ responses: Vec<(&'static str, String)>,
+) -> tokio::task::JoinHandle<Vec<String>> {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ tokio::spawn(async move {
+ let mut requests = Vec::new();
+ for (status, body) in responses {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut bytes = Vec::new();
+ loop {
+ let mut chunk = [0_u8; 4096];
+ let read = stream.read(&mut chunk).await.unwrap();
+ assert!(read > 0);
+ bytes.extend_from_slice(&chunk[..read]);
+ let text = String::from_utf8_lossy(&bytes);
+ if let Some(header_end) = text.find("\r\n\r\n") {
+ let length = text[..header_end]
+ .lines()
+ .find_map(|line| {
+ line.to_lowercase()
+ .strip_prefix("content-length: ")
+ .map(|n| n.parse::<usize>().unwrap())
+ })
+ .unwrap_or(0);
+ if bytes.len() >= header_end + 4 + length {
+ break;
+ }
+ }
+ }
+ requests.push(String::from_utf8(bytes).unwrap());
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len(),
+ );
+ stream.write_all(response.as_bytes()).await.unwrap();
+ }
+ requests
+ })
+}
+
+#[tokio::test]
+async fn delete_and_run_now_call_the_owner_routes() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/scheduled-action", listener.local_addr().unwrap());
+ let id = Uuid::from_u128(7);
+ let execution = serde_json::json!({
+ "action_id": id,
+ "chat_id": null,
+ "resource": { "type": "agent", "id": "session-1" },
+ })
+ .to_string();
+ let server = serve_responses(
+ listener,
+ vec![("204 No Content", String::new()), ("200 OK", execution)],
+ );
+ let client = RoutineClient::new(&url, "test-internal-key").unwrap();
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ client
+ .delete(&user, id)
+ .await
+ .expect("204 is a successful delete");
+ let started = client.run_now(&user, id).await.expect("run starts");
+
+ assert_eq!(started.routine_id, id);
+ assert_eq!(started.resource.unwrap()["id"], "session-1");
+ let requests = server.await.unwrap();
+ assert!(requests[0].starts_with(&format!("DELETE /scheduled-action/scheduled-actions/{id} ")));
+ assert!(requests[1].starts_with(&format!(
+ "POST /scheduled-action/scheduled-actions/{id}/execute "
+ )));
+ for request in &requests {
+ assert!(request.to_lowercase().contains("macro|[email protected]"));
+ }
+}
+
+#[tokio::test]
+async fn run_now_explains_an_exhausted_ai_allowance() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/scheduled-action", listener.local_addr().unwrap());
+ let server = serve_responses(listener, vec![("402 Payment Required", "{}".to_owned())]);
+ let client = RoutineClient::new(&url, "test-internal-key").unwrap();
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let error = client
+ .run_now(&user, Uuid::from_u128(7))
+ .await
+ .expect_err("402 is not a successful run");
+
+ assert!(error.to_string().contains("allowance"), "{error}");
+ server.await.unwrap();
+}
diff --git a/crates/soup/src/inbound/toolset/list_entities.rs b/crates/soup/src/inbound/toolset/list_entities.rs
index 50f860dfa2..7038bd5292 100644
--- a/crates/soup/src/inbound/toolset/list_entities.rs
+++ b/crates/soup/src/inbound/toolset/list_entities.rs
@@ -403,6 +403,13 @@ pub struct ListEntities {
#[serde(default)]
pub include_types: Option<Vec<ItemType>>,
+ /// Restrict results to the user's favorites.
+ #[schemars(
+ description = "Only return items the user has favorited (starred). Use for requests like \"my favorites\" or \"what have I starred\". Combine with includeTypes and the other filters as usual. Favorite or unfavorite an item with SetFavorite."
+ )]
+ #[serde(default)]
+ pub favorites_only: bool,
+
/// Sort order for returned items.
#[schemars(
description = "How to sort results: recently_viewed, recently_updated (default to this), or recently_created. Use recently_updated for updated_at-style soup results."
@@ -550,7 +557,7 @@ impl ListEntities {
};
let ast = EntityFilterAst {
- favorites_only: None,
+ favorites_only: self.favorites_only.then_some(true),
calendar_event_filter: None,
document_filter: self.document_filter.clone(),
project_filter: self.project_filter.clone(),
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 7e4dac3b27..0866e0f505 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -100,6 +100,19 @@ mutations refresh the project views.
Deleting a project shows its result without a link to the deleted project.
Failed project deletions show `Not deleted`.
+## Acting on items
+
+The assistant can take the same item actions as the app's menus. Messages
+and comments: edit, delete, or react to channel messages; edit or delete
+document comments; open a DM. Items: move to trash, duplicate, rename, change
+sharing, favorite, and mute or snooze notifications. Also: create CRM companies
+and contacts, rename or delete calls, create skills, and run or delete routines.
+Edits and deletes act as the message or comment's author, so the assistant
+changes its own messages as itself and the user's as the user. Reactions are
+always the user's. Each row names the item with a chip that opens it; edit and
+sharing rows expand to show the new text or settings. Verify with throwaway
+items, since these mutate real data.
+
## Phones with new agents enabled
With `enable-chat-v3-agents`, **Agents** opens the new conversation list on phones,
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 7bc176cba8..0d60907940 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -260,17 +260,21 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
PgGithubPullRequestRepo::new(pool.clone()),
);
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- ),
- crm::domain::service::NoOpCrmService,
- github_pull_request_service,
- ));
+ let favorites_service = ai_tools::build_favorites_service(pool.clone());
+ let soup_service = Arc::new(
+ SoupImpl::new(
+ PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
+ frecency_service,
+ ReadonlyEmailPreviewAdapter(email_service),
+ channels_service,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
+ crm::domain::service::NoOpCrmService,
+ github_pull_request_service,
+ )
+ .with_favorites(favorites_service.clone()),
+ );
let ingress_queue = SqsQueue::new(
aws_sdk_sqs::Client::from_conf(sqs_config.clone()),
@@ -519,6 +523,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(pool.clone(), true),
notification_tool_context: notification_tool_context.clone(),
+ item_notification_preference_tool_context:
+ ai_tools::build_item_notification_preference_tool_context(pool.clone()),
databases_tool_context,
forms_tool_context,
databases_sql_tool_context,
@@ -541,6 +547,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
)
.expect("valid test coding agent context"),
project_tool_context,
+ favorites_tool_context: ai_tools::build_favorites_tool_context(
+ favorites_service,
+ entity_access_service.clone(),
+ ),
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()),
diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rs
index 392bb76563..496e40dc77 100644
--- a/services/document_cognition_service/src/server.rs
+++ b/services/document_cognition_service/src/server.rs
@@ -257,15 +257,19 @@ pub async fn run() -> anyhow::Result<()> {
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
PgGithubPullRequestRepo::new(db.clone()),
);
- let soup_service = Arc::new(soup::domain::service::SoupImpl::new(
- soup::outbound::pg_soup_repo::PgSoupRepo::new(ReadOnlyPool(db.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
- crm::domain::service::NoOpCrmService,
- github_pull_request_service,
- ));
+ let favorites_service = ai_tools::build_favorites_service(db.clone());
+ let soup_service = Arc::new(
+ soup::domain::service::SoupImpl::new(
+ soup::outbound::pg_soup_repo::PgSoupRepo::new(ReadOnlyPool(db.clone())),
+ frecency_service,
+ ReadonlyEmailPreviewAdapter(email_service),
+ channels_service,
+ CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
+ crm::domain::service::NoOpCrmService,
+ github_pull_request_service,
+ )
+ .with_favorites(favorites_service.clone()),
+ );
tracing::info!("initialized soup service");
@@ -760,6 +764,8 @@ pub async fn run() -> anyhow::Result<()> {
.unwrap_or(false),
),
notification_tool_context: notification_tool_context.clone(),
+ item_notification_preference_tool_context:
+ ai_tools::build_item_notification_preference_tool_context(db.clone()),
databases_tool_context,
forms_tool_context,
databases_sql_tool_context,
@@ -780,6 +786,10 @@ pub async fn run() -> anyhow::Result<()> {
internal_api_key.clone(),
)?,
project_tool_context,
+ favorites_tool_context: ai_tools::build_favorites_tool_context(
+ favorites_service,
+ entity_access_service.clone(),
+ ),
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()),
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 8422a13306..d31e11f988 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -205,17 +205,21 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
PgGithubPullRequestRepo::new(db.clone()),
);
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),
- ),
- crm::domain::service::NoOpCrmService,
- github_pull_request_service,
- ));
+ let favorites_service = ai_tools::build_favorites_service(db.clone());
+ let soup_service = Arc::new(
+ SoupImpl::new(
+ PgSoupRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
+ frecency_service,
+ ReadonlyEmailPreviewAdapter(email_service),
+ channels_service,
+ call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),
+ ),
+ crm::domain::service::NoOpCrmService,
+ github_pull_request_service,
+ )
+ .with_favorites(favorites_service.clone()),
+ );
let s3_client = macro_aws_config::s3_client().await;
let document_files = documents::outbound::s3_document_files::S3DocumentFiles::new(
@@ -559,6 +563,8 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
.unwrap_or(false),
),
notification_tool_context,
+ item_notification_preference_tool_context:
+ ai_tools::build_item_notification_preference_tool_context(db.clone()),
databases_tool_context,
forms_tool_context,
databases_sql_tool_context,
@@ -577,6 +583,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
config.internal_api_key.to_string(),
)?,
project_tool_context,
+ favorites_tool_context: ai_tools::build_favorites_tool_context(
+ favorites_service,
+ entity_access_service.clone(),
+ ),
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()),