Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: channel create, rename, and member AI tools (#5919)
teo2f8d48cef77a
diff --git a/apps/docs/AI/mcp/tools/create-channel.mdx b/apps/docs/AI/mcp/tools/create-channel.mdxnew file mode 100644index 0000000000..23416827a1--- /dev/null+++ b/apps/docs/AI/mcp/tools/create-channel.mdx@@ -0,0 +1,16 @@+---+title: CreateChannel+description: "Create a private or team channel and add its first members. Use `private` for an invite-only channel and `team` for a channel owned by the current user's team. Do not use this for a direct message — those are created separately. Team id is resolved from the current user; do not invent one. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Creating a team channel when the user has no team fails; create a private channel instead. Creating a team channel with no participants adds the current user so the channel is valid. Use only when the user asks to create a channel."+---++# CreateChannel++Create a private or team channel and add its first members. Use `private` for an invite-only channel and `team` for a channel owned by the current user's team. Do not use this for a direct message — those are created separately. Team id is resolved from the current user; do not invent one. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Creating a team channel when the user has no team fails; create a private channel instead. Creating a team channel with no participants adds the current user so the channel is valid. Use only when the user asks to create a channel.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `name` | string | Yes | Display name for the new channel. |+| `channelType` | `"private"` \| `"team"` | Yes | Channel types an agent may create. |+| `participants` | string[] | No | People to add, as `macro\|<email>` ids or bare emails. Defaults to none. A team channel with an empty list adds the current user. |diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 4317383080..17d8fdf388 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -15,6 +15,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ContentSearch](/AI/mcp/tools/content-search)- [CreateBot](/AI/mcp/tools/create-bot)- [CreateCalendarEvent](/AI/mcp/tools/create-calendar-event)+- [CreateChannel](/AI/mcp/tools/create-channel)- [CreateDocument](/AI/mcp/tools/create-document)- [CreateImportEntity](/AI/mcp/tools/create-import-entity)- [CreateProject](/AI/mcp/tools/create-project)@@ -49,6 +50,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ListTeamMembers](/AI/mcp/tools/list-team-members)- [LoadTools](/AI/mcp/tools/load-tools)- [ManageBotChannelAccess](/AI/mcp/tools/manage-bot-channel-access)+- [ManageChannelParticipants](/AI/mcp/tools/manage-channel-participants)- [MarkNotificationsDone](/AI/mcp/tools/mark-notifications-done)- [MarkNotificationsSeen](/AI/mcp/tools/mark-notifications-seen)- [MoveToProject](/AI/mcp/tools/move-to-project)@@ -63,6 +65,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadMetadata](/AI/mcp/tools/read-metadata)- [ReadProject](/AI/mcp/tools/read-project)- [ReadThread](/AI/mcp/tools/read-thread)+- [RenameChannel](/AI/mcp/tools/rename-channel)- [RenameDocument](/AI/mcp/tools/rename-document)- [SearchSkills](/AI/mcp/tools/search-skills)- [SearchTools](/AI/mcp/tools/search-tools)diff --git a/apps/docs/AI/mcp/tools/manage-channel-participants.mdx b/apps/docs/AI/mcp/tools/manage-channel-participants.mdxnew file mode 100644index 0000000000..1f8df09d99--- /dev/null+++ b/apps/docs/AI/mcp/tools/manage-channel-participants.mdx@@ -0,0 +1,16 @@+---+title: ManageChannelParticipants+description: "Add or remove members of an existing channel. Requires the current user to be a channel member. Direct-message channels cannot change membership. The channel owner cannot be removed. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Use `add` to invite people and `remove` to take them out. Use only when the user asks to change who is in a channel."+---++# ManageChannelParticipants++Add or remove members of an existing channel. Requires the current user to be a channel member. Direct-message channels cannot change membership. The channel owner cannot be removed. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Use `add` to invite people and `remove` to take them out. Use only when the user asks to change who is in a channel.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `channelId` | string | Yes | Channel id whose membership should change. |+| `action` | `"add"` \| `"remove"` | Yes | Membership change to apply. |+| `participants` | string[] | Yes | People to add or remove, as `macro\|<email>` ids or bare emails. Must not be empty. |diff --git a/apps/docs/AI/mcp/tools/rename-channel.mdx b/apps/docs/AI/mcp/tools/rename-channel.mdxnew file mode 100644index 0000000000..7e11e03296--- /dev/null+++ b/apps/docs/AI/mcp/tools/rename-channel.mdx@@ -0,0 +1,15 @@+---+title: RenameChannel+description: "Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."+---++# RenameChannel++Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `channelId` | string | Yes | Channel id to rename. |+| `name` | string | Yes | New display name for the channel. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex ed9cbfb6dd..6141f8ab19 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -6,6 +6,7 @@"AI/mcp/tools/content-search","AI/mcp/tools/create-bot","AI/mcp/tools/create-calendar-event",+ "AI/mcp/tools/create-channel","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-project",@@ -40,6 +41,7 @@"AI/mcp/tools/list-team-members","AI/mcp/tools/load-tools","AI/mcp/tools/manage-bot-channel-access",+ "AI/mcp/tools/manage-channel-participants","AI/mcp/tools/mark-notifications-done","AI/mcp/tools/mark-notifications-seen","AI/mcp/tools/move-to-project",@@ -54,6 +56,7 @@"AI/mcp/tools/read-metadata","AI/mcp/tools/read-project","AI/mcp/tools/read-thread",+ "AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 44f0e363f3..60d0b528f5 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -76,6 +76,7 @@"AI/mcp/tools/content-search","AI/mcp/tools/create-bot","AI/mcp/tools/create-calendar-event",+ "AI/mcp/tools/create-channel","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-project",@@ -110,6 +111,7 @@"AI/mcp/tools/list-team-members","AI/mcp/tools/load-tools","AI/mcp/tools/manage-bot-channel-access",+ "AI/mcp/tools/manage-channel-participants","AI/mcp/tools/mark-notifications-done","AI/mcp/tools/mark-notifications-seen","AI/mcp/tools/move-to-project",@@ -124,6 +126,7 @@"AI/mcp/tools/read-metadata","AI/mcp/tools/read-project","AI/mcp/tools/read-thread",+ "AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools",diff --git a/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx b/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsxnew file mode 100644index 0000000000..9465318676--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx@@ -0,0 +1,203 @@+import { ItemPreview } from '@core/component/ItemPreview';+import Hash from '@phosphor-icons/core/regular/hash.svg';+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';+import Users from '@phosphor-icons/core/regular/users.svg';+import { createSignal, For, Show, Suspense } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type Detail = {+ label: string;+ value?: string | null;+};++function DetailPanel(props: { details: Detail[]; summary?: string }) {+ const details = () => props.details.filter((detail) => detail.value != null);++ return (+ <div class="rounded-lg border border-edge-muted bg-ink/[0.02] p-3">+ <Show when={props.summary}>+ <p class="mb-2 text-xs text-ink-muted">{props.summary}</p>+ </Show>+ <dl class="flex flex-col gap-2">+ <For each={details()}>+ {(detail) => (+ <div class="grid grid-cols-[7rem_minmax(0,1fr)] gap-2 text-xs">+ <dt class="text-ink-extra-muted">{detail.label}</dt>+ <dd class="min-w-0 break-all text-ink">{detail.value}</dd>+ </div>+ )}+ </For>+ </dl>+ </div>+ );+}++function ChannelPreview(props: { channelId: string }) {+ return (+ <Suspense>+ <ItemPreview+ class="inline-flex align-middle ring-0"+ id={props.channelId}+ type="channel"+ />+ </Suspense>+ );+}++function displayParticipant(id: string) {+ return id.startsWith('macro|') ? id.slice('macro|'.length) : id;+}++const createChannelHandler = createToolRenderer({+ name: 'CreateChannel',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const response = () => ctx.response?.data;+ const participants = () => response()?.participants ?? [];++ return (+ <BaseTool+ icon={Hash}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() && response() ? (+ <div class="flex flex-col gap-2">+ <DetailPanel+ summary={response()!.summary}+ details={[+ { label: 'Type', value: response()!.channelType },+ {+ label: 'Members',+ value:+ participants().length > 0+ ? participants().map(displayParticipant).join(', ')+ : 'Owner only',+ },+ ]}+ />+ </div>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span class="min-w-0 truncate">+ {ctx.response ? 'Created channel' : 'Create channel'}{' '}+ <Show+ when={response()}+ fallback={<span class="text-ink">{ctx.tool.data.name}</span>}+ >+ {(created) => <ChannelPreview channelId={created().channelId} />}+ </Show>+ </span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!response()}+ status={+ ctx.response+ ? ctx.tool.data.channelType === 'team'+ ? 'Team'+ : 'Private'+ : undefined+ }+ />+ </div>+ </BaseTool>+ );+ },+});++const renameChannelHandler = createToolRenderer({+ name: 'RenameChannel',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const response = () => ctx.response?.data;++ return (+ <BaseTool+ icon={PencilSimple}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() && response() ? (+ <DetailPanel+ summary={response()!.summary}+ details={[+ { label: 'Previous', value: response()!.previousName },+ { label: 'Name', value: response()!.name },+ ]}+ />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span class="min-w-0 truncate">+ {ctx.response ? 'Renamed' : 'Rename'}{' '}+ <ChannelPreview channelId={ctx.tool.data.channelId} /> to{' '}+ <span class="text-ink">{ctx.tool.data.name}</span>+ </span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!response()}+ status={ctx.response ? 'Renamed' : undefined}+ />+ </div>+ </BaseTool>+ );+ },+});++const manageChannelParticipantsHandler = createToolRenderer({+ name: 'ManageChannelParticipants',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const response = () => ctx.response?.data;+ const adding = () => ctx.tool.data.action === 'add';+ const participants = () =>+ response()?.participants ?? ctx.tool.data.participants;++ return (+ <BaseTool+ icon={Users}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() && response() ? (+ <DetailPanel+ summary={response()!.summary}+ details={[+ {+ label: adding() ? 'Added' : 'Removed',+ value: participants().map(displayParticipant).join(', '),+ },+ ]}+ />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span class="min-w-0 truncate">+ {adding() ? 'Add members to' : 'Remove members from'}{' '}+ <ChannelPreview channelId={ctx.tool.data.channelId} />+ </span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!response()}+ status={ctx.response ? (adding() ? 'Added' : 'Removed') : undefined}+ />+ </div>+ </BaseTool>+ );+ },+});++export {+ createChannelHandler,+ manageChannelParticipantsHandler,+ renameChannelHandler,+};diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex b6781a6bc8..cb37c753dc 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@@ -21,6 +21,11 @@ import {listCalendarsHandler,updateCalendarEventHandler,} from './CalendarTools';+import {+ createChannelHandler,+ manageChannelParticipantsHandler,+ renameChannelHandler,+} from './ChannelMutations';import { createDocumentHandler } from './CreateDocument';import { createProjectHandler } from './CreateProject';import { createTagHandler } from './CreateTag';@@ -94,6 +99,7 @@ import { webSearchHandler } from './WebSearch';const toolHandlers: ToolHandlerMap<RenderContext> = {ConfigureBot: configureBotHandler,+ CreateChannel: createChannelHandler,CreateBot: createBotHandler,DeleteBot: deleteBotHandler,GetBotWebhooks: getBotWebhooksHandler,@@ -116,6 +122,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ListInboxes: listInboxesHandler,ListLabels: listLabelsHandler,ListSkills: listSkillsHandler,+ ManageChannelParticipants: manageChannelParticipantsHandler,ListNotifications: listNotificationsHandler,ListReminders: listRemindersHandler,ListTags: listTagsHandler,@@ -147,6 +154,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadContent: readContentHandler,ReadMetadata: readMetadataHandler,ReadProject: readProjectHandler,+ RenameChannel: renameChannelHandler,RenameDocument: renameDocumentHandler,SearchSkills: searchSkillsHandler,SearchTools: searchToolsHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex f94be2647a..4d4e1f5f8d 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@@ -979,6 +979,54 @@ export const UserToolResponseForToolCalendarEvent = z}});+export const CreateChannel = z.object({+ name: z.string(),+ channelType: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('private'), 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',+ });+ }+ }),+ participants: z.array(z.string()).optional(),+});++export const CreateChannelResponse = z.object({+ channelId: z.string().uuid(),+ name: z.string(),+ channelType: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('private'), 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',+ });+ }+ }),+ participants: z.array(z.string()),+ summary: z.string(),+});+export const CreateDocument = z.object({documentName: z.string(),fileContent: z.string(),@@ -2543,6 +2591,53 @@ export const ManageBotChannelAccessResponse = z.object({summary: z.string(),});+export const ManageChannelParticipants = z.object({+ channelId: z.string().uuid(),+ 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',+ });+ }+ }),+ participants: z.array(z.string()),+});++export const ManageChannelParticipantsResponse = z.object({+ channelId: z.string().uuid(),+ 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',+ });+ }+ }),+ participants: z.array(z.string()),+ summary: z.string(),+});+export const MarkNotificationsDone = z.object({notificationIds: z.array(z.string().uuid()),done: z.boolean(),@@ -3850,6 +3945,18 @@ export const ReadProjectResponse = z.object({),});+export const RenameChannel = z.object({+ channelId: z.string().uuid(),+ name: z.string(),+});++export const RenameChannelResponse = z.object({+ channelId: z.string().uuid(),+ name: z.string(),+ previousName: z.union([z.string(), z.null()]).optional(),+ summary: z.string(),+});+export const RenameDocument = z.object({documentId: z.string().uuid(),documentName: z.string(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex 232dcc0018..5f052399ff 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@@ -29,6 +29,10 @@ type ToolParserMap = {call: types.CreateCalendarEvent;response: types.UserToolResponseForToolCalendarEvent;};+ CreateChannel: {+ call: types.CreateChannel;+ response: types.CreateChannelResponse;+ };CreateDocument: {call: types.CreateDocument;response: types.CreateDocumentResponse;@@ -126,6 +130,10 @@ type ToolParserMap = {call: types.ManageBotChannelAccess;response: types.ManageBotChannelAccessResponse;};+ ManageChannelParticipants: {+ call: types.ManageChannelParticipants;+ response: types.ManageChannelParticipantsResponse;+ };MarkNotificationsDone: {call: types.MarkNotificationsDone;response: types.MarkNotificationsResponse;@@ -167,6 +175,10 @@ type ToolParserMap = {};ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };ReadThread: { call: types.ReadThread; response: types.ReadResponse };+ RenameChannel: {+ call: types.RenameChannel;+ response: types.RenameChannelResponse;+ };RenameDocument: {call: types.RenameDocument;response: types.RenameDocumentResponse;@@ -236,6 +248,10 @@ const toolParserMap = {call: schemas.CreateCalendarEvent,response: schemas.UserToolResponseForToolCalendarEvent,},+ CreateChannel: {+ call: schemas.CreateChannel,+ response: schemas.CreateChannelResponse,+ },CreateDocument: {call: schemas.CreateDocument,response: schemas.CreateDocumentResponse,@@ -348,6 +364,10 @@ const toolParserMap = {call: schemas.ManageBotChannelAccess,response: schemas.ManageBotChannelAccessResponse,},+ ManageChannelParticipants: {+ call: schemas.ManageChannelParticipants,+ response: schemas.ManageChannelParticipantsResponse,+ },MarkNotificationsDone: {call: schemas.MarkNotificationsDone,response: schemas.MarkNotificationsResponse,@@ -398,6 +418,10 @@ const toolParserMap = {response: schemas.ReadProjectResponse,},ReadThread: { call: schemas.ReadThread, response: schemas.ReadResponse },+ RenameChannel: {+ call: schemas.RenameChannel,+ response: schemas.RenameChannelResponse,+ },RenameDocument: {call: schemas.RenameDocument,response: schemas.RenameDocumentResponse,@@ -481,6 +505,10 @@ type ToolDataMap = {call: types.CreateCalendarEvent;response: types.UserToolResponseForToolCalendarEvent;};+ CreateChannel: {+ call: types.CreateChannel;+ response: types.CreateChannelResponse;+ };CreateDocument: {call: types.CreateDocument;response: types.CreateDocumentResponse;@@ -578,6 +606,10 @@ type ToolDataMap = {call: types.ManageBotChannelAccess;response: types.ManageBotChannelAccessResponse;};+ ManageChannelParticipants: {+ call: types.ManageChannelParticipants;+ response: types.ManageChannelParticipantsResponse;+ };MarkNotificationsDone: {call: types.MarkNotificationsDone;response: types.MarkNotificationsResponse;@@ -619,6 +651,10 @@ type ToolDataMap = {};ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };ReadThread: { call: types.ReadThread; response: types.ReadResponse };+ RenameChannel: {+ call: types.RenameChannel;+ response: types.RenameChannelResponse;+ };RenameDocument: {call: types.RenameDocument;response: types.RenameDocumentResponse;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex c795b56ec6..cb217322b2 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@@ -208,6 +208,10 @@ export type UserToolResponseForToolCalendarEvent =| {UserAction: ToolCalendarEvent;};+/**+ * Channel types an agent may create.+ */+export type NewChannelType = 'private' | 'team';/*** External systems items can be imported from.*/@@ -510,6 +514,10 @@ export type NotificationEntityType =* Channel-access change to apply to a bot.*/export type BotChannelAccessAction = 'grant' | 'revoke';+/**+ * Membership change to apply.+ */+export type ParticipantAction = 'add' | 'remove';/*** The kind of entity to move.*/@@ -1939,6 +1947,42 @@ export interface ToolEventAttendee {*/isOptional: boolean;}+/**+ * Create a private or team channel and add its first members. Use `private` for an invite-only channel and `team` for a channel owned by the current user's team. Do not use this for a direct message — those are created separately. Team id is resolved from the current user; do not invent one. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Creating a team channel when the user has no team fails; create a private channel instead. Creating a team channel with no participants adds the current user so the channel is valid. Use only when the user asks to create a channel.+ */+export interface CreateChannel {+ /**+ * Display name for the new channel.+ */+ name: string;+ channelType: NewChannelType;+ /**+ * People to add, as `macro|<email>` ids or bare emails. Defaults to none. A team channel with an empty list adds the current user.+ */+ participants?: string[];+}+/**+ * Response from [`CreateChannel`].+ */+export interface CreateChannelResponse {+ /**+ * Created channel id.+ */+ channelId: string;+ /**+ * Trimmed channel name.+ */+ name: string;+ channelType: NewChannelType;+ /**+ * Canonical participant ids sent with the create request.+ */+ participants: string[];+ /**+ * Human-readable result summary.+ */+ summary: string;+}/*** Create a plaintext document.*/@@ -3661,6 +3705,38 @@ export interface ManageBotChannelAccessResponse {*/summary: string;}+/**+ * Add or remove members of an existing channel. Requires the current user to be a channel member. Direct-message channels cannot change membership. The channel owner cannot be removed. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Use `add` to invite people and `remove` to take them out. Use only when the user asks to change who is in a channel.+ */+export interface ManageChannelParticipants {+ /**+ * Channel id whose membership should change.+ */+ channelId: string;+ action: ParticipantAction;+ /**+ * People to add or remove, as `macro|<email>` ids or bare emails. Must not be empty.+ */+ participants: string[];+}+/**+ * Response from [`ManageChannelParticipants`].+ */+export interface ManageChannelParticipantsResponse {+ /**+ * Channel whose membership changed.+ */+ channelId: string;+ action: ParticipantAction;+ /**+ * Canonical participant ids that were requested.+ */+ participants: string[];+ /**+ * Human-readable result summary.+ */+ summary: string;+}/*** Mark one or more notifications as done or not done for the current user. Use this when the user has completed the action associated with a notification.*/@@ -4670,6 +4746,40 @@ export interface ProjectItem {*/updatedAt?: string | null;}+/**+ * Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel.+ */+export interface RenameChannel {+ /**+ * Channel id to rename.+ */+ channelId: string;+ /**+ * New display name for the channel.+ */+ name: string;+}+/**+ * Response from [`RenameChannel`].+ */+export interface RenameChannelResponse {+ /**+ * Channel that was renamed.+ */+ channelId: string;+ /**+ * New trimmed name.+ */+ name: string;+ /**+ * Previous display name when it could be read.+ */+ previousName?: string | null;+ /**+ * Human-readable result summary.+ */+ summary: string;+}/*** Rename a document. Requires edit access to the document.*/diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rsindex fe1d09d934..55dde583ed 100644--- a/crates/channels/src/inbound/toolset.rs+++ b/crates/channels/src/inbound/toolset.rs@@ -1,8 +1,11 @@-//! AI tools for reading channel messages and threads.+//! AI tools for reading channel messages and mutating channel membership.+mod create_channel;+mod manage_channel_participants;mod read_channel_message_context;mod read_channel_messages;mod read_channel_thread;+mod rename_channel;mod send_channel_message;mod types;@@ -10,13 +13,21 @@ mod types;mod test;use crate::{- domain::ports::ChannelService, inbound::toolset::send_channel_message::SendChannelMessage,+ domain::{models::Sender, ports::ChannelMutationErr, ports::ChannelService},+ inbound::toolset::{+ create_channel::CreateChannel, manage_channel_participants::ManageChannelParticipants,+ rename_channel::RenameChannel, send_channel_message::SendChannelMessage,+ },};use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};use entity_access::domain::{- models::{AccessError, AccessLevel, EntityType},+ models::{+ AccessError, AccessLevel, AdminParticipantRole, EntityAccessReceipt, EntityType,+ MemberParticipantRole, RequiredPermission,+ },ports::EntityAccessService,};+use macro_user_id::user_id::MacroUserIdStr;use std::sync::Arc;use uuid::Uuid;@@ -81,6 +92,49 @@ where.map(|_| ()).map_err(channel_access_error)}++ /// Mint the same admin receipt HTTP uses before renaming a channel.+ pub async fn require_channel_admin(+ &self,+ request_context: &RequestContext,+ channel_id: Uuid,+ ) -> Result<EntityAccessReceipt<AdminParticipantRole>, ToolCallError> {+ self.channel_receipt(request_context, channel_id, ChannelReceiptKind::Admin)+ .await+ }++ /// Mint the same member receipt HTTP uses before changing participants.+ pub async fn require_channel_member_role(+ &self,+ request_context: &RequestContext,+ channel_id: Uuid,+ ) -> Result<EntityAccessReceipt<MemberParticipantRole>, ToolCallError> {+ self.channel_receipt(request_context, channel_id, ChannelReceiptKind::Member)+ .await+ }++ async fn channel_receipt<P: RequiredPermission>(+ &self,+ request_context: &RequestContext,+ channel_id: Uuid,+ kind: ChannelReceiptKind,+ ) -> Result<EntityAccessReceipt<P>, ToolCallError> {+ self.entity_access_service+ .generate_entity_access_receipt::<P>(+ &request_context.user_id,+ None,+ &channel_id.to_string(),+ EntityType::Channel,+ )+ .await+ .map_err(|error| channel_receipt_error(kind, error))+ }+}++#[derive(Clone, Copy)]+enum ChannelReceiptKind {+ Admin,+ Member,}fn channel_access_error(err: AccessError) -> ToolCallError {@@ -101,6 +155,130 @@ fn channel_access_error(err: AccessError) -> ToolCallError {}}+fn channel_receipt_error(kind: ChannelReceiptKind, err: AccessError) -> ToolCallError {+ let description = match (kind, &err) {+ (+ ChannelReceiptKind::Admin,+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),+ ) => "you need channel admin access to rename this channel",+ (+ ChannelReceiptKind::Member,+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),+ ) => "you must be a member of the channel to change its participants",+ (_, AccessError::NotFound(_)) => "channel not found",+ (_, AccessError::BadRequest(_)) => "invalid channel id",+ (ChannelReceiptKind::Admin, AccessError::Unavailable(_) | AccessError::Internal(_)) => {+ "failed to verify channel admin access"+ }+ (ChannelReceiptKind::Member, AccessError::Unavailable(_) | AccessError::Internal(_)) => {+ "failed to verify channel membership"+ }+ };++ ToolCallError {+ description: description.to_string(),+ internal_error: err.into(),+ }+}++fn user_sender<P: RequiredPermission>(+ receipt: &EntityAccessReceipt<P>,+) -> Result<Sender, ToolCallError> {+ receipt+ .get_authenticated_user()+ .cloned()+ .map(Sender::new_from_user)+ .map_err(|error| ToolCallError {+ description: "authenticated user required".to_string(),+ internal_error: error.into(),+ })+}++fn channel_mutation_error(action: &'static str, err: ChannelMutationErr) -> ToolCallError {+ let description = match &err {+ ChannelMutationErr::BadRequest(message)+ | ChannelMutationErr::Unauthorized(message)+ | ChannelMutationErr::Forbidden(message)+ | ChannelMutationErr::NotFound(message) => message.clone(),+ ChannelMutationErr::Repo(_)+ | ChannelMutationErr::Gateway(_)+ | ChannelMutationErr::Notification(_)+ | ChannelMutationErr::Contacts(_) => format!("failed to {action}"),+ };++ ToolCallError {+ description,+ internal_error: err.into(),+ }+}++const MAX_CHANNEL_NAME_CHARS: usize = 255;++fn channel_name(name: &str) -> Result<String, ToolCallError> {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Err(ToolCallError {+ description: "channel name must not be empty".to_string(),+ internal_error: anyhow::anyhow!("empty channel name"),+ });+ }+ if trimmed.chars().count() > MAX_CHANNEL_NAME_CHARS {+ return Err(ToolCallError {+ description: format!(+ "channel name must be {MAX_CHANNEL_NAME_CHARS} characters or fewer"+ ),+ internal_error: anyhow::anyhow!("channel name exceeds {MAX_CHANNEL_NAME_CHARS} chars"),+ });+ }+ Ok(trimmed.to_string())+}++fn parse_participants(entries: &[String]) -> Result<Vec<MacroUserIdStr<'static>>, ToolCallError> {+ let mut participants = Vec::new();+ let mut seen = std::collections::HashSet::new();+ let mut invalid = Vec::new();++ for (index, raw) in entries.iter().enumerate() {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ invalid.push(format!("participants[{index}] is empty"));+ continue;+ }+ match parse_participant(trimmed) {+ Ok(user_id) => {+ if seen.insert(user_id.as_ref().to_string()) {+ participants.push(user_id);+ }+ }+ Err(()) => invalid.push(format!(+ "participants[{index}] `{trimmed}` is not a user id (`macro|<email>`) or email"+ )),+ }+ }++ if !invalid.is_empty() {+ return Err(ToolCallError {+ description: invalid.join("; "),+ internal_error: anyhow::anyhow!("invalid channel participant ids"),+ });+ }++ Ok(participants)+}++fn parse_participant(raw: &str) -> Result<MacroUserIdStr<'static>, ()> {+ MacroUserIdStr::try_from(raw.to_string())+ .or_else(|_| MacroUserIdStr::try_from_email(raw))+ .map_err(|_| ())+}++fn participant_id_strings(participants: &[MacroUserIdStr<'static>]) -> Vec<String> {+ participants+ .iter()+ .map(|user_id| user_id.as_ref().to_string())+ .collect()+}+/// Create the channel AI toolset.pub fn channel_toolset<Svc, AccessSvc>() -> AsyncToolCollection<ChannelToolContext<Svc, AccessSvc>>where@@ -112,4 +290,7 @@ where.add_tool::<ReadChannelMessageContext, ChannelToolContext<Svc, AccessSvc>>().add_tool::<ReadChannelThread, ChannelToolContext<Svc, AccessSvc>>().add_tool::<SendChannelMessage, ChannelToolContext<Svc, AccessSvc>>()+ .add_tool::<CreateChannel, ChannelToolContext<Svc, AccessSvc>>()+ .add_tool::<RenameChannel, ChannelToolContext<Svc, AccessSvc>>()+ .add_tool::<ManageChannelParticipants, ChannelToolContext<Svc, AccessSvc>>()}diff --git a/crates/channels/src/inbound/toolset/create_channel.rs b/crates/channels/src/inbound/toolset/create_channel.rsnew file mode 100644index 0000000000..ac4d264820--- /dev/null+++ b/crates/channels/src/inbound/toolset/create_channel.rs@@ -0,0 +1,159 @@+use super::{+ ChannelToolContext, channel_mutation_error, channel_name, parse_participants,+ participant_id_strings,+};+use crate::domain::models::{ChannelType, CreateChannelRequest, Sender};+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 std::collections::HashSet;+use uuid::Uuid;++/// Channel types an agent may create.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub enum NewChannelType {+ /// Invite-only channel with no team.+ Private,+ /// Channel owned by the caller's current team.+ Team,+}++impl NewChannelType {+ fn to_domain(self) -> ChannelType {+ match self {+ Self::Private => ChannelType::Private,+ Self::Team => ChannelType::Team,+ }+ }+}++/// Response from [`CreateChannel`].+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateChannelResponse {+ /// Created channel id.+ pub channel_id: Uuid,+ /// Trimmed channel name.+ pub name: String,+ /// Channel type that was created.+ pub channel_type: NewChannelType,+ /// Canonical participant ids sent with the create request.+ pub participants: Vec<String>,+ /// Human-readable result summary.+ pub summary: String,+}++/// Create a private or team channel and add its first members.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "CreateChannel",+ description = "Create a private or team channel and add its first members. Use `private` for an invite-only channel and `team` for a channel owned by the current user's team. Do not use this for a direct message — those are created separately. Team id is resolved from the current user; do not invent one. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Creating a team channel when the user has no team fails; create a private channel instead. Creating a team channel with no participants adds the current user so the channel is valid. Use only when the user asks to create a channel."+)]+pub struct CreateChannel {+ /// Channel display name.+ #[schemars(description = "Display name for the new channel.")]+ pub name: String,+ /// Private or team.+ #[schemars(+ description = "Use `private` for an invite-only channel or `team` for the current user's team."+ )]+ pub channel_type: NewChannelType,+ /// First members, excluding implicit owner insertion performed by the domain.+ #[schemars(+ description = "People to add, as `macro|<email>` ids or bare emails. Defaults to none. A team channel with an empty list adds the current user."+ )]+ #[serde(default)]+ pub participants: Vec<String>,+}++impl ToolAnnotated for CreateChannel {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create channel");+}++#[async_trait]+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for CreateChannel+where+ Svc: ChannelService,+ AccessSvc: EntityAccessService,+{+ type Output = CreateChannelResponse;++ #[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 name = channel_name(&self.name)?;+ let mut participants = parse_participants(&self.participants)?;+ let team_id = match self.channel_type {+ NewChannelType::Private => None,+ NewChannelType::Team => {+ let team = service_context+ .entity_access_service+ .get_user_team(&request_context.user_id)+ .await+ .map_err(team_lookup_error)?;+ let team = team.ok_or_else(|| ToolCallError {+ description:+ "you are not a member of a team — create a private channel instead"+ .to_string(),+ internal_error: anyhow::anyhow!("create team channel without a team"),+ })?;+ if participants.is_empty() {+ participants.push(request_context.user_id.clone());+ }+ Some(team.team_id)+ }+ };++ let participant_ids = participant_id_strings(&participants);+ let response = service_context+ .service+ .create_channel(+ Sender::new_from_user(request_context.user_id.clone()),+ None,+ CreateChannelRequest {+ name: Some(name.clone()),+ channel_type: self.channel_type.to_domain(),+ team_id,+ auto_join_team: false,+ participants: HashSet::from_iter(participants),+ },+ )+ .await+ .map_err(|error| channel_mutation_error("create the channel", error))?;++ let channel_id = Uuid::parse_str(&response.id).map_err(|error| ToolCallError {+ description: "created channel id was not a valid uuid".to_string(),+ internal_error: error.into(),+ })?;+ let kind = match self.channel_type {+ NewChannelType::Private => "private",+ NewChannelType::Team => "team",+ };++ Ok(CreateChannelResponse {+ channel_id,+ name: name.clone(),+ channel_type: self.channel_type,+ participants: participant_ids,+ summary: format!("Created the {kind} channel `{name}`."),+ })+ }+}++fn team_lookup_error(error: entity_access::domain::models::AccessError) -> ToolCallError {+ ToolCallError {+ description: "failed to resolve the current user's team".to_string(),+ internal_error: error.into(),+ }+}diff --git a/crates/channels/src/inbound/toolset/manage_channel_participants.rs b/crates/channels/src/inbound/toolset/manage_channel_participants.rsnew file mode 100644index 0000000000..e13a5c37d2--- /dev/null+++ b/crates/channels/src/inbound/toolset/manage_channel_participants.rs@@ -0,0 +1,143 @@+use super::{+ ChannelToolContext, channel_mutation_error, parse_participants, participant_id_strings,+ user_sender,+};+use crate::domain::models::{AddParticipantsRequest, RemoveParticipantsRequest};+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 std::collections::HashSet;+use uuid::Uuid;++/// Membership change to apply.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub enum ParticipantAction {+ /// Add or reactivate members.+ Add,+ /// Remove members.+ Remove,+}++/// Response from [`ManageChannelParticipants`].+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ManageChannelParticipantsResponse {+ /// Channel whose membership changed.+ pub channel_id: Uuid,+ /// Applied membership change.+ pub action: ParticipantAction,+ /// Canonical participant ids that were requested.+ pub participants: Vec<String>,+ /// Human-readable result summary.+ pub summary: String,+}++/// Add or remove people from a channel.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ManageChannelParticipants",+ description = "Add or remove members of an existing channel. Requires the current user to be a channel member. Direct-message channels cannot change membership. The channel owner cannot be removed. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Use `add` to invite people and `remove` to take them out. Use only when the user asks to change who is in a channel."+)]+pub struct ManageChannelParticipants {+ /// Channel to change.+ #[schemars(description = "Channel id whose membership should change.")]+ pub channel_id: Uuid,+ /// Add or remove.+ #[schemars(description = "Use `add` to invite people or `remove` to take them out.")]+ pub action: ParticipantAction,+ /// People to add or remove.+ #[schemars(+ description = "People to add or remove, as `macro|<email>` ids or bare emails. Must not be empty."+ )]+ pub participants: Vec<String>,+}++impl ToolAnnotated for ManageChannelParticipants {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Change channel members");+}++#[async_trait]+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ManageChannelParticipants+where+ Svc: ChannelService,+ AccessSvc: EntityAccessService,+{+ type Output = ManageChannelParticipantsResponse;++ #[tracing::instrument(+ skip_all,+ fields(+ user_id=?request_context.user_id,+ channel_id=%self.channel_id,+ action=?self.action+ ),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ if self.participants.is_empty() {+ return Err(ToolCallError {+ description: "participants must not be empty — pass at least one user id or email"+ .to_string(),+ internal_error: anyhow::anyhow!("empty channel participant list"),+ });+ }++ let participants = parse_participants(&self.participants)?;+ let receipt = service_context+ .require_channel_member_role(&request_context, self.channel_id)+ .await?;+ let actor = user_sender(&receipt)?;+ let participant_ids = participant_id_strings(&participants);++ match self.action {+ ParticipantAction::Add => service_context+ .service+ .add_participants(+ actor,+ self.channel_id,+ AddParticipantsRequest {+ participants: HashSet::from_iter(participants),+ },+ )+ .await+ .map_err(|error| channel_mutation_error("add channel participants", error))?,+ ParticipantAction::Remove => service_context+ .service+ .remove_participants(+ actor,+ self.channel_id,+ RemoveParticipantsRequest {+ participants: participant_ids.clone(),+ },+ )+ .await+ .map_err(|error| channel_mutation_error("remove channel participants", error))?,+ }++ let count = participant_ids.len();+ let noun = if count == 1 { "member" } else { "members" };+ let summary = match self.action {+ ParticipantAction::Add => format!("Added {count} {noun} to the channel."),+ ParticipantAction::Remove => format!("Removed {count} {noun} from the channel."),+ };++ Ok(ManageChannelParticipantsResponse {+ channel_id: self.channel_id,+ action: self.action,+ participants: participant_ids,+ summary,+ })+ }+}diff --git a/crates/channels/src/inbound/toolset/rename_channel.rs b/crates/channels/src/inbound/toolset/rename_channel.rsnew file mode 100644index 0000000000..c47684603d--- /dev/null+++ b/crates/channels/src/inbound/toolset/rename_channel.rs@@ -0,0 +1,103 @@+use super::{ChannelToolContext, channel_mutation_error, channel_name, user_sender};+use crate::domain::models::PatchChannelRequest;+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 [`RenameChannel`].+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RenameChannelResponse {+ /// Channel that was renamed.+ pub channel_id: Uuid,+ /// New trimmed name.+ pub name: String,+ /// Previous display name when it could be read.+ pub previous_name: Option<String>,+ /// Human-readable result summary.+ pub summary: String,+}++/// Rename an existing channel.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "RenameChannel",+ description = "Rename an existing channel. Requires the current user to be a channel admin or owner. Direct-message channels cannot be renamed. Use only when the user asks to rename a channel."+)]+pub struct RenameChannel {+ /// Channel to rename.+ #[schemars(description = "Channel id to rename.")]+ pub channel_id: Uuid,+ /// New display name.+ #[schemars(description = "New display name for the channel.")]+ pub name: String,+}++impl ToolAnnotated for RenameChannel {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Rename channel");+}++#[async_trait]+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for RenameChannel+where+ Svc: ChannelService,+ AccessSvc: EntityAccessService,+{+ type Output = RenameChannelResponse;++ #[tracing::instrument(+ skip_all,+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let name = channel_name(&self.name)?;+ let receipt = service_context+ .require_channel_admin(&request_context, self.channel_id)+ .await?;+ let actor = user_sender(&receipt)?;+ let previous_name = service_context+ .service+ .get_channel_metadata(self.channel_id, request_context.user_id.clone())+ .await+ .ok()+ .map(|metadata| metadata.channel_name);++ service_context+ .service+ .patch_channel(+ actor,+ self.channel_id,+ PatchChannelRequest {+ channel_name: Some(name.clone()),+ convert_to_team_channel: None,+ auto_join_team: None,+ },+ )+ .await+ .map_err(|error| channel_mutation_error("rename the channel", error))?;++ let summary = match previous_name.as_deref() {+ Some(previous) => format!("Renamed the channel from `{previous}` to `{name}`."),+ None => format!("Renamed the channel to `{name}`."),+ };++ Ok(RenameChannelResponse {+ channel_id: self.channel_id,+ name,+ previous_name,+ summary,+ })+ }+}diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rsindex 45795a9206..47f4bc2bc6 100644--- a/crates/channels/src/inbound/toolset/test.rs+++ b/crates/channels/src/inbound/toolset/test.rs@@ -1,5 +1,333 @@-use super::{ReadChannelMessageContext, ReadChannelMessages, ReadChannelThread};-use ai_toolset::schema::generate_validated_input_schema;+use super::{+ ChannelToolContext, ReadChannelMessageContext, ReadChannelMessages, ReadChannelThread,+ channel_mutation_error, channel_name,+ create_channel::{CreateChannel, NewChannelType},+ manage_channel_participants::{ManageChannelParticipants, ParticipantAction},+ parse_participants,+ rename_channel::RenameChannel,+};+use crate::domain::{+ models::{+ AddParticipantsRequest, ChannelMetadata, ChannelType, CreateChannelRequest,+ CreateChannelResponse, PatchChannelRequest, RemoveParticipantsRequest, Sender,+ },+ ports::{ChannelMutationErr, ChannelService},+};+use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, schema::generate_validated_input_schema,+};+use entity_access::domain::{+ models::{+ AccessError, AccessLevel, BotAccessScope, CallChannelInfo, EntityAccessReceipt,+ EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,+ },+ ports::{EntityAccessService, NoOpEntityAccessService},+};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};+use std::sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+};+use uuid::Uuid;++const TEST_USER_ID: &str = "macro|[email protected]";++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(TEST_USER_ID.to_string()).expect("valid macro user id")+}++type CreatedChannelCall = (Sender, Option<i64>, CreateChannelRequest);+type PatchChannelCall = (Sender, Uuid, PatchChannelRequest);+type AddParticipantsCall = (Sender, Uuid, AddParticipantsRequest);+type RemoveParticipantsCall = (Sender, Uuid, RemoveParticipantsRequest);++#[derive(Clone, Default)]+struct ToolTestChannelService {+ created: Arc<Mutex<Option<CreatedChannelCall>>>,+ created_id: Option<Uuid>,+ create_error: Option<String>,+ patches: Arc<Mutex<Vec<PatchChannelCall>>>,+ patch_error: Option<String>,+ adds: Arc<Mutex<Vec<AddParticipantsCall>>>,+ removes: Arc<Mutex<Vec<RemoveParticipantsCall>>>,+ metadata_name: Option<String>,+}++impl ChannelService for ToolTestChannelService {+ async fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ _direction: crate::domain::models::MessagePageDirection,+ _limit: u16,+ _filters: &crate::domain::models::ChannelMessageFilters,+ _notification_user_id: Option<MacroUserIdStr<'static>>,+ ) -> Result<+ crate::domain::ports::ChannelMessagesQueryResult,+ crate::domain::ports::ChannelMessagesErr,+ > {+ unimplemented!("read path unused by mutation tools")+ }++ async fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ _limit: u16,+ _attachment_type: Option<crate::domain::models::ChannelAttachmentType>,+ ) -> Result<+ crate::domain::ports::ChannelAttachmentsPage,+ crate::domain::ports::ChannelMessagesErr,+ > {+ unimplemented!("read path unused by mutation tools")+ }++ async fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> Result<+ Vec<crate::domain::models::ChannelParticipant>,+ crate::domain::ports::ChannelMessagesErr,+ > {+ unimplemented!("read path unused by mutation tools")+ }++ async fn get_channel_metadata(+ &self,+ _channel_id: Uuid,+ _viewer_user_id: MacroUserIdStr<'static>,+ ) -> Result<ChannelMetadata, crate::domain::ports::ChannelMessagesErr> {+ Ok(ChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: self+ .metadata_name+ .clone()+ .unwrap_or_else(|| "Previous".to_string()),+ })+ }++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<+ Vec<crate::domain::models::AttachmentEntityReference>,+ crate::domain::ports::ChannelMessagesErr,+ > {+ unimplemented!("read path unused by mutation tools")+ }++ async fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _limit: u16,+ ) -> Result<+ crate::domain::ports::ChannelMessagesQueryResult,+ crate::domain::ports::ChannelMessagesErr,+ > {+ unimplemented!("read path unused by mutation tools")+ }++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, crate::domain::ports::ChannelMessagesErr>+ {+ unimplemented!("read path unused by mutation tools")+ }++ async fn create_channel(+ &self,+ actor: Sender,+ actor_org_id: Option<i64>,+ req: CreateChannelRequest,+ ) -> Result<CreateChannelResponse, ChannelMutationErr> {+ if let Some(message) = &self.create_error {+ return Err(ChannelMutationErr::BadRequest(message.clone()));+ }+ *self.created.lock().expect("create lock") = Some((actor, actor_org_id, req));+ Ok(CreateChannelResponse {+ id: self.created_id.unwrap_or_else(Uuid::new_v4).to_string(),+ })+ }++ async fn patch_channel(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: PatchChannelRequest,+ ) -> Result<(), ChannelMutationErr> {+ if let Some(message) = &self.patch_error {+ return Err(ChannelMutationErr::BadRequest(message.clone()));+ }+ self.patches+ .lock()+ .expect("patch lock")+ .push((actor, channel_id, req));+ Ok(())+ }++ async fn add_participants(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: AddParticipantsRequest,+ ) -> Result<(), ChannelMutationErr> {+ self.adds+ .lock()+ .expect("add lock")+ .push((actor, channel_id, req));+ Ok(())+ }++ async fn remove_participants(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: RemoveParticipantsRequest,+ ) -> Result<(), ChannelMutationErr> {+ self.removes+ .lock()+ .expect("remove lock")+ .push((actor, channel_id, req));+ Ok(())+ }+}++#[derive(Clone, Copy)]+enum ReceiptFail {+ Unauthorized,+ NotFound,+}++#[derive(Clone)]+struct ToolTestAccessService {+ receipt_error: Option<ReceiptFail>,+ team: Option<UserTeamInfo>,+ receipt_calls: Arc<AtomicUsize>,+}++impl Default for ToolTestAccessService {+ fn default() -> Self {+ Self {+ receipt_error: None,+ team: None,+ receipt_calls: Arc::new(AtomicUsize::new(0)),+ }+ }+}++impl EntityAccessService for ToolTestAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ self.receipt_calls.fetch_add(1, Ordering::SeqCst);+ if let Some(error) = self.receipt_error {+ return Err(match error {+ ReceiptFail::Unauthorized => AccessError::Unauthorized,+ ReceiptFail::NotFound => AccessError::NotFound("missing"),+ });+ }+ Ok(EntityAccessReceipt::dangerously_assert_authenticated_user(+ user_id(),+ entity_id,+ entity_type,+ ))+ }++ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: entity_access::domain::models::BotId,+ _scope: BotAccessScope,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::internal("test access failure"))+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Ok(self.team)+ }+}#[test]fn read_channel_messages_schema_is_valid() {@@ -35,3 +363,403 @@ fn read_channel_thread_schema_is_valid() {assert_eq!(validated.name, "ReadChannelThread");assert!(validated.description.contains("Read"));}++#[test]+fn create_channel_schema_is_valid() {+ let result = generate_validated_input_schema::<CreateChannel>();+ assert!(result.is_ok(), "{result:?}");+ let validated = result.unwrap();+ assert_eq!(validated.name, "CreateChannel");+ assert!(validated.description.contains("private or team"));+}++#[test]+fn rename_channel_schema_is_valid() {+ let result = generate_validated_input_schema::<RenameChannel>();+ assert!(result.is_ok(), "{result:?}");+ let validated = result.unwrap();+ assert_eq!(validated.name, "RenameChannel");+ assert!(validated.description.contains("Rename"));+}++#[test]+fn manage_channel_participants_schema_is_valid() {+ let result = generate_validated_input_schema::<ManageChannelParticipants>();+ assert!(result.is_ok(), "{result:?}");+ let validated = result.unwrap();+ assert_eq!(validated.name, "ManageChannelParticipants");+ assert!(validated.description.contains("Add or remove"));+}++#[test]+fn channel_name_trims_and_rejects_empty() {+ assert_eq!(channel_name(" Planning ").expect("trimmed"), "Planning");+ assert_eq!(+ channel_name(" ").expect_err("empty").description,+ "channel name must not be empty"+ );+ assert!(+ channel_name(&"n".repeat(256))+ .expect_err("too long")+ .description+ .contains("255")+ );+}++#[test]+fn parse_participants_accepts_ids_and_emails_and_dedupes() {+ let parsed = parse_participants(&[+ "macro|[email protected]".to_string(),+ "[email protected]".to_string(),+ " macro|[email protected] ".to_string(),+ ])+ .expect("valid participants");+ assert_eq!(+ parsed+ .iter()+ .map(|id| id.as_ref().to_string())+ .collect::<Vec<_>>(),+ vec!["macro|[email protected]", "macro|[email protected]"]+ );+}++#[test]+fn parse_participants_reports_every_invalid_entry() {+ let error = parse_participants(&["not-an-id".to_string(), "".to_string()])+ .expect_err("invalid participants");+ assert!(error.description.contains("participants[0]"));+ assert!(error.description.contains("participants[1]"));+}++#[test]+fn mutation_errors_are_actionable_without_exposing_repository_details() {+ let missing = channel_mutation_error(+ "rename the channel",+ ChannelMutationErr::NotFound("channel not found".to_string()),+ );+ assert_eq!(missing.description, "channel not found");++ let repository = channel_mutation_error(+ "rename the channel",+ ChannelMutationErr::Repo(anyhow::anyhow!("database password leaked")),+ );+ assert_eq!(repository.description, "failed to rename the channel");+}++#[tokio::test]+async fn create_private_channel_does_not_resolve_a_team() {+ let channel_id = Uuid::new_v4();+ let service = ToolTestChannelService {+ created_id: Some(channel_id),+ ..ToolTestChannelService::default()+ };+ let created = service.created.clone();+ let context = ChannelToolContext::new(service, NoOpEntityAccessService);++ let response = CreateChannel {+ name: " Planning ".to_string(),+ channel_type: NewChannelType::Private,+ participants: vec!["[email protected]".to_string()],+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("private create does not need entity access");++ assert_eq!(response.channel_id, channel_id);+ assert_eq!(response.name, "Planning");+ assert_eq!(response.channel_type, NewChannelType::Private);+ assert_eq!(response.participants, vec!["macro|[email protected]"]);+ let (actor, org_id, req) = created+ .lock()+ .expect("create lock")+ .clone()+ .expect("called");+ assert_eq!(actor.as_user(), Some(&user_id()));+ assert_eq!(org_id, None);+ assert_eq!(req.channel_type, ChannelType::Private);+ assert_eq!(req.team_id, None);+ assert!(!req.auto_join_team);+ assert_eq!(req.name.as_deref(), Some("Planning"));+}++#[tokio::test]+async fn create_team_channel_injects_the_caller_when_participants_are_empty() {+ let team_id = Uuid::new_v4();+ let service = ToolTestChannelService::default();+ let created = service.created.clone();+ let context = ChannelToolContext::new(+ service,+ ToolTestAccessService {+ team: Some(UserTeamInfo {+ team_id,+ role: TeamRole::Member,+ }),+ ..ToolTestAccessService::default()+ },+ );++ let response = CreateChannel {+ name: "Team Sync".to_string(),+ channel_type: NewChannelType::Team,+ participants: Vec::new(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("team create injects the caller");++ assert_eq!(response.participants, vec![TEST_USER_ID]);+ let (_, _, req) = created+ .lock()+ .expect("create lock")+ .clone()+ .expect("called");+ assert_eq!(req.channel_type, ChannelType::Team);+ assert_eq!(req.team_id, Some(team_id));+ assert!(req.participants.contains(&user_id()));+}++#[tokio::test]+async fn create_team_channel_fails_when_the_user_has_no_team() {+ let service = ToolTestChannelService::default();+ let created = service.created.clone();+ let context = ChannelToolContext::new(service, ToolTestAccessService::default());++ let error = CreateChannel {+ name: "Team Sync".to_string(),+ channel_type: NewChannelType::Team,+ participants: Vec::new(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("team create without a team");++ assert!(error.description.contains("not a member of a team"));+ assert!(created.lock().expect("create lock").is_none());+}++#[tokio::test]+async fn create_channel_rejects_an_empty_name() {+ let context =+ ChannelToolContext::new(ToolTestChannelService::default(), NoOpEntityAccessService);++ let error = CreateChannel {+ name: " ".to_string(),+ channel_type: NewChannelType::Private,+ participants: Vec::new(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("empty name");++ assert_eq!(error.description, "channel name must not be empty");+}++#[tokio::test]+async fn create_channel_surfaces_domain_errors() {+ let context = ChannelToolContext::new(+ ToolTestChannelService {+ create_error: Some("participants must be a non-empty list of 'macro|<email>'".into()),+ ..ToolTestChannelService::default()+ },+ NoOpEntityAccessService,+ );++ let error = CreateChannel {+ name: "Planning".to_string(),+ channel_type: NewChannelType::Private,+ participants: Vec::new(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("domain error");++ assert!(+ error+ .description+ .contains("participants must be a non-empty list")+ );+}++#[tokio::test]+async fn rename_channel_requires_admin_and_patches_only_the_name() {+ let channel_id = Uuid::new_v4();+ let service = ToolTestChannelService {+ metadata_name: Some("Old Name".to_string()),+ ..ToolTestChannelService::default()+ };+ let patches = service.patches.clone();+ let access = ToolTestAccessService::default();+ let receipt_calls = access.receipt_calls.clone();+ let context = ChannelToolContext::new(service, access);++ let response = RenameChannel {+ channel_id,+ name: " New Name ".to_string(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("admin can rename");++ assert_eq!(response.name, "New Name");+ assert_eq!(response.previous_name.as_deref(), Some("Old Name"));+ assert_eq!(receipt_calls.load(Ordering::SeqCst), 1);+ let (actor, patched_id, req) = patches.lock().expect("patch lock").pop().expect("patched");+ assert_eq!(actor.as_user(), Some(&user_id()));+ assert_eq!(patched_id, channel_id);+ assert_eq!(req.channel_name.as_deref(), Some("New Name"));+ assert_eq!(req.convert_to_team_channel, None);+ assert_eq!(req.auto_join_team, None);+}++#[tokio::test]+async fn rename_channel_rejects_non_admins() {+ let context = ChannelToolContext::new(+ ToolTestChannelService::default(),+ ToolTestAccessService {+ receipt_error: Some(ReceiptFail::Unauthorized),+ ..ToolTestAccessService::default()+ },+ );++ let error = RenameChannel {+ channel_id: Uuid::new_v4(),+ name: "New Name".to_string(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("non-admin");++ assert_eq!(+ error.description,+ "you need channel admin access to rename this channel"+ );+}++#[tokio::test]+async fn rename_channel_surfaces_dm_rename_rejection() {+ let context = ChannelToolContext::new(+ ToolTestChannelService {+ patch_error: Some("cannot change channel_name for direct message channels".into()),+ ..ToolTestChannelService::default()+ },+ ToolTestAccessService::default(),+ );++ let error = RenameChannel {+ channel_id: Uuid::new_v4(),+ name: "Nope".to_string(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("dm rename");++ assert_eq!(+ error.description,+ "cannot change channel_name for direct message channels"+ );+}++#[tokio::test]+async fn manage_participants_adds_canonical_ids() {+ let channel_id = Uuid::new_v4();+ let service = ToolTestChannelService::default();+ let adds = service.adds.clone();+ let context = ChannelToolContext::new(service, ToolTestAccessService::default());++ let response = ManageChannelParticipants {+ channel_id,+ action: ParticipantAction::Add,+ participants: vec!["[email protected]".to_string()],+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("member can add");++ assert_eq!(response.action, ParticipantAction::Add);+ assert_eq!(response.participants, vec!["macro|[email protected]"]);+ let (actor, added_id, req) = adds.lock().expect("add lock").pop().expect("added");+ assert_eq!(actor.as_user(), Some(&user_id()));+ assert_eq!(added_id, channel_id);+ assert!(+ req.participants+ .contains(&MacroUserIdStr::try_from_email("[email protected]").expect("email"))+ );+}++#[tokio::test]+async fn manage_participants_canonicalizes_remove_ids() {+ let channel_id = Uuid::new_v4();+ let service = ToolTestChannelService::default();+ let removes = service.removes.clone();+ let context = ChannelToolContext::new(service, ToolTestAccessService::default());++ ManageChannelParticipants {+ channel_id,+ action: ParticipantAction::Remove,+ participants: vec!["[email protected]".to_string()],+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("member can remove");++ let (_, _, req) = removes.lock().expect("remove lock").pop().expect("removed");+ assert_eq!(req.participants, vec!["macro|[email protected]"]);+}++#[tokio::test]+async fn manage_participants_rejects_an_empty_list_before_the_service() {+ let service = ToolTestChannelService::default();+ let adds = service.adds.clone();+ let context = ChannelToolContext::new(service, ToolTestAccessService::default());++ let error = ManageChannelParticipants {+ channel_id: Uuid::new_v4(),+ action: ParticipantAction::Add,+ participants: Vec::new(),+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("empty list");++ assert!(error.description.contains("must not be empty"));+ assert!(adds.lock().expect("add lock").is_empty());+}++#[tokio::test]+async fn manage_participants_requires_membership() {+ let context =+ ChannelToolContext::new(ToolTestChannelService::default(), NoOpEntityAccessService);++ let error = ManageChannelParticipants {+ channel_id: Uuid::new_v4(),+ action: ParticipantAction::Add,+ participants: vec!["[email protected]".to_string()],+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("NoOp rejects membership");++ assert_eq!(error.description, "failed to verify channel membership");+}++#[tokio::test]+async fn manage_participants_distinguishes_missing_channels() {+ let context = ChannelToolContext::new(+ ToolTestChannelService::default(),+ ToolTestAccessService {+ receipt_error: Some(ReceiptFail::NotFound),+ ..ToolTestAccessService::default()+ },+ );++ let error = ManageChannelParticipants {+ channel_id: Uuid::new_v4(),+ action: ParticipantAction::Remove,+ participants: vec!["[email protected]".to_string()],+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("missing channel");++ assert_eq!(error.description, "channel not found");+}