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(ai): give ai tools to create and manage bots (#5748)

teoe2d3bbab8aee
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index f4789bdca7..a98f6f4716 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -408,6 +408,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -591,6 +592,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -1155,6 +1157,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -2043,6 +2046,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -4569,6 +4573,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -4692,6 +4697,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -5823,6 +5829,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
diff --git a/Cargo.lock b/Cargo.lock
index 57f29e9342..d5e30749bd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -490,6 +490,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"bot_id",
+ "bots",
"calendar_events",
"call",
"channels",
@@ -2647,7 +2648,9 @@ dependencies = [
name = "bots"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
"anyhow",
+ "async-trait",
"axum",
"bot_id",
"channels",
@@ -2664,6 +2667,7 @@ dependencies = [
"model-error-response",
"rand 0.9.4",
"rootcause",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/docs/AI/mcp/tools/configure-bot.mdx b/apps/docs/AI/mcp/tools/configure-bot.mdx
new file mode 100644
index 0000000000..05541de63f
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/configure-bot.mdx
@@ -0,0 +1,19 @@
+---
+title: ConfigureBot
+description: "Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle."
+---
+
+# ConfigureBot
+
+Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `botId` | string | Yes | Bot id from CreateBot or ListBots. |
+| `name` | string | No | New display name. Omit to keep the current name. |
+| `handle` | string | No | New stable handle using lowercase ASCII letters, digits, hyphens, and underscores. Omit to keep the current handle. |
+| `description` | string | No | New bot description. Omit to keep the current value; pass an empty string to clear it. |
+| `avatarUrl` | string | No | New profile-picture URL. Use a Macro static-file URL or another reachable image URL. Omit to keep the current picture; pass an empty string to clear it. |
+| `hasAgent` | boolean | No | Set true if mentioning this bot should open a sandboxed coding-agent session. Omit to leave unchanged. |
diff --git a/apps/docs/AI/mcp/tools/create-bot.mdx b/apps/docs/AI/mcp/tools/create-bot.mdx
new file mode 100644
index 0000000000..2085231e72
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/create-bot.mdx
@@ -0,0 +1,22 @@
+---
+title: CreateBot
+description: "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
+---
+
+# CreateBot
+
+Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Team id that should own the bot. Omit for a bot owned by the current user. |
+| `name` | string | Yes | Human-readable display name for the bot. |
+| `handle` | string | Yes | Stable mention handle using only lowercase ASCII letters, digits, hyphens, and underscores; maximum 64 characters. |
+| `description` | string | No | Optional short description of what the bot does. |
+| `avatarUrl` | string | No | Optional URL for the bot profile picture. Pass the URL of an image already uploaded to Macro static files or another reachable image URL. |
+| `channelId` | string | No | Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL. |
+| `credentialLabel` | string | No | Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId. |
+| `credentialExpiresAt` | string | No | Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId. |
+| `hasAgent` | boolean | No | Set true if mentioning this bot should open a sandboxed coding-agent session. Defaults to false. |
diff --git a/apps/docs/AI/mcp/tools/delete-bot.mdx b/apps/docs/AI/mcp/tools/delete-bot.mdx
new file mode 100644
index 0000000000..294a7381fb
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-bot.mdx
@@ -0,0 +1,14 @@
+---
+title: DeleteBot
+description: "Delete a bot the current user owns or a bot owned by a team they belong to. This removes the bot from every channel and disables its credentials and webhooks. The operation cannot be undone, so only use it after the user explicitly confirms deletion."
+---
+
+# DeleteBot
+
+Delete a bot the current user owns or a bot owned by a team they belong to. This removes the bot from every channel and disables its credentials and webhooks. The operation cannot be undone, so only use it after the user explicitly confirms deletion.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `botId` | string | Yes | Bot id from ListBots. |
diff --git a/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx b/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx
new file mode 100644
index 0000000000..e990de1d1b
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx
@@ -0,0 +1,14 @@
+---
+title: GetBotWebhooks
+description: "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
+---
+
+# GetBotWebhooks
+
+Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `botId` | string | Yes | Bot id from CreateBot or ListBots. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 825dd8f2be..45c8152475 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -11,13 +11,16 @@ These pages are generated from Macro's Rust MCP tool registry.
- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)
- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)
+- [ConfigureBot](/AI/mcp/tools/configure-bot)
- [ContentSearch](/AI/mcp/tools/content-search)
+- [CreateBot](/AI/mcp/tools/create-bot)
- [CreateCalendarEvent](/AI/mcp/tools/create-calendar-event)
- [CreateDocument](/AI/mcp/tools/create-document)
- [CreateImportEntity](/AI/mcp/tools/create-import-entity)
- [CreateProject](/AI/mcp/tools/create-project)
- [CreateReminder](/AI/mcp/tools/create-reminder)
- [CreateTag](/AI/mcp/tools/create-tag)
+- [DeleteBot](/AI/mcp/tools/delete-bot)
- [DeleteCalendarEvent](/AI/mcp/tools/delete-calendar-event)
- [DeleteImportEntity](/AI/mcp/tools/delete-import-entity)
- [DeleteReminder](/AI/mcp/tools/delete-reminder)
@@ -25,10 +28,13 @@ These pages are generated from Macro's Rust MCP tool registry.
- [DisplayResults](/AI/mcp/tools/display-results)
- [EditDocument](/AI/mcp/tools/edit-document)
- [EditTag](/AI/mcp/tools/edit-tag)
+- [GetBotWebhooks](/AI/mcp/tools/get-bot-webhooks)
- [GetCompany](/AI/mcp/tools/get-company)
- [GetEntityProperties](/AI/mcp/tools/get-entity-properties)
- [GetThread](/AI/mcp/tools/get-thread)
- [ImportNotionPage](/AI/mcp/tools/import-notion-page)
+- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)
+- [ListBots](/AI/mcp/tools/list-bots)
- [ListCalendarEvents](/AI/mcp/tools/list-calendar-events)
- [ListCalendars](/AI/mcp/tools/list-calendars)
- [ListCompanies](/AI/mcp/tools/list-companies)
@@ -42,6 +48,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ListTags](/AI/mcp/tools/list-tags)
- [ListTeamMembers](/AI/mcp/tools/list-team-members)
- [LoadTools](/AI/mcp/tools/load-tools)
+- [ManageBotChannelAccess](/AI/mcp/tools/manage-bot-channel-access)
- [MarkNotificationsDone](/AI/mcp/tools/mark-notifications-done)
- [MarkNotificationsSeen](/AI/mcp/tools/mark-notifications-seen)
- [MoveToProject](/AI/mcp/tools/move-to-project)
diff --git a/apps/docs/AI/mcp/tools/issue-bot-credential.mdx b/apps/docs/AI/mcp/tools/issue-bot-credential.mdx
new file mode 100644
index 0000000000..ced23ab9d4
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/issue-bot-credential.mdx
@@ -0,0 +1,16 @@
+---
+title: IssueBotCredential
+description: "Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once."
+---
+
+# IssueBotCredential
+
+Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `botId` | string | Yes | Bot id from CreateBot or ListBots. |
+| `label` | string | No | Optional label describing where the credential will be used, such as `github-webhook`. |
+| `expiresAt` | string | No | Optional RFC 3339 expiration timestamp. Omit for a credential without a scheduled expiration. |
diff --git a/apps/docs/AI/mcp/tools/list-bots.mdx b/apps/docs/AI/mcp/tools/list-bots.mdx
new file mode 100644
index 0000000000..ce3d93e0dc
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/list-bots.mdx
@@ -0,0 +1,8 @@
+---
+title: ListBots
+description: "List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot."
+---
+
+# ListBots
+
+List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot.
diff --git a/apps/docs/AI/mcp/tools/manage-bot-channel-access.mdx b/apps/docs/AI/mcp/tools/manage-bot-channel-access.mdx
new file mode 100644
index 0000000000..410ccf82d7
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/manage-bot-channel-access.mdx
@@ -0,0 +1,16 @@
+---
+title: ManageBotChannelAccess
+description: "Grant or revoke a manageable bot's access to one channel. Granting requires the current user to be a channel member. Both actions require the user to own the bot or belong to its owning team; revoking still works after the manager leaves the channel. Granting access creates that channel's webhook URL; revoking access disables posting to that channel. Use only after the user asks to change bot access."
+---
+
+# ManageBotChannelAccess
+
+Grant or revoke a manageable bot's access to one channel. Granting requires the current user to be a channel member. Both actions require the user to own the bot or belong to its owning team; revoking still works after the manager leaves the channel. Granting access creates that channel's webhook URL; revoking access disables posting to that channel. Use only after the user asks to change bot access.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `botId` | string | Yes | Bot id from CreateBot or ListBots. |
+| `channelId` | string | Yes | Channel id to grant or revoke access to. |
+| `action` | `"grant"` \| `"revoke"` | Yes | Channel-access change to apply to a bot. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 8132d31b47..287cdb672b 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -2,13 +2,16 @@
"AI/mcp/tools/index",
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
+ "AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
+ "AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-document",
"AI/mcp/tools/create-import-entity",
"AI/mcp/tools/create-project",
"AI/mcp/tools/create-reminder",
"AI/mcp/tools/create-tag",
+ "AI/mcp/tools/delete-bot",
"AI/mcp/tools/delete-calendar-event",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-reminder",
@@ -16,10 +19,13 @@
"AI/mcp/tools/display-results",
"AI/mcp/tools/edit-document",
"AI/mcp/tools/edit-tag",
+ "AI/mcp/tools/get-bot-webhooks",
"AI/mcp/tools/get-company",
"AI/mcp/tools/get-entity-properties",
"AI/mcp/tools/get-thread",
"AI/mcp/tools/import-notion-page",
+ "AI/mcp/tools/issue-bot-credential",
+ "AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
"AI/mcp/tools/list-companies",
@@ -33,6 +39,7 @@
"AI/mcp/tools/list-tags",
"AI/mcp/tools/list-team-members",
"AI/mcp/tools/load-tools",
+ "AI/mcp/tools/manage-bot-channel-access",
"AI/mcp/tools/mark-notifications-done",
"AI/mcp/tools/mark-notifications-seen",
"AI/mcp/tools/move-to-project",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index d39cd7d87e..f5946fee3c 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -71,13 +71,16 @@
"AI/mcp/tools/index",
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
+ "AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
+ "AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-document",
"AI/mcp/tools/create-import-entity",
"AI/mcp/tools/create-project",
"AI/mcp/tools/create-reminder",
"AI/mcp/tools/create-tag",
+ "AI/mcp/tools/delete-bot",
"AI/mcp/tools/delete-calendar-event",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-reminder",
@@ -85,10 +88,13 @@
"AI/mcp/tools/display-results",
"AI/mcp/tools/edit-document",
"AI/mcp/tools/edit-tag",
+ "AI/mcp/tools/get-bot-webhooks",
"AI/mcp/tools/get-company",
"AI/mcp/tools/get-entity-properties",
"AI/mcp/tools/get-thread",
"AI/mcp/tools/import-notion-page",
+ "AI/mcp/tools/issue-bot-credential",
+ "AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
"AI/mcp/tools/list-companies",
@@ -102,6 +108,7 @@
"AI/mcp/tools/list-tags",
"AI/mcp/tools/list-team-members",
"AI/mcp/tools/load-tools",
+ "AI/mcp/tools/manage-bot-channel-access",
"AI/mcp/tools/mark-notifications-done",
"AI/mcp/tools/mark-notifications-seen",
"AI/mcp/tools/move-to-project",
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx
new file mode 100644
index 0000000000..214cc74d0e
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx
@@ -0,0 +1,448 @@
+import Key from '@phosphor-icons/core/regular/key.svg';
+import Link from '@phosphor-icons/core/regular/link.svg';
+import List from '@phosphor-icons/core/regular/list.svg';
+import PlugsConnected from '@phosphor-icons/core/regular/plugs-connected.svg';
+import Robot from '@phosphor-icons/core/regular/robot.svg';
+import SlidersHorizontal from '@phosphor-icons/core/regular/sliders-horizontal.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import type {
+ BotOwnerSummary,
+ BotSummary,
+} from '@service-cognition/generated/tools/types';
+import { createSignal, For, Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+type Detail = {
+ label: string;
+ value?: string | null;
+ secret?: boolean;
+};
+
+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"
+ classList={{ 'select-all font-mono': detail.secret }}
+ >
+ {detail.value}
+ </dd>
+ </div>
+ )}
+ </For>
+ </dl>
+ </div>
+ );
+}
+
+function ownerLabel(owner: BotOwnerSummary): string {
+ return owner.type === 'team'
+ ? `Team · ${owner.team_id}`
+ : `User · ${owner.user_id}`;
+}
+
+function botDetails(bot: BotSummary): Detail[] {
+ return [
+ { label: 'Bot ID', value: bot.botId, secret: true },
+ { label: 'Handle', value: `@${bot.handle}` },
+ { label: 'Owner', value: ownerLabel(bot.owner) },
+ { label: 'Description', value: bot.description },
+ { label: 'Profile picture', value: bot.avatarUrl },
+ { label: 'Coding agent', value: bot.hasAgent ? 'Yes' : 'No' },
+ ];
+}
+
+type ListedBot = NamedTool<'ListBots', 'response'>['data']['bots'][number];
+
+function BotList(props: { bots: ListedBot[] }) {
+ return (
+ <Tool.List>
+ <div class="max-h-60 overflow-y-auto overscroll-contain">
+ <For each={props.bots}>
+ {(bot) => (
+ <Tool.ListItem icon={<Robot class="size-4" />}>
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <div class="min-w-0">
+ <div class="truncate text-ink">{bot.name}</div>
+ <div class="truncate text-2xs text-ink-extra-muted">
+ @{bot.handle}
+ </div>
+ </div>
+ <span class="max-w-44 shrink-0 truncate text-ink-extra-muted">
+ {bot.owner.type === 'team' ? 'Team bot' : 'User bot'}
+ </span>
+ </div>
+ </Tool.ListItem>
+ )}
+ </For>
+ </div>
+ </Tool.List>
+ );
+}
+
+const listBotsHandler = createToolRenderer({
+ name: 'ListBots',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const bots = () => ctx.response?.data.bots ?? [];
+ const status = () => {
+ if (!ctx.response) return undefined;
+ return `${bots().length} bot${bots().length === 1 ? '' : 's'}`;
+ };
+
+ return (
+ <BaseTool
+ icon={List}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && bots().length > 0 ? (
+ <BotList bots={bots()} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>List manageable bots</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={bots().length > 0}
+ status={status()}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const createBotHandler = createToolRenderer({
+ name: 'CreateBot',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const bot = () => ctx.response?.data.bot;
+ const setup = () => ctx.response?.data.channelSetup;
+
+ return (
+ <BaseTool
+ icon={Robot}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && bot() ? (
+ <div class="flex flex-col gap-2">
+ <DetailPanel
+ details={botDetails(bot()!)}
+ summary={ctx.response?.data.summary}
+ />
+ <Show when={setup()}>
+ {(channelSetup) => (
+ <DetailPanel
+ details={[
+ {
+ label: 'Bearer token',
+ value: channelSetup().bearerToken,
+ secret: true,
+ },
+ {
+ label: 'Webhook',
+ value: channelSetup().webhook.webhookUrl,
+ secret: true,
+ },
+ {
+ label: 'Channel ID',
+ value: channelSetup().channelId,
+ },
+ {
+ label: 'Token header',
+ value: channelSetup().credentialHeader,
+ },
+ ]}
+ />
+ )}
+ </Show>
+ </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 bot' : 'Create bot'}{' '}
+ <span class="text-ink">@{ctx.tool.data.handle}</span>
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!bot()}
+ status={
+ ctx.response
+ ? setup()
+ ? 'Created · credential'
+ : 'Created'
+ : undefined
+ }
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const issueBotCredentialHandler = createToolRenderer({
+ name: 'IssueBotCredential',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const credential = () => ctx.response?.data;
+
+ return (
+ <BaseTool
+ icon={Key}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && credential() ? (
+ <DetailPanel
+ summary={credential()!.summary}
+ details={[
+ {
+ label: 'Bearer token',
+ value: credential()!.bearerToken,
+ secret: true,
+ },
+ {
+ label: 'Credential ID',
+ value: credential()!.tokenId,
+ secret: true,
+ },
+ { label: 'Label', value: credential()!.label },
+ { label: 'Expires', value: credential()!.expiresAt },
+ ]}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0 truncate">
+ {ctx.response ? 'Issued' : 'Issue'} bot credential
+ <Show when={ctx.tool.data.label}>
+ {(label) => <> · {label()}</>}
+ </Show>
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!credential()}
+ status={ctx.response ? 'Sensitive' : undefined}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const getBotWebhooksHandler = createToolRenderer({
+ name: 'GetBotWebhooks',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+ const webhooks = () => response()?.webhooks ?? [];
+
+ return (
+ <BaseTool
+ icon={Link}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <div class="flex flex-col gap-2">
+ <For each={webhooks()}>
+ {(webhook) => (
+ <DetailPanel
+ details={[
+ {
+ label: webhook.channelName || 'Channel',
+ value: webhook.webhookUrl,
+ secret: true,
+ },
+ { label: 'Channel ID', value: webhook.channelId },
+ ]}
+ />
+ )}
+ </For>
+ <Show when={webhooks().length === 0}>
+ <DetailPanel details={[]} summary={response()!.summary} />
+ </Show>
+ <DetailPanel
+ details={[
+ {
+ label: 'Token header',
+ value: response()!.credentialHeader,
+ secret: true,
+ },
+ {
+ label: 'Scope header',
+ value: response()!.credentialScopeHeader,
+ },
+ {
+ label: 'Scope value',
+ value: response()!.credentialScope,
+ },
+ ]}
+ />
+ </div>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>Get bot webhooks</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={
+ response()
+ ? `${webhooks().length} webhook${webhooks().length === 1 ? '' : 's'}`
+ : undefined
+ }
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const manageBotChannelAccessHandler = createToolRenderer({
+ name: 'ManageBotChannelAccess',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+ const granting = () => ctx.tool.data.action === 'grant';
+
+ return (
+ <BaseTool
+ icon={PlugsConnected}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <DetailPanel
+ summary={response()!.summary}
+ details={[
+ { label: 'Bot ID', value: response()!.botId },
+ { label: 'Channel ID', value: response()!.channelId },
+ ]}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ {granting()
+ ? 'Grant bot channel access'
+ : 'Revoke bot channel access'}
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={
+ ctx.response ? (granting() ? 'Granted' : 'Revoked') : undefined
+ }
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const configureBotHandler = createToolRenderer({
+ name: 'ConfigureBot',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+
+ return (
+ <BaseTool
+ icon={SlidersHorizontal}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <DetailPanel
+ details={botDetails(response()!.bot)}
+ summary={response()!.summary}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>{ctx.response ? 'Configured bot' : 'Configure bot'}</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={
+ ctx.response ? `@${ctx.response.data.bot.handle}` : undefined
+ }
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const deleteBotHandler = createToolRenderer({
+ name: 'DeleteBot',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+
+ return (
+ <BaseTool
+ icon={Trash}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <DetailPanel
+ details={[{ label: 'Bot ID', value: response()!.botId }]}
+ summary={response()!.summary}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>{ctx.response ? 'Deleted bot' : 'Delete bot'}</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={ctx.response ? 'Deleted' : undefined}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export {
+ configureBotHandler,
+ createBotHandler,
+ deleteBotHandler,
+ getBotWebhooksHandler,
+ issueBotCredentialHandler,
+ listBotsHandler,
+ manageBotChannelAccessHandler,
+};
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 f4452ce3cd..bb89be582c 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
@@ -5,6 +5,15 @@ import {
} from '@service-cognition/generated/tools/tool';
import { Dynamic } from 'solid-js/web';
import { bashCodeExecutionHandler } from './BashCodeExecution';
+import {
+ configureBotHandler,
+ createBotHandler,
+ deleteBotHandler,
+ getBotWebhooksHandler,
+ issueBotCredentialHandler,
+ listBotsHandler,
+ manageBotChannelAccessHandler,
+} from './Bots';
import {
createCalendarEventHandler,
deleteCalendarEventHandler,
@@ -83,6 +92,13 @@ import { webFetchHandler } from './WebFetch';
import { webSearchHandler } from './WebSearch';
const toolHandlers: ToolHandlerMap<RenderContext> = {
+ ConfigureBot: configureBotHandler,
+ CreateBot: createBotHandler,
+ DeleteBot: deleteBotHandler,
+ GetBotWebhooks: getBotWebhooksHandler,
+ IssueBotCredential: issueBotCredentialHandler,
+ ListBots: listBotsHandler,
+ ManageBotChannelAccess: manageBotChannelAccessHandler,
CreateCalendarEvent: createCalendarEventHandler,
UpdateCalendarEvent: updateCalendarEventHandler,
DeleteCalendarEvent: deleteCalendarEventHandler,
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 a52100f10b..e1d9b8db8b 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
@@ -104,6 +104,48 @@ export const BulkSetEntityPropertyOptionsResponse = z.object({
summary: z.string(),
});
+export const ConfigureBot = z.object({
+ botId: z.string().uuid(),
+ name: z.union([z.string(), z.null()]).optional(),
+ handle: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ avatarUrl: z.union([z.string(), z.null()]).optional(),
+ hasAgent: z.union([z.boolean(), z.null()]).optional(),
+});
+
+export const ConfigureBotResponse = z.object({
+ bot: z.object({
+ botId: z.string().uuid(),
+ owner: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ user_id: z.string(), type: z.literal('user') }),
+ z.object({ team_id: z.string().uuid(), type: 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',
+ });
+ }
+ }),
+ name: z.string(),
+ handle: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ avatarUrl: z.union([z.string(), z.null()]).optional(),
+ hasAgent: z.boolean(),
+ }),
+ summary: z.string(),
+});
+
export const ContentSearch = z.object({
query: z.string(),
matchType: z
@@ -646,6 +688,71 @@ export const SearchToolResponse = z.object({
),
});
+export const CreateBot = z.object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ name: z.string(),
+ handle: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ avatarUrl: z.union([z.string(), z.null()]).optional(),
+ channelId: z.union([z.string().uuid(), z.null()]).optional(),
+ credentialLabel: z.union([z.string(), z.null()]).optional(),
+ credentialExpiresAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ hasAgent: z.union([z.boolean(), z.null()]).optional(),
+});
+
+export const CreateBotResponse = z.object({
+ bot: z.object({
+ botId: z.string().uuid(),
+ owner: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ user_id: z.string(), type: z.literal('user') }),
+ z.object({ team_id: z.string().uuid(), type: 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',
+ });
+ }
+ }),
+ name: z.string(),
+ handle: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ avatarUrl: z.union([z.string(), z.null()]).optional(),
+ hasAgent: z.boolean(),
+ }),
+ channelSetup: z
+ .union([
+ z.object({
+ channelId: z.string().uuid(),
+ tokenId: z.string().uuid(),
+ bearerToken: z.string(),
+ webhook: z.object({
+ channelId: z.string().uuid(),
+ channelName: z.union([z.string(), z.null()]).optional(),
+ webhookUrl: z.string(),
+ }),
+ credentialHeader: z.string(),
+ credentialScopeHeader: z.string(),
+ credentialScope: z.string(),
+ }),
+ z.null(),
+ ])
+ .optional(),
+ summary: z.string(),
+});
+
export const CreateCalendarEvent = z.object({
title: z.string(),
time: z.any().superRefine((x, ctx) => {
@@ -1044,6 +1151,14 @@ export const CreateTagResponse = z.object({
summary: z.string(),
});
+export const DeleteBot = z.object({ botId: z.string().uuid() });
+
+export const DeleteBotResponse = z.object({
+ botId: z.string().uuid(),
+ deleted: z.boolean(),
+ summary: z.string(),
+});
+
export const DeleteCalendarEvent = z.object({
eventId: z.string().uuid(),
scope: z
@@ -1167,6 +1282,23 @@ export const EditTagResponse = z.object({
summary: z.string(),
});
+export const GetBotWebhooks = z.object({ botId: z.string().uuid() });
+
+export const GetBotWebhooksResponse = z.object({
+ botId: z.string().uuid(),
+ credentialHeader: z.string(),
+ credentialScopeHeader: z.string(),
+ credentialScope: z.string(),
+ webhooks: z.array(
+ z.object({
+ channelId: z.string().uuid(),
+ channelName: z.union([z.string(), z.null()]).optional(),
+ webhookUrl: z.string(),
+ })
+ ),
+ summary: z.string(),
+});
+
export const GetCompany = z.object({ company_id: z.string().uuid() });
export const GetCompanyResponse = z.object({
@@ -1374,6 +1506,62 @@ export const ImportNotionPageResponse = z.object({
message: z.string(),
});
+export const IssueBotCredential = z.object({
+ botId: z.string().uuid(),
+ label: z.union([z.string(), z.null()]).optional(),
+ expiresAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+});
+
+export const IssueBotCredentialResponse = z.object({
+ botId: z.string().uuid(),
+ tokenId: z.string().uuid(),
+ bearerToken: z.string(),
+ label: z.union([z.string(), z.null()]).optional(),
+ expiresAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ summary: z.string(),
+});
+
+export const ListBots = z.record(z.any());
+
+export const ListBotsResponse = z.object({
+ bots: z.array(
+ z.object({
+ botId: z.string().uuid(),
+ owner: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ user_id: z.string(), type: z.literal('user') }),
+ z.object({ team_id: z.string().uuid(), type: 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',
+ });
+ }
+ }),
+ name: z.string(),
+ handle: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ avatarUrl: z.union([z.string(), z.null()]).optional(),
+ hasAgent: z.boolean(),
+ })
+ ),
+ summary: z.string(),
+});
+
export const ListCalendarEvents = z.object({
start: z.string().datetime({ offset: true }),
end: z.string().datetime({ offset: true }),
@@ -2193,6 +2381,53 @@ export const LoadToolsResponse = z.object({
not_found: z.array(z.string()),
});
+export const ManageBotChannelAccess = z.object({
+ botId: z.string().uuid(),
+ channelId: z.string().uuid(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('grant'), z.literal('revoke')];
+ 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',
+ });
+ }
+ }),
+});
+
+export const ManageBotChannelAccessResponse = z.object({
+ botId: z.string().uuid(),
+ channelId: z.string().uuid(),
+ action: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('grant'), z.literal('revoke')];
+ 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',
+ });
+ }
+ }),
+ summary: z.string(),
+});
+
export const MarkNotificationsDone = z.object({
notificationIds: z.array(z.string().uuid()),
done: z.boolean(),
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 c40abb61a5..d063332b8e 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
@@ -16,10 +16,15 @@ type ToolParserMap = {
call: types.BulkSetEntityPropertyOptions;
response: types.BulkSetEntityPropertyOptionsResponse;
};
+ ConfigureBot: {
+ call: types.ConfigureBot;
+ response: types.ConfigureBotResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
response: types.UserToolResponseForToolCalendarEvent;
@@ -38,6 +43,7 @@ type ToolParserMap = {
};
CreateReminder: { call: types.CreateReminder; response: types.ToolReminder };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
+ DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };
DeleteCalendarEvent: {
call: types.DeleteCalendarEvent;
response: types.DeleteCalendarEventResponse;
@@ -60,6 +66,10 @@ type ToolParserMap = {
response: types.EditDocumentResponse;
};
EditTag: { call: types.EditTag; response: types.EditTagResponse };
+ GetBotWebhooks: {
+ call: types.GetBotWebhooks;
+ response: types.GetBotWebhooksResponse;
+ };
GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };
GetEntityProperties: {
call: types.GetEntityProperties;
@@ -70,6 +80,11 @@ type ToolParserMap = {
call: types.ImportNotionPage;
response: types.ImportNotionPageResponse;
};
+ IssueBotCredential: {
+ call: types.IssueBotCredential;
+ response: types.IssueBotCredentialResponse;
+ };
+ ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
response: types.ListCalendarEventsResponse;
@@ -107,6 +122,10 @@ type ToolParserMap = {
response: types.ListTeamMembersResponse;
};
LoadTools: { call: types.LoadTools; response: types.LoadToolsResponse };
+ ManageBotChannelAccess: {
+ call: types.ManageBotChannelAccess;
+ response: types.ManageBotChannelAccessResponse;
+ };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
@@ -200,10 +219,15 @@ const toolParserMap = {
call: schemas.BulkSetEntityPropertyOptions,
response: schemas.BulkSetEntityPropertyOptionsResponse,
},
+ ConfigureBot: {
+ call: schemas.ConfigureBot,
+ response: schemas.ConfigureBotResponse,
+ },
ContentSearch: {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
},
+ CreateBot: { call: schemas.CreateBot, response: schemas.CreateBotResponse },
CreateCalendarEvent: {
call: schemas.CreateCalendarEvent,
response: schemas.UserToolResponseForToolCalendarEvent,
@@ -225,6 +249,7 @@ const toolParserMap = {
response: schemas.ToolReminder,
},
CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },
+ DeleteBot: { call: schemas.DeleteBot, response: schemas.DeleteBotResponse },
DeleteCalendarEvent: {
call: schemas.DeleteCalendarEvent,
response: schemas.DeleteCalendarEventResponse,
@@ -247,6 +272,10 @@ const toolParserMap = {
response: schemas.EditDocumentResponse,
},
EditTag: { call: schemas.EditTag, response: schemas.EditTagResponse },
+ GetBotWebhooks: {
+ call: schemas.GetBotWebhooks,
+ response: schemas.GetBotWebhooksResponse,
+ },
GetCompany: {
call: schemas.GetCompany,
response: schemas.GetCompanyResponse,
@@ -260,6 +289,11 @@ const toolParserMap = {
call: schemas.ImportNotionPage,
response: schemas.ImportNotionPageResponse,
},
+ IssueBotCredential: {
+ call: schemas.IssueBotCredential,
+ response: schemas.IssueBotCredentialResponse,
+ },
+ ListBots: { call: schemas.ListBots, response: schemas.ListBotsResponse },
ListCalendarEvents: {
call: schemas.ListCalendarEvents,
response: schemas.ListCalendarEventsResponse,
@@ -306,6 +340,10 @@ const toolParserMap = {
response: schemas.ListTeamMembersResponse,
},
LoadTools: { call: schemas.LoadTools, response: schemas.LoadToolsResponse },
+ ManageBotChannelAccess: {
+ call: schemas.ManageBotChannelAccess,
+ response: schemas.ManageBotChannelAccessResponse,
+ },
MarkNotificationsDone: {
call: schemas.MarkNotificationsDone,
response: schemas.MarkNotificationsResponse,
@@ -422,10 +460,15 @@ type ToolDataMap = {
call: types.BulkSetEntityPropertyOptions;
response: types.BulkSetEntityPropertyOptionsResponse;
};
+ ConfigureBot: {
+ call: types.ConfigureBot;
+ response: types.ConfigureBotResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
response: types.UserToolResponseForToolCalendarEvent;
@@ -444,6 +487,7 @@ type ToolDataMap = {
};
CreateReminder: { call: types.CreateReminder; response: types.ToolReminder };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
+ DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };
DeleteCalendarEvent: {
call: types.DeleteCalendarEvent;
response: types.DeleteCalendarEventResponse;
@@ -466,6 +510,10 @@ type ToolDataMap = {
response: types.EditDocumentResponse;
};
EditTag: { call: types.EditTag; response: types.EditTagResponse };
+ GetBotWebhooks: {
+ call: types.GetBotWebhooks;
+ response: types.GetBotWebhooksResponse;
+ };
GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };
GetEntityProperties: {
call: types.GetEntityProperties;
@@ -476,6 +524,11 @@ type ToolDataMap = {
call: types.ImportNotionPage;
response: types.ImportNotionPageResponse;
};
+ IssueBotCredential: {
+ call: types.IssueBotCredential;
+ response: types.IssueBotCredentialResponse;
+ };
+ ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
response: types.ListCalendarEventsResponse;
@@ -513,6 +566,10 @@ type ToolDataMap = {
response: types.ListTeamMembersResponse;
};
LoadTools: { call: types.LoadTools; response: types.LoadToolsResponse };
+ ManageBotChannelAccess: {
+ call: types.ManageBotChannelAccess;
+ response: types.ManageBotChannelAccessResponse;
+ };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
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 72c4cf7431..8eb179a3cf 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
@@ -41,6 +41,24 @@ export type ToolPropertyTargetEntityType =
| 'call'
| 'user'
| 'company';
+/**
+ * Ownership scope of a manageable bot.
+ */
+export type BotOwnerSummary =
+ | {
+ /**
+ * Macro user id of the owner.
+ */
+ user_id: string;
+ type: 'user';
+ }
+ | {
+ /**
+ * Team id of the owner.
+ */
+ team_id: string;
+ type: 'team';
+ };
/**
* How search tools match query terms. Restricted to partial/exact — the
* backend also supports regexp and an internal query mode, but those are not
@@ -445,6 +463,10 @@ export type NotificationEntityType =
| 'crm_contact'
| 'reminder'
| 'skill';
+/**
+ * Channel-access change to apply to a bot.
+ */
+export type BotChannelAccessAction = 'grant' | 'revoke';
/**
* The kind of entity to move.
*/
@@ -902,6 +924,75 @@ export interface BulkSetEntityPropertyOptionsResult {
*/
error?: string | null;
}
+/**
+ * Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle.
+ */
+export interface ConfigureBot {
+ /**
+ * Bot id from CreateBot or ListBots.
+ */
+ botId: string;
+ /**
+ * New display name. Omit to keep the current name.
+ */
+ name?: string | null;
+ /**
+ * New stable handle using lowercase ASCII letters, digits, hyphens, and underscores. Omit to keep the current handle.
+ */
+ handle?: string | null;
+ /**
+ * New bot description. Omit to keep the current value; pass an empty string to clear it.
+ */
+ description?: string | null;
+ /**
+ * New profile-picture URL. Use a Macro static-file URL or another reachable image URL. Omit to keep the current picture; pass an empty string to clear it.
+ */
+ avatarUrl?: string | null;
+ /**
+ * Set true if mentioning this bot should open a sandboxed coding-agent session. Omit to leave unchanged.
+ */
+ hasAgent?: boolean | null;
+}
+/**
+ * Response from [`ConfigureBot`].
+ */
+export interface ConfigureBotResponse {
+ bot: BotSummary;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
+/**
+ * High-signal bot details returned to AI agents.
+ */
+export interface BotSummary {
+ /**
+ * Bot id used by the other bot-management tools.
+ */
+ botId: string;
+ owner: BotOwnerSummary;
+ /**
+ * Display name.
+ */
+ name: string;
+ /**
+ * Stable mention handle.
+ */
+ handle: string;
+ /**
+ * Optional description.
+ */
+ description?: string | null;
+ /**
+ * Optional profile-picture URL.
+ */
+ avatarUrl?: string | null;
+ /**
+ * Whether mentioning this bot opens a sandboxed coding-agent session.
+ */
+ hasAgent: boolean;
+}
/**
* Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content 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. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts 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 content, 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 (e.g. an exact word, identifier, or full email address). 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 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).
*/
@@ -1448,6 +1539,108 @@ export interface CrmCompanySearchDomain {
*/
createdAt: string;
}
+/**
+ * Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
+ */
+export interface CreateBot {
+ /**
+ * Team id that should own the bot. Omit for a bot owned by the current user.
+ */
+ teamId?: string | null;
+ /**
+ * Human-readable display name for the bot.
+ */
+ name: string;
+ /**
+ * Stable mention handle using only lowercase ASCII letters, digits, hyphens, and underscores; maximum 64 characters.
+ */
+ handle: string;
+ /**
+ * Optional short description of what the bot does.
+ */
+ description?: string | null;
+ /**
+ * Optional URL for the bot profile picture. Pass the URL of an image already uploaded to Macro static files or another reachable image URL.
+ */
+ avatarUrl?: string | null;
+ /**
+ * Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL.
+ */
+ channelId?: string | null;
+ /**
+ * Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId.
+ */
+ credentialLabel?: string | null;
+ /**
+ * Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId.
+ */
+ credentialExpiresAt?: string | null;
+ /**
+ * Set true if mentioning this bot should open a sandboxed coding-agent session. Defaults to false.
+ */
+ hasAgent?: boolean | null;
+}
+/**
+ * Response from [`CreateBot`].
+ */
+export interface CreateBotResponse {
+ bot: BotSummary;
+ /**
+ * Credential and webhook returned when [`CreateBot::channel_id`] was set.
+ */
+ channelSetup?: CreatedBotChannelSetup | null;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
+/**
+ * One-time credential and webhook created with a channel-scoped bot.
+ */
+export interface CreatedBotChannelSetup {
+ /**
+ * Channel the bot can now post to.
+ */
+ channelId: string;
+ /**
+ * Token metadata id, used to revoke this credential through the bot API.
+ */
+ tokenId: string;
+ /**
+ * Raw bearer token. It is returned only when minted and must be stored securely.
+ */
+ bearerToken: string;
+ webhook: BotWebhook;
+ /**
+ * Header where callers send [`Self::bearer_token`].
+ */
+ credentialHeader: string;
+ /**
+ * Header where callers send [`Self::credential_scope`].
+ */
+ credentialScopeHeader: string;
+ /**
+ * Required scope value for the bot credential.
+ */
+ credentialScope: string;
+}
+/**
+ * One channel-specific webhook URL for a bot.
+ */
+export interface BotWebhook {
+ /**
+ * Channel id the webhook posts into.
+ */
+ channelId: string;
+ /**
+ * Channel display name, when present.
+ */
+ channelName?: string | null;
+ /**
+ * Public URL to POST webhook content to.
+ */
+ webhookUrl: string;
+}
/**
* Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call.
*
@@ -1888,6 +2081,32 @@ export interface CreateTagResponse {
*/
summary: string;
}
+/**
+ * Delete a bot the current user owns or a bot owned by a team they belong to. This removes the bot from every channel and disables its credentials and webhooks. The operation cannot be undone, so only use it after the user explicitly confirms deletion.
+ */
+export interface DeleteBot {
+ /**
+ * Bot id from ListBots.
+ */
+ botId: string;
+}
+/**
+ * Response from [`DeleteBot`].
+ */
+export interface DeleteBotResponse {
+ /**
+ * Deleted bot id.
+ */
+ botId: string;
+ /**
+ * Whether the bot was deleted.
+ */
+ deleted: boolean;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Delete an event from the user's calendar. The deletion is written to Google immediately and attendees are notified, so confirm with the user before deleting — it cannot be undone. Get the `eventId` from ListCalendarEvents.
*
@@ -2073,6 +2292,44 @@ export interface EditTagResponse {
*/
summary: string;
}
+/**
+ * Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
+ */
+export interface GetBotWebhooks {
+ /**
+ * Bot id from CreateBot or ListBots.
+ */
+ botId: string;
+}
+/**
+ * Response from [`GetBotWebhooks`].
+ */
+export interface GetBotWebhooksResponse {
+ /**
+ * Bot whose webhook URLs were requested.
+ */
+ botId: string;
+ /**
+ * Header where callers send a bearer token from [`super::IssueBotCredential`].
+ */
+ credentialHeader: string;
+ /**
+ * Header where callers send [`Self::credential_scope`].
+ */
+ credentialScopeHeader: string;
+ /**
+ * Required scope value for the bot credential.
+ */
+ credentialScope: string;
+ /**
+ * One webhook per channel where the bot currently has access.
+ */
+ webhooks: BotWebhook[];
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response.
*/
@@ -2425,6 +2682,69 @@ export interface ImportNotionPageResponse {
*/
message: string;
}
+/**
+ * Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once.
+ */
+export interface IssueBotCredential {
+ /**
+ * Bot id from CreateBot or ListBots.
+ */
+ botId: string;
+ /**
+ * Optional label describing where the credential will be used, such as `github-webhook`.
+ */
+ label?: string | null;
+ /**
+ * Optional RFC 3339 expiration timestamp. Omit for a credential without a scheduled expiration.
+ */
+ expiresAt?: string | null;
+}
+/**
+ * Response containing a newly issued bot credential.
+ */
+export interface IssueBotCredentialResponse {
+ /**
+ * Bot receiving the credential.
+ */
+ botId: string;
+ /**
+ * Token metadata id, used to revoke this credential through the bot API.
+ */
+ tokenId: string;
+ /**
+ * Raw bearer token. It is returned only when minted and must be stored securely.
+ */
+ bearerToken: string;
+ /**
+ * Optional credential label.
+ */
+ label?: string | null;
+ /**
+ * Optional expiration time.
+ */
+ expiresAt?: string | null;
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
+/**
+ * List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot.
+ */
+export type ListBots = {};
+/**
+ * Response from [`ListBots`].
+ */
+export interface ListBotsResponse {
+ /**
+ * Active bots the caller can manage.
+ */
+ bots: BotSummary[];
+ /**
+ * Human-readable result summary.
+ */
+ summary: string;
+}
/**
* List the user's calendar events between two instants, across every calendar they have connected. Returns one entry per occurrence (a recurring event appears once per instance in the window), soonest first, with the `eventId` needed by UpdateCalendarEvent and DeleteCalendarEvent.
*
@@ -3194,6 +3514,38 @@ export interface ToolMatch {
*/
description: string;
}
+/**
+ * Grant or revoke a manageable bot's access to one channel. Granting requires the current user to be a channel member. Both actions require the user to own the bot or belong to its owning team; revoking still works after the manager leaves the channel. Granting access creates that channel's webhook URL; revoking access disables posting to that channel. Use only after the user asks to change bot access.
+ */
+export interface ManageBotChannelAccess {
+ /**
+ * Bot id from CreateBot or ListBots.
+ */
+ botId: string;
+ /**
+ * Channel id to grant or revoke access to.
+ */
+ channelId: string;
+ action: BotChannelAccessAction;
+}
+/**
+ * Response from [`ManageBotChannelAccess`].
+ */
+export interface ManageBotChannelAccessResponse {
+ /**
+ * Bot whose channel access changed.
+ */
+ botId: string;
+ /**
+ * Affected channel.
+ */
+ channelId: string;
+ action: BotChannelAccessAction;
+ /**
+ * 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.
*/
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index bd84b9cfb5..6ac91929fb 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -20,6 +20,7 @@ bot_id = { path = "../bot_id" }
async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
+bots = { path = "../bots", default-features = false, features = ["ai_tools", "outbound"] }
calendar_events = { path = "../calendar_events", features = ["ai_tools", "mutation-client", "postgres"] }
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 5351a69d6d..36a0806f0d 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -417,6 +417,12 @@ pub async fn build_tool_service_context_from_env(
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
channel_tool_context,
+ bot_tool_context: crate::tool_context::build_bot_tool_context(
+ pool.clone(),
+ crate::tool_context::ToolBotEventBroker::Real(macro_event_broker.clone()),
+ entity_access_service.clone(),
+ document_storage_service_url,
+ ),
project_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 8f02dedc66..086247c40e 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -19,6 +19,7 @@ mod tool_context;
pub use anthropic::toolset::AnthropicToolContext;
use anthropic::toolset::anthropic_toolset;
+use bots::inbound::toolset::bot_toolset;
use calendar_events::inbound::toolset::{calendar_toolset, mcp_toolset as calendar_mcp_toolset};
use call::inbound::toolset::call_toolset;
use channels::inbound::toolset::channel_toolset;
@@ -50,19 +51,20 @@ pub use tool_context::no_op_schedule_context;
pub use tool_context::{
ChannelSideEffectClients, NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress,
NoOpNotificationService, NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties,
- RequestContext, TaskPropertiesAdapter, ToolActivityToolContext, ToolCalendarMutationService,
- ToolCalendarReadService, ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService,
- ToolCallToolContext, ToolChannelEventDispatcher, ToolChannelMessagesService,
- ToolChannelToolContext, ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService,
- ToolCrmToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,
- ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
- ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolImportService,
- ToolImportToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,
- ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,
- ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolRemindersService,
- ToolRemindersToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
- ToolSoupService, ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext,
- ToolUserEmailService, build_activity_tool_context, build_calendar_tool_context,
+ RequestContext, TaskPropertiesAdapter, ToolActivityToolContext, ToolBotEventBroker,
+ ToolBotService, ToolBotToolContext, ToolCalendarMutationService, ToolCalendarReadService,
+ ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,
+ ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,
+ ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,
+ ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,
+ ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,
+ ToolForeignEntityService, ToolFrecencyService, ToolImportService, ToolImportToolContext,
+ ToolMcpSelector, ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
+ ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,
+ ToolPropertiesToolContext, ToolRemindersService, ToolRemindersToolContext, ToolServiceContext,
+ ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,
+ ToolTeamService, ToolTeamToolContext, ToolUserEmailService, build_activity_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_crm_tool_context,
build_project_tool_context, build_properties_service, build_properties_tool_context,
@@ -99,6 +101,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
.add_subtoolset::<ToolCallToolContext>(call_toolset())
.add_subtoolset::<ToolChatToolContext>(chat_toolset())
.add_subtoolset::<ToolChannelToolContext>(channel_toolset())
+ .add_subtoolset::<ToolBotToolContext>(bot_toolset())
.add_subtoolset::<ToolTeamToolContext>(team_toolset())
.add_subtoolset::<ToolCrmToolContext>(crm_toolset())
.add_subtoolset::<ToolSkillToolContext>(skill_toolset())
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index a9da48bcd9..5209490aac 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1,5 +1,9 @@
use anthropic::toolset::AnthropicToolContext;
use axum::extract::FromRef;
+use bots::{
+ domain::service::BotServiceImpl, inbound::toolset::BotToolContext,
+ outbound::pg_bots_repo::PgBotsRepo,
+};
use calendar_events::inbound::toolset::CalendarToolContext;
use call::domain::models::{CallError, CallWebhookEvent, EgressS3Config};
use call::domain::ports::CallRtcClient;
@@ -35,7 +39,10 @@ use foreign_entity::{
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
};
use lexical_mention_extractor::LexicalMentionExtractor;
-use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
+use macro_event_broker::{
+ EventBrokerError, KafkaEventPublisher, MacroEvent, MacroEventBroker, MacroEventBrokerService,
+ NoopMacroEventBroker,
+};
use macro_user_id::user_id::MacroUserIdStr;
use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
@@ -92,6 +99,51 @@ pub type ToolEmailService = EmailServiceImpl<
/// graceful shutdown by the hosting process.
pub type ToolEventBroker = MacroEventBrokerService<KafkaEventPublisher, TaskTracker>;
+/// Event broker used by bot tools across hosts that either do or do not have
+/// Kafka lifecycle publishing configured.
+#[derive(Clone)]
+pub enum ToolBotEventBroker {
+ /// Publish bot lifecycle events through the shared Kafka broker.
+ Real(ToolEventBroker),
+ /// Drop lifecycle events in hosts that do not configure Kafka.
+ NoOp(NoopMacroEventBroker),
+}
+
+impl MacroEventBroker for ToolBotEventBroker {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
+ match self {
+ Self::Real(broker) => broker.send_event(event),
+ Self::NoOp(broker) => broker.send_event(event),
+ }
+ }
+}
+
+/// Concrete bot domain service used by AI tools.
+pub type ToolBotService = BotServiceImpl<PgBotsRepo, ToolBotEventBroker>;
+
+/// Bot-management AI tool context.
+pub type ToolBotToolContext = BotToolContext<ToolBotService, ToolEntityAccessService>;
+
+/// Build bot-management tools over the canonical Postgres repository and
+/// entity-access service.
+pub fn build_bot_tool_context(
+ pool: sqlx::PgPool,
+ event_broker: ToolBotEventBroker,
+ entity_access_service: Arc<ToolEntityAccessService>,
+ document_storage_service_url: String,
+) -> ToolBotToolContext {
+ BotToolContext {
+ service: Arc::new(BotServiceImpl::new(PgBotsRepo::new(pool), event_broker)),
+ entity_access_service,
+ document_storage_service_url: document_storage_service_url
+ .trim_end_matches('/')
+ .to_string(),
+ }
+}
+
/// Type alias for the send-capable email service implementation used by user
/// tools. Carries the real event broker: these tools mutate email state, and
/// the Gmail-echo suppression means events skipped here are never recovered.
@@ -1238,6 +1290,7 @@ pub struct ToolServiceContext {
#[from_ref(skip)]
pub chat_tool_context: ToolChatToolContext,
pub channel_tool_context: ToolChannelToolContext,
+ pub bot_tool_context: ToolBotToolContext,
pub project_tool_context: ToolProjectToolContext,
pub team_tool_context: ToolTeamToolContext,
pub crm_tool_context: ToolCrmToolContext,
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index e50af8204f..8faeb66823 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -5,6 +5,14 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai_toolset",
+ "dep:async-trait",
+ "dep:entity_access",
+ "dep:schemars",
+ "entity_access/ports",
+ "ports",
+]
default = ["inbound", "outbound", "ports"]
inbound = [
"dep:axum",
@@ -20,11 +28,13 @@ inbound = [
"ports",
]
outbound = ["dep:sqlx", "dep:macro_uuid", "ports"]
-ports = ["dep:tokio"]
+ports = ["dep:entity_access", "entity_access/ports", "dep:tokio"]
test-utils = ["dep:mockall", "ports"]
[dependencies]
+ai_toolset = { path = "../ai_toolset", optional = true }
anyhow = { workspace = true }
+async-trait = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
bot_id = { path = "../bot_id", features = ["schema"] }
channels = { path = "../channels", optional = true, default-features = false, features = ["ports"] }
@@ -39,6 +49,7 @@ macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
rand = { workspace = true }
+schemars = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index b3cb06ad5c..4107c90e67 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -5,6 +5,7 @@ use super::models::{
BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,
CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,
};
+use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};
use macro_user_id::user_id::MacroUserIdStr;
use std::future::Future;
use uuid::Uuid;
@@ -191,8 +192,7 @@ pub trait BotService: Send + Sync + 'static {
/// Add an owned/team-available bot to a channel.
fn add_bot_to_channel(
&self,
- caller: MacroUserIdStr<'static>,
- channel_id: Uuid,
+ access: EntityAccessReceipt<MemberParticipantRole>,
bot_id: BotId,
) -> impl Future<Output = Result<(), BotError>> + Send;
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index 602c1e5ce0..c8778d9a81 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -11,6 +11,7 @@ use super::{
tokens,
};
use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, MemberParticipantRole};
use macro_event_broker::MacroEventBroker;
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
@@ -308,10 +309,20 @@ where
async fn add_bot_to_channel(
&self,
- caller: MacroUserIdStr<'static>,
- channel_id: Uuid,
+ access: EntityAccessReceipt<MemberParticipantRole>,
bot_id: BotId,
) -> Result<(), BotError> {
+ if access.entity().entity_type != EntityType::Channel {
+ return Err(BotError::BadRequest(
+ "channel access receipt required".to_string(),
+ ));
+ }
+ let channel_id = Uuid::parse_str(&access.entity().entity_id)
+ .map_err(|error| BotError::BadRequest(error.to_string()))?;
+ let caller = access
+ .get_authenticated_user()
+ .cloned()
+ .map_err(|_| BotError::Unauthorized)?;
self.ensure_manageable(caller, bot_id).await?;
self.repo
.add_bot_to_channel(channel_id, bot_id)
diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rs
index d9ca0dad6d..7e502f1025 100644
--- a/crates/bots/src/inbound/axum_router.rs
+++ b/crates/bots/src/inbound/axum_router.rs
@@ -445,13 +445,12 @@ async fn add_channel_bot_handler<
>(
State(state): State<BotsRouterState<S, Svc, Auth>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
- Path(path): Path<ChannelPath>,
+ Path(_path): Path<ChannelPath>,
Json(req): Json<AddChannelBotRequest>,
) -> Result<StatusCode, BotsHandlerErr> {
- let caller = caller_from_receipt(&access.entity_access_receipt)?;
state
.service
- .add_bot_to_channel(caller, path.channel_id, req.bot_id)
+ .add_bot_to_channel(access.entity_access_receipt, req.bot_id)
.await?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index e5a3a61307..e732a10a74 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -11,8 +11,9 @@ use axum::{
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityPermission,
- EntityType, ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole,
+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -150,8 +151,7 @@ impl BotService for TestBotService {
async fn add_bot_to_channel(
&self,
- _caller: MacroUserIdStr<'static>,
- _channel_id: Uuid,
+ _access: EntityAccessReceipt<MemberParticipantRole>,
_bot_id: BotId,
) -> Result<(), BotError> {
self.add_calls.fetch_add(1, Ordering::SeqCst);
@@ -832,7 +832,20 @@ async fn bot_owner_can_list_and_remove_bot_channels_via_bot_routes(
.await?;
bot_service
- .add_bot_to_channel(macro_user_id(BOT_OWNER_ID), channel_id, bot.id)
+ .add_bot_to_channel(
+ EntityAccessReceipt::try_new_authenticated_user(
+ macro_user_id(BOT_OWNER_ID),
+ Entity {
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ },
+ EntityPermission::ChannelRole {
+ role: EntityParticipantRole::Member,
+ },
+ )
+ .expect("member role satisfies channel membership"),
+ bot.id,
+ )
.await?;
let bot_principal_id = bot.id.into_storage_id().to_string();
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index db7ba20d55..c4de817657 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -12,8 +12,9 @@ use channels::domain::models::PostMessageResponse;
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityPermission,
- EntityType, ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberParticipantRole,
+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -210,8 +211,7 @@ impl BotService for TestBotService {
async fn add_bot_to_channel(
&self,
- _caller: MacroUserIdStr<'static>,
- _channel_id: Uuid,
+ _access: EntityAccessReceipt<MemberParticipantRole>,
_bot_id: BotId,
) -> Result<(), BotError> {
unimplemented!()
diff --git a/crates/bots/src/inbound/mod.rs b/crates/bots/src/inbound/mod.rs
index a114ce8b63..b9b0dc8511 100644
--- a/crates/bots/src/inbound/mod.rs
+++ b/crates/bots/src/inbound/mod.rs
@@ -1,6 +1,11 @@
-//! Inbound HTTP adapters for bots.
+//! Inbound HTTP and AI-tool adapters for bots.
+#[cfg(feature = "inbound")]
/// Axum router for bot management.
pub mod axum_router;
+#[cfg(feature = "inbound")]
/// Axum router for channel-scoped bot webhooks.
pub mod channel_webhook_router;
+#[cfg(feature = "ai_tools")]
+/// AI tools for managing bots.
+pub mod toolset;
diff --git a/crates/bots/src/inbound/toolset/configure_bot.rs b/crates/bots/src/inbound/toolset/configure_bot.rs
new file mode 100644
index 0000000000..8ae530a03d
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/configure_bot.rs
@@ -0,0 +1,111 @@
+//! ConfigureBot tool.
+
+use super::{BotSummary, BotToolContext, bot_tool_error};
+use crate::domain::{
+ models::{BotId, PatchBotRequest},
+ ports::BotService,
+};
+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 [`ConfigureBot`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ConfigureBotResponse {
+ /// Updated bot profile.
+ pub bot: BotSummary,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Update a bot's display profile and stable handle.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ConfigureBot",
+ description = "Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle."
+)]
+pub struct ConfigureBot {
+ /// Bot to configure.
+ #[schemars(description = "Bot id from CreateBot or ListBots.")]
+ pub bot_id: Uuid,
+ /// Optional replacement display name.
+ #[schemars(description = "New display name. Omit to keep the current name.")]
+ #[serde(default)]
+ pub name: Option<String>,
+ /// Optional replacement handle.
+ #[schemars(
+ description = "New stable handle using lowercase ASCII letters, digits, hyphens, and underscores. Omit to keep the current handle."
+ )]
+ #[serde(default)]
+ pub handle: Option<String>,
+ /// Optional replacement description.
+ #[schemars(
+ description = "New bot description. Omit to keep the current value; pass an empty string to clear it."
+ )]
+ #[serde(default)]
+ pub description: Option<String>,
+ /// Optional replacement profile-picture URL.
+ #[schemars(
+ description = "New profile-picture URL. Use a Macro static-file URL or another reachable image URL. Omit to keep the current picture; pass an empty string to clear it."
+ )]
+ #[serde(default)]
+ pub avatar_url: Option<String>,
+ /// Optional coding-agent session flag.
+ #[schemars(
+ description = "Set true if mentioning this bot should open a sandboxed coding-agent session. Omit to leave unchanged."
+ )]
+ #[serde(default)]
+ pub has_agent: Option<bool>,
+}
+
+impl ToolAnnotated for ConfigureBot {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Configure bot");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for ConfigureBot
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ConfigureBotResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, bot_id=%self.bot_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let bot = BotSummary::try_from(
+ service_context
+ .service
+ .patch_bot(
+ request_context.user_id,
+ BotId::new_from_uuid(self.bot_id),
+ PatchBotRequest {
+ name: self.name.clone(),
+ handle: self.handle.clone(),
+ description: self.description.clone(),
+ avatar_url: self.avatar_url.clone(),
+ has_agent: self.has_agent,
+ },
+ )
+ .await
+ .map_err(|error| bot_tool_error("configure bot", error))?,
+ )?;
+ let summary = format!("Updated bot @{}.", bot.handle);
+
+ Ok(ConfigureBotResponse { bot, summary })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/create_bot.rs b/crates/bots/src/inbound/toolset/create_bot.rs
new file mode 100644
index 0000000000..f83df6b9de
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/create_bot.rs
@@ -0,0 +1,220 @@
+//! CreateBot tool.
+
+use super::{
+ BOT_WEBHOOK_SCOPE, BOT_WEBHOOK_SCOPE_HEADER, BOT_WEBHOOK_TOKEN_HEADER, BotSummary,
+ BotToolContext, BotWebhook, CreatedBotChannelSetup, bot_tool_error,
+};
+use crate::domain::{
+ models::{CreateBotRequest, CreateChannelScopedBotRequest},
+ ports::BotService,
+};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Response from [`CreateBot`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateBotResponse {
+ /// Newly created bot.
+ pub bot: BotSummary,
+ /// Credential and webhook returned when [`CreateBot::channel_id`] was set.
+ pub channel_setup: Option<CreatedBotChannelSetup>,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Create a user- or team-owned bot, optionally ready to post in one channel.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateBot",
+ description = "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
+)]
+pub struct CreateBot {
+ /// Team owner; omit for a user-owned bot.
+ #[schemars(
+ description = "Team id that should own the bot. Omit for a bot owned by the current user."
+ )]
+ #[serde(default)]
+ pub team_id: Option<Uuid>,
+ /// Bot display name.
+ #[schemars(description = "Human-readable display name for the bot.")]
+ pub name: String,
+ /// Stable lowercase handle.
+ #[schemars(
+ description = "Stable mention handle using only lowercase ASCII letters, digits, hyphens, and underscores; maximum 64 characters."
+ )]
+ pub handle: String,
+ /// Optional bot description.
+ #[schemars(description = "Optional short description of what the bot does.")]
+ #[serde(default)]
+ pub description: Option<String>,
+ /// Optional profile-picture URL.
+ #[schemars(
+ description = "Optional URL for the bot profile picture. Pass the URL of an image already uploaded to Macro static files or another reachable image URL."
+ )]
+ #[serde(default)]
+ pub avatar_url: Option<String>,
+ /// Optional channel to grant immediately.
+ #[schemars(
+ description = "Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL."
+ )]
+ #[serde(default)]
+ pub channel_id: Option<Uuid>,
+ /// Optional credential label used only with [`Self::channel_id`].
+ #[schemars(
+ description = "Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId."
+ )]
+ #[serde(default)]
+ pub credential_label: Option<String>,
+ /// Optional credential expiry used only with [`Self::channel_id`].
+ #[schemars(
+ description = "Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId."
+ )]
+ #[serde(default)]
+ pub credential_expires_at: Option<DateTime<Utc>>,
+ /// Optional coding-agent session flag.
+ #[schemars(
+ description = "Set true if mentioning this bot should open a sandboxed coding-agent session. Defaults to false."
+ )]
+ #[serde(default)]
+ pub has_agent: Option<bool>,
+}
+
+impl ToolAnnotated for CreateBot {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create bot");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for CreateBot
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = CreateBotResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.channel_id.is_none()
+ && (self.credential_label.is_some() || self.credential_expires_at.is_some())
+ {
+ return Err(ToolCallError {
+ description: "credentialLabel and credentialExpiresAt require channelId. Pass channelId to create a channel-ready bot, or omit those fields to create the bot only.".to_string(),
+ internal_error: anyhow::anyhow!("credential fields without channel_id"),
+ });
+ }
+
+ match self.channel_id {
+ Some(channel_id) => {
+ self.create_for_channel(service_context, request_context, channel_id)
+ .await
+ }
+ None => {
+ self.create_standalone(service_context, request_context)
+ .await
+ }
+ }
+ }
+}
+
+impl CreateBot {
+ async fn create_standalone<Svc, AccessSvc>(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<CreateBotResponse>
+ where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+ {
+ let bot: BotSummary = service_context
+ .service
+ .create_bot(
+ request_context.user_id,
+ CreateBotRequest {
+ team_id: self.team_id,
+ name: self.name.clone(),
+ handle: self.handle.clone(),
+ description: self.description.clone(),
+ avatar_url: self.avatar_url.clone(),
+ has_agent: self.has_agent,
+ },
+ )
+ .await
+ .map_err(|error| bot_tool_error("create bot", error))?
+ .try_into()?;
+ let summary = format!("Created bot @{}.", bot.handle);
+
+ Ok(CreateBotResponse {
+ bot,
+ channel_setup: None,
+ summary,
+ })
+ }
+
+ async fn create_for_channel<Svc, AccessSvc>(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ channel_id: Uuid,
+ ) -> ToolResult<CreateBotResponse>
+ where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+ {
+ service_context
+ .require_channel_member(&request_context, channel_id)
+ .await?;
+ let created = service_context
+ .service
+ .create_channel_scoped_bot(
+ request_context.user_id,
+ channel_id,
+ CreateChannelScopedBotRequest {
+ team_id: self.team_id,
+ name: self.name.clone(),
+ handle: self.handle.clone(),
+ description: self.description.clone(),
+ avatar_url: self.avatar_url.clone(),
+ token_label: self.credential_label.clone(),
+ token_expires_at: self.credential_expires_at,
+ has_agent: self.has_agent,
+ },
+ )
+ .await
+ .map_err(|error| bot_tool_error("create bot", error))?;
+ let bot = BotSummary::try_from(created.bot)?;
+ let webhook =
+ BotWebhook::for_channel(&service_context.document_storage_service_url, channel_id);
+ let summary = format!(
+ "Created bot @{} and granted it access to the channel. Store the bearer token securely; it will not be shown again.",
+ bot.handle
+ );
+
+ Ok(CreateBotResponse {
+ bot,
+ channel_setup: Some(CreatedBotChannelSetup {
+ channel_id,
+ token_id: created.token.id,
+ bearer_token: created.bot_token,
+ webhook,
+ credential_header: BOT_WEBHOOK_TOKEN_HEADER.to_string(),
+ credential_scope_header: BOT_WEBHOOK_SCOPE_HEADER.to_string(),
+ credential_scope: BOT_WEBHOOK_SCOPE.to_string(),
+ }),
+ summary,
+ })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/delete_bot.rs b/crates/bots/src/inbound/toolset/delete_bot.rs
new file mode 100644
index 0000000000..29139f247f
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/delete_bot.rs
@@ -0,0 +1,73 @@
+//! DeleteBot tool.
+
+use super::{BotToolContext, bot_tool_error};
+use crate::domain::{models::BotId, ports::BotService};
+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 [`DeleteBot`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteBotResponse {
+ /// Deleted bot id.
+ pub bot_id: Uuid,
+ /// Whether the bot was deleted.
+ pub deleted: bool,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Permanently disable and remove a manageable bot.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteBot",
+ description = "Delete a bot the current user owns or a bot owned by a team they belong to. This removes the bot from every channel and disables its credentials and webhooks. The operation cannot be undone, so only use it after the user explicitly confirms deletion."
+)]
+pub struct DeleteBot {
+ /// Bot to delete.
+ #[schemars(description = "Bot id from ListBots.")]
+ pub bot_id: Uuid,
+}
+
+impl ToolAnnotated for DeleteBot {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Delete bot");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for DeleteBot
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = DeleteBotResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, bot_id=%self.bot_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ service_context
+ .service
+ .delete_bot(request_context.user_id, BotId::new_from_uuid(self.bot_id))
+ .await
+ .map_err(|error| bot_tool_error("delete bot", error))?;
+
+ Ok(DeleteBotResponse {
+ bot_id: self.bot_id,
+ deleted: true,
+ summary: "Deleted the bot and disabled its credentials and webhooks.".to_string(),
+ })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/get_bot_webhooks.rs b/crates/bots/src/inbound/toolset/get_bot_webhooks.rs
new file mode 100644
index 0000000000..d8e7fdc2a3
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/get_bot_webhooks.rs
@@ -0,0 +1,108 @@
+//! GetBotWebhooks tool.
+
+use super::{
+ BOT_WEBHOOK_SCOPE, BOT_WEBHOOK_SCOPE_HEADER, BOT_WEBHOOK_TOKEN_HEADER, BotToolContext,
+ BotWebhook, bot_tool_error,
+};
+use crate::domain::{
+ models::{BotChannelListCaller, BotId},
+ ports::BotService,
+};
+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 [`GetBotWebhooks`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GetBotWebhooksResponse {
+ /// Bot whose webhook URLs were requested.
+ pub bot_id: Uuid,
+ /// Header where callers send a bearer token from [`super::IssueBotCredential`].
+ pub credential_header: String,
+ /// Header where callers send [`Self::credential_scope`].
+ pub credential_scope_header: String,
+ /// Required scope value for the bot credential.
+ pub credential_scope: String,
+ /// One webhook per channel where the bot currently has access.
+ pub webhooks: Vec<BotWebhook>,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Get every channel webhook URL currently available to a bot.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "GetBotWebhooks",
+ description = "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
+)]
+pub struct GetBotWebhooks {
+ /// Bot to inspect.
+ #[schemars(description = "Bot id from CreateBot or ListBots.")]
+ pub bot_id: Uuid,
+}
+
+impl ToolAnnotated for GetBotWebhooks {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Get bot webhooks");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for GetBotWebhooks
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = GetBotWebhooksResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, bot_id=%self.bot_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let channels = service_context
+ .service
+ .list_bot_channels(
+ BotChannelListCaller::User(request_context.user_id),
+ BotId::new_from_uuid(self.bot_id),
+ )
+ .await
+ .map_err(|error| bot_tool_error("get bot webhooks", error))?;
+ let webhooks: Vec<BotWebhook> = channels
+ .into_iter()
+ .map(|channel| BotWebhook {
+ channel_id: channel.channel_id,
+ channel_name: channel.name,
+ webhook_url: BotWebhook::for_channel(
+ &service_context.document_storage_service_url,
+ channel.channel_id,
+ )
+ .webhook_url,
+ })
+ .collect();
+ let summary = match webhooks.len() {
+ 0 => "This bot has no channel webhooks. Add it to a channel first.".to_string(),
+ 1 => "Found 1 channel webhook.".to_string(),
+ count => format!("Found {count} channel webhooks."),
+ };
+
+ Ok(GetBotWebhooksResponse {
+ bot_id: self.bot_id,
+ credential_header: BOT_WEBHOOK_TOKEN_HEADER.to_string(),
+ credential_scope_header: BOT_WEBHOOK_SCOPE_HEADER.to_string(),
+ credential_scope: BOT_WEBHOOK_SCOPE.to_string(),
+ webhooks,
+ summary,
+ })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/issue_bot_credential.rs b/crates/bots/src/inbound/toolset/issue_bot_credential.rs
new file mode 100644
index 0000000000..300c1549df
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/issue_bot_credential.rs
@@ -0,0 +1,106 @@
+//! IssueBotCredential tool.
+
+use super::{BotToolContext, bot_tool_error};
+use crate::domain::{
+ models::{BotId, CreateBotTokenRequest},
+ ports::BotService,
+};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Response containing a newly issued bot credential.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct IssueBotCredentialResponse {
+ /// Bot receiving the credential.
+ pub bot_id: Uuid,
+ /// Token metadata id, used to revoke this credential through the bot API.
+ pub token_id: Uuid,
+ /// Raw bearer token. It is returned only when minted and must be stored securely.
+ pub bearer_token: String,
+ /// Optional credential label.
+ pub label: Option<String>,
+ /// Optional expiration time.
+ pub expires_at: Option<DateTime<Utc>>,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Mint a new secret credential for a manageable bot.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "IssueBotCredential",
+ description = "Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once."
+)]
+pub struct IssueBotCredential {
+ /// Bot to issue a credential for.
+ #[schemars(description = "Bot id from CreateBot or ListBots.")]
+ pub bot_id: Uuid,
+ /// Optional identifying label.
+ #[schemars(
+ description = "Optional label describing where the credential will be used, such as `github-webhook`."
+ )]
+ #[serde(default)]
+ pub label: Option<String>,
+ /// Optional expiry.
+ #[schemars(
+ description = "Optional RFC 3339 expiration timestamp. Omit for a credential without a scheduled expiration."
+ )]
+ #[serde(default)]
+ pub expires_at: Option<DateTime<Utc>>,
+}
+
+impl ToolAnnotated for IssueBotCredential {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Issue bot credential");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for IssueBotCredential
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = IssueBotCredentialResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(user_id=?request_context.user_id, bot_id=%self.bot_id),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let response = service_context
+ .service
+ .create_token(
+ request_context.user_id,
+ BotId::new_from_uuid(self.bot_id),
+ CreateBotTokenRequest {
+ label: self.label.clone(),
+ expires_at: self.expires_at,
+ },
+ )
+ .await
+ .map_err(|error| bot_tool_error("issue bot credential", error))?;
+
+ Ok(IssueBotCredentialResponse {
+ bot_id: self.bot_id,
+ token_id: response.token.id,
+ bearer_token: response.bearer_token,
+ label: response.token.label,
+ expires_at: response.token.expires_at,
+ summary: "Issued a new bot credential. Store the bearer token securely; it will not be shown again."
+ .to_string(),
+ })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/list_bots.rs b/crates/bots/src/inbound/toolset/list_bots.rs
new file mode 100644
index 0000000000..ce73e1a3ee
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/list_bots.rs
@@ -0,0 +1,65 @@
+//! ListBots tool.
+
+use super::{BotSummary, BotToolContext, bot_tool_error};
+use crate::domain::ports::BotService;
+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};
+
+/// Response from [`ListBots`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListBotsResponse {
+ /// Active bots the caller can manage.
+ pub bots: Vec<BotSummary>,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// List bots owned by the user or by teams they belong to.
+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
+#[schemars(
+ title = "ListBots",
+ description = "List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot."
+)]
+pub struct ListBots {}
+
+impl ToolAnnotated for ListBots {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List bots");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for ListBots
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ListBotsResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let bots: Vec<BotSummary> = service_context
+ .service
+ .list_bots(request_context.user_id)
+ .await
+ .map_err(|error| bot_tool_error("list bots", error))?
+ .into_iter()
+ .map(BotSummary::try_from)
+ .collect::<Result<Vec<_>, _>>()?;
+ let summary = match bots.len() {
+ 0 => "No manageable bots found.".to_string(),
+ 1 => "Found 1 manageable bot.".to_string(),
+ count => format!("Found {count} manageable bots."),
+ };
+
+ Ok(ListBotsResponse { bots, summary })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/manage_bot_channel_access.rs b/crates/bots/src/inbound/toolset/manage_bot_channel_access.rs
new file mode 100644
index 0000000000..21bdaf950d
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/manage_bot_channel_access.rs
@@ -0,0 +1,114 @@
+//! ManageBotChannelAccess tool.
+
+use super::{BotToolContext, bot_tool_error};
+use crate::domain::{models::BotId, ports::BotService};
+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;
+
+/// Channel-access change to apply to a bot.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum BotChannelAccessAction {
+ /// Add the bot to the channel.
+ Grant,
+ /// Remove the bot from the channel.
+ Revoke,
+}
+
+/// Response from [`ManageBotChannelAccess`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ManageBotChannelAccessResponse {
+ /// Bot whose channel access changed.
+ pub bot_id: Uuid,
+ /// Affected channel.
+ pub channel_id: Uuid,
+ /// Applied access change.
+ pub action: BotChannelAccessAction,
+ /// Human-readable result summary.
+ pub summary: String,
+}
+
+/// Grant or revoke a bot's access to one channel.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ManageBotChannelAccess",
+ description = "Grant or revoke a manageable bot's access to one channel. Granting requires the current user to be a channel member. Both actions require the user to own the bot or belong to its owning team; revoking still works after the manager leaves the channel. Granting access creates that channel's webhook URL; revoking access disables posting to that channel. Use only after the user asks to change bot access."
+)]
+pub struct ManageBotChannelAccess {
+ /// Bot to add or remove.
+ #[schemars(description = "Bot id from CreateBot or ListBots.")]
+ pub bot_id: Uuid,
+ /// Channel whose bot access should change.
+ #[schemars(description = "Channel id to grant or revoke access to.")]
+ pub channel_id: Uuid,
+ /// Access change.
+ #[schemars(description = "Use `grant` to add the bot or `revoke` to remove it.")]
+ pub action: BotChannelAccessAction,
+}
+
+impl ToolAnnotated for ManageBotChannelAccess {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Manage bot channel access");
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for ManageBotChannelAccess
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ManageBotChannelAccessResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(
+ user_id=?request_context.user_id,
+ bot_id=%self.bot_id,
+ channel_id=%self.channel_id,
+ action=?self.action
+ ),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let bot_id = BotId::new_from_uuid(self.bot_id);
+ let summary = match self.action {
+ BotChannelAccessAction::Grant => {
+ let access = service_context
+ .require_channel_member(&request_context, self.channel_id)
+ .await?;
+ service_context
+ .service
+ .add_bot_to_channel(access, bot_id)
+ .await
+ .map_err(|error| bot_tool_error("grant bot channel access", error))?;
+ "Granted the bot access to the channel.".to_string()
+ }
+ BotChannelAccessAction::Revoke => {
+ service_context
+ .service
+ .remove_bot_from_channel(request_context.user_id, self.channel_id, bot_id)
+ .await
+ .map_err(|error| bot_tool_error("revoke bot channel access", error))?;
+ "Revoked the bot's access to the channel.".to_string()
+ }
+ };
+
+ Ok(ManageBotChannelAccessResponse {
+ bot_id: self.bot_id,
+ channel_id: self.channel_id,
+ action: self.action,
+ summary,
+ })
+ }
+}
diff --git a/crates/bots/src/inbound/toolset/mod.rs b/crates/bots/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..e9274dc535
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/mod.rs
@@ -0,0 +1,149 @@
+//! AI tools for bot management.
+
+mod configure_bot;
+mod create_bot;
+mod delete_bot;
+mod get_bot_webhooks;
+mod issue_bot_credential;
+mod list_bots;
+mod manage_bot_channel_access;
+mod types;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::ports::{BotError, BotService};
+use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
+use configure_bot::ConfigureBot;
+use create_bot::CreateBot;
+use delete_bot::DeleteBot;
+use entity_access::domain::{
+ models::{AccessError, EntityAccessReceipt, EntityType, MemberParticipantRole},
+ ports::EntityAccessService,
+};
+use get_bot_webhooks::GetBotWebhooks;
+use issue_bot_credential::IssueBotCredential;
+use list_bots::ListBots;
+use manage_bot_channel_access::ManageBotChannelAccess;
+use std::sync::Arc;
+use uuid::Uuid;
+
+pub use types::{
+ BOT_WEBHOOK_SCOPE, BOT_WEBHOOK_SCOPE_HEADER, BOT_WEBHOOK_TOKEN_HEADER, BotOwnerSummary,
+ BotSummary, BotWebhook, CreatedBotChannelSetup,
+};
+
+/// Dependencies shared by bot-management AI tools.
+pub struct BotToolContext<Svc, AccessSvc>
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ /// Bot domain service. Ownership and team-administration policy live here.
+ pub service: Arc<Svc>,
+ /// Entity access service used to verify channel membership at the edge.
+ pub entity_access_service: Arc<AccessSvc>,
+ /// Public document-storage service base URL used to construct webhook URLs.
+ pub document_storage_service_url: String,
+}
+
+impl<Svc, AccessSvc> Clone for BotToolContext<Svc, AccessSvc>
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ document_storage_service_url: self.document_storage_service_url.clone(),
+ }
+ }
+}
+
+impl<Svc, AccessSvc> BotToolContext<Svc, AccessSvc>
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ /// Create a bot tool context.
+ pub fn new(
+ service: Svc,
+ entity_access_service: AccessSvc,
+ document_storage_service_url: String,
+ ) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access_service: Arc::new(entity_access_service),
+ document_storage_service_url: document_storage_service_url
+ .trim_end_matches('/')
+ .to_string(),
+ }
+ }
+
+ /// Verify that the request user is an active member of a channel.
+ pub async fn require_channel_member(
+ &self,
+ request_context: &RequestContext,
+ channel_id: Uuid,
+ ) -> Result<EntityAccessReceipt<MemberParticipantRole>, ToolCallError> {
+ self.entity_access_service
+ .generate_entity_access_receipt::<MemberParticipantRole>(
+ &request_context.user_id,
+ None,
+ &channel_id.to_string(),
+ EntityType::Channel,
+ )
+ .await
+ .map_err(channel_access_error)
+ }
+}
+
+fn channel_access_error(error: AccessError) -> ToolCallError {
+ let description = match error {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ "you must be a member of the channel to manage its bots"
+ }
+ AccessError::NotFound(_) => "channel not found",
+ AccessError::BadRequest(_) => "invalid channel id",
+ AccessError::DatabaseError(_) | AccessError::Internal => {
+ "failed to verify channel membership"
+ }
+ };
+
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: error.into(),
+ }
+}
+
+fn bot_tool_error(action: &'static str, error: BotError) -> ToolCallError {
+ let description = match &error {
+ BotError::BadRequest(message) | BotError::NotFound(message) => message.clone(),
+ BotError::Unauthorized => {
+ "you do not have permission to manage this bot or its owning team".to_string()
+ }
+ BotError::Repo(_) => format!("failed to {action}"),
+ };
+
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
+/// Create the bot-management AI toolset.
+pub fn bot_toolset<Svc, AccessSvc>() -> AsyncToolCollection<BotToolContext<Svc, AccessSvc>>
+where
+ Svc: BotService,
+ AccessSvc: EntityAccessService,
+{
+ AsyncToolCollection::new()
+ .add_tool::<ListBots, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<CreateBot, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<IssueBotCredential, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<GetBotWebhooks, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<ManageBotChannelAccess, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<ConfigureBot, BotToolContext<Svc, AccessSvc>>()
+ .add_tool::<DeleteBot, BotToolContext<Svc, AccessSvc>>()
+}
diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..a8e04743d4
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/test.rs
@@ -0,0 +1,575 @@
+use super::{
+ BotOwnerSummary, BotSummary, BotToolContext, bot_tool_error,
+ create_bot::CreateBot,
+ get_bot_webhooks::GetBotWebhooks,
+ manage_bot_channel_access::{BotChannelAccessAction, ManageBotChannelAccess},
+};
+use crate::domain::models::{
+ AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotToken, CreateBotRequest,
+ CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,
+ CreateChannelScopedBotResponse, PatchBotRequest,
+};
+use crate::domain::{
+ models::{Bot, BotKind, BotOwner},
+ ports::{BotError, BotService},
+};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
+use bot_id::BotId;
+use chrono::Utc;
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, BotAccessScope, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberParticipantRole, 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")
+}
+
+fn sample_bot(handle: &str) -> Bot {
+ let now = Utc::now();
+ Bot {
+ id: BotId::new_from_uuid(Uuid::new_v4()),
+ kind: BotKind::Owned,
+ owner: Some(BotOwner::User {
+ user_id: TEST_USER_ID.to_string(),
+ }),
+ name: "Build Bot".to_string(),
+ handle: handle.to_string(),
+ description: Some("Builds things".to_string()),
+ avatar_url: Some("https://static.example/bot.png".to_string()),
+ created_by: Some(TEST_USER_ID.to_string()),
+ created_at: now,
+ updated_at: now,
+ deleted_at: None,
+ has_agent: false,
+ }
+}
+
+fn sample_token(bot_id: BotId, label: Option<String>) -> BotToken {
+ BotToken {
+ id: Uuid::new_v4(),
+ bot_id,
+ token: "secret-token".to_string(),
+ label,
+ last_used_at: None,
+ expires_at: None,
+ revoked_at: None,
+ created_at: Utc::now(),
+ }
+}
+
+#[derive(Clone, Default)]
+struct ToolTestBotService {
+ channels: Vec<BotChannel>,
+ remove_calls: Arc<AtomicUsize>,
+ created: Arc<Mutex<Option<CreateBotRequest>>>,
+ scoped: Arc<Mutex<Option<(Uuid, CreateChannelScopedBotRequest)>>>,
+}
+
+impl BotService for ToolTestBotService {
+ async fn create_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ req: CreateBotRequest,
+ ) -> Result<Bot, BotError> {
+ *self.created.lock().expect("create lock") = Some(req.clone());
+ Ok(sample_bot(&req.handle))
+ }
+
+ async fn create_channel_scoped_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: CreateChannelScopedBotRequest,
+ ) -> Result<CreateChannelScopedBotResponse, BotError> {
+ *self.scoped.lock().expect("scoped lock") = Some((channel_id, req.clone()));
+ let bot = sample_bot(&req.handle);
+ let token = sample_token(bot.id, req.token_label.clone());
+ Ok(CreateChannelScopedBotResponse {
+ bot,
+ token,
+ bot_token: "secret-token".to_string(),
+ })
+ }
+
+ async fn list_bots(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {
+ unimplemented!()
+ }
+
+ async fn get_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn get_self(&self, _bot_id: BotId) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn patch_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _req: PatchBotRequest,
+ ) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn delete_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn add_bot_to_channel(
+ &self,
+ _access: EntityAccessReceipt<MemberParticipantRole>,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn remove_bot_from_channel(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.remove_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+
+ async fn list_bot_channels(
+ &self,
+ _caller: BotChannelListCaller,
+ _bot_id: BotId,
+ ) -> Result<Vec<BotChannel>, BotError> {
+ Ok(self.channels.clone())
+ }
+
+ async fn list_channel_bots(&self, _channel_id: Uuid) -> Result<Vec<Bot>, BotError> {
+ unimplemented!()
+ }
+
+ async fn create_token(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _req: CreateBotTokenRequest,
+ ) -> Result<CreateBotTokenResponse, BotError> {
+ unimplemented!()
+ }
+
+ async fn list_tokens(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Vec<BotToken>, BotError> {
+ unimplemented!()
+ }
+
+ async fn revoke_token(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _token_id: Uuid,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn ensure_bot_in_channel(
+ &self,
+ _bot_id: BotId,
+ _channel_id: Uuid,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {
+ unimplemented!()
+ }
+
+ async fn authenticate_channel_token(
+ &self,
+ _channel_id: Uuid,
+ _token: &str,
+ ) -> Result<AuthenticatedBot, BotError> {
+ unimplemented!()
+ }
+}
+
+#[derive(Clone, Default)]
+struct AllowingEntityAccessService {
+ calls: Arc<AtomicUsize>,
+}
+
+impl EntityAccessService for AllowingEntityAccessService {
+ 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.calls.fetch_add(1, Ordering::SeqCst);
+ 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)
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Err(AccessError::Internal)
+ }
+
+ 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)
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ Err(AccessError::Internal)
+ }
+
+ 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)
+ }
+
+ 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)
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ Err(AccessError::Internal)
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ Err(AccessError::Internal)
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ Err(AccessError::Internal)
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ Ok(None)
+ }
+}
+
+#[test]
+fn bot_summary_preserves_team_scope_and_profile() {
+ let bot_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let now = Utc::now();
+ let summary = BotSummary::try_from(Bot {
+ id: BotId::new_from_uuid(bot_id),
+ kind: BotKind::Owned,
+ owner: Some(BotOwner::Team { team_id }),
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: Some("Builds things".to_string()),
+ avatar_url: Some("https://static.example/bot.png".to_string()),
+ created_by: Some("macro|[email protected]".to_string()),
+ created_at: now,
+ updated_at: now,
+ deleted_at: None,
+ has_agent: false,
+ })
+ .expect("owned bot has an owner");
+
+ assert_eq!(summary.bot_id, bot_id);
+ assert!(matches!(
+ summary.owner,
+ BotOwnerSummary::Team { team_id: id } if id == team_id
+ ));
+ assert_eq!(
+ summary.avatar_url.as_deref(),
+ Some("https://static.example/bot.png")
+ );
+ assert!(!summary.has_agent);
+}
+
+#[test]
+fn bot_summary_rejects_ownerless_bots() {
+ let now = Utc::now();
+ let error = BotSummary::try_from(Bot {
+ id: BotId::new_from_uuid(Uuid::new_v4()),
+ kind: BotKind::System,
+ owner: None,
+ name: "Macro".to_string(),
+ handle: "macro".to_string(),
+ description: None,
+ avatar_url: None,
+ created_by: None,
+ created_at: now,
+ updated_at: now,
+ deleted_at: None,
+ has_agent: false,
+ })
+ .expect_err("system bots are not manageable");
+
+ assert_eq!(
+ error.description,
+ "bot is missing an owner and cannot be managed"
+ );
+}
+
+#[test]
+fn bot_errors_are_actionable_without_exposing_repository_details() {
+ let missing = bot_tool_error(
+ "configure bot",
+ BotError::NotFound("bot not found".to_string()),
+ );
+ assert_eq!(missing.description, "bot not found");
+
+ let repository = bot_tool_error(
+ "configure bot",
+ BotError::Repo(anyhow::anyhow!("database password leaked")),
+ );
+ assert_eq!(repository.description, "failed to configure bot");
+}
+
+#[tokio::test]
+async fn create_bot_without_channel_does_not_mint_a_credential() {
+ let service = ToolTestBotService::default();
+ let created = service.created.clone();
+ let scoped = service.scoped.clone();
+ let context = BotToolContext::new(
+ service,
+ NoOpEntityAccessService,
+ "https://storage.example.com".to_string(),
+ );
+
+ let response = CreateBot {
+ team_id: None,
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: None,
+ avatar_url: None,
+ channel_id: None,
+ credential_label: None,
+ credential_expires_at: None,
+ has_agent: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("standalone create should not consult entity access");
+
+ assert_eq!(response.bot.handle, "build-bot");
+ assert!(response.channel_setup.is_none());
+ assert!(created.lock().expect("create lock").is_some());
+ assert!(scoped.lock().expect("scoped lock").is_none());
+}
+
+#[tokio::test]
+async fn create_bot_rejects_credential_fields_without_channel() {
+ let context = BotToolContext::new(
+ ToolTestBotService::default(),
+ NoOpEntityAccessService,
+ "https://storage.example.com".to_string(),
+ );
+
+ let error = CreateBot {
+ team_id: None,
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: None,
+ avatar_url: None,
+ channel_id: None,
+ credential_label: Some("github-webhook".to_string()),
+ credential_expires_at: None,
+ has_agent: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("credential label requires channelId");
+
+ assert!(error.description.contains("require channelId"));
+}
+
+#[tokio::test]
+async fn create_bot_for_channel_returns_credential_and_webhook() {
+ let channel_id = Uuid::new_v4();
+ let service = ToolTestBotService::default();
+ let scoped = service.scoped.clone();
+ let access = AllowingEntityAccessService::default();
+ let access_calls = access.calls.clone();
+ let context = BotToolContext::new(service, access, "https://storage.example.com/".to_string());
+
+ let response = CreateBot {
+ team_id: None,
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: None,
+ avatar_url: None,
+ channel_id: Some(channel_id),
+ credential_label: Some("github-webhook".to_string()),
+ credential_expires_at: None,
+ has_agent: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("channel member can create a channel-ready bot");
+
+ let setup = response.channel_setup.expect("channel setup");
+ assert_eq!(setup.channel_id, channel_id);
+ assert_eq!(setup.bearer_token, "secret-token");
+ assert_eq!(
+ setup.webhook.webhook_url,
+ format!("https://storage.example.com/channels/{channel_id}/webhook")
+ );
+ assert_eq!(setup.credential_header, "x-macro-bot-token");
+ assert_eq!(access_calls.load(Ordering::SeqCst), 1);
+ let (scoped_channel, scoped_req) = scoped.lock().expect("scoped lock").clone().expect("scoped");
+ assert_eq!(scoped_channel, channel_id);
+ assert_eq!(scoped_req.token_label.as_deref(), Some("github-webhook"));
+}
+
+#[tokio::test]
+async fn create_bot_for_channel_requires_membership() {
+ let context = BotToolContext::new(
+ ToolTestBotService::default(),
+ NoOpEntityAccessService,
+ "https://storage.example.com".to_string(),
+ );
+
+ let error = CreateBot {
+ team_id: None,
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: None,
+ avatar_url: None,
+ channel_id: Some(Uuid::new_v4()),
+ credential_label: None,
+ credential_expires_at: None,
+ has_agent: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("NoOp entity access rejects membership");
+
+ assert_eq!(error.description, "failed to verify channel membership");
+}
+
+#[tokio::test]
+async fn revoke_does_not_require_current_channel_membership() {
+ let service = ToolTestBotService::default();
+ let remove_calls = service.remove_calls.clone();
+ let context = BotToolContext::new(
+ service,
+ NoOpEntityAccessService,
+ "https://storage.example.com".to_string(),
+ );
+
+ let response = ManageBotChannelAccess {
+ bot_id: Uuid::new_v4(),
+ channel_id: Uuid::new_v4(),
+ action: BotChannelAccessAction::Revoke,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("revoke skips entity-access because NoOp would have failed");
+
+ assert_eq!(response.action, BotChannelAccessAction::Revoke);
+ assert_eq!(remove_calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn webhook_response_uses_preferred_bot_authentication_headers() {
+ let channel_id = Uuid::new_v4();
+ let service = ToolTestBotService {
+ channels: vec![BotChannel {
+ channel_id,
+ name: Some("Alerts".to_string()),
+ channel_type: BotChannelType::Private,
+ joined_at: Utc::now(),
+ }],
+ ..ToolTestBotService::default()
+ };
+ let context = BotToolContext::new(
+ service,
+ NoOpEntityAccessService,
+ "https://storage.example.com/".to_string(),
+ );
+
+ let response = GetBotWebhooks {
+ bot_id: Uuid::new_v4(),
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("manageable bot channels should produce webhook metadata");
+
+ assert_eq!(response.credential_header, "x-macro-bot-token");
+ assert_eq!(response.credential_scope_header, "x-macro-bot-scope");
+ assert_eq!(response.credential_scope, "user");
+ assert_eq!(
+ response.webhooks[0].webhook_url,
+ format!("https://storage.example.com/channels/{channel_id}/webhook")
+ );
+}
diff --git a/crates/bots/src/inbound/toolset/types.rs b/crates/bots/src/inbound/toolset/types.rs
new file mode 100644
index 0000000000..06d9e665a2
--- /dev/null
+++ b/crates/bots/src/inbound/toolset/types.rs
@@ -0,0 +1,125 @@
+//! Shared bot tool response types.
+
+use crate::domain::models::{Bot, BotOwner};
+use ai_toolset::ToolCallError;
+use schemars::JsonSchema;
+use serde::Serialize;
+use uuid::Uuid;
+
+/// Preferred header used to authenticate bot webhook requests.
+pub const BOT_WEBHOOK_TOKEN_HEADER: &str = "x-macro-bot-token";
+/// Header selecting the authorization scope for bot webhook requests.
+pub const BOT_WEBHOOK_SCOPE_HEADER: &str = "x-macro-bot-scope";
+/// User scope works for both user- and team-owned bots on channel webhooks.
+pub const BOT_WEBHOOK_SCOPE: &str = "user";
+
+/// Ownership scope of a manageable bot.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case", tag = "type")]
+pub enum BotOwnerSummary {
+ /// Bot owned by one user.
+ User {
+ /// Macro user id of the owner.
+ user_id: String,
+ },
+ /// Bot owned by a team.
+ Team {
+ /// Team id of the owner.
+ team_id: Uuid,
+ },
+}
+
+impl From<BotOwner> for BotOwnerSummary {
+ fn from(owner: BotOwner) -> Self {
+ match owner {
+ BotOwner::User { user_id } => Self::User { user_id },
+ BotOwner::Team { team_id } => Self::Team { team_id },
+ }
+ }
+}
+
+/// High-signal bot details returned to AI agents.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BotSummary {
+ /// Bot id used by the other bot-management tools.
+ pub bot_id: Uuid,
+ /// User or team that owns the bot.
+ pub owner: BotOwnerSummary,
+ /// Display name.
+ pub name: String,
+ /// Stable mention handle.
+ pub handle: String,
+ /// Optional description.
+ pub description: Option<String>,
+ /// Optional profile-picture URL.
+ pub avatar_url: Option<String>,
+ /// Whether mentioning this bot opens a sandboxed coding-agent session.
+ pub has_agent: bool,
+}
+
+impl TryFrom<Bot> for BotSummary {
+ type Error = ToolCallError;
+
+ fn try_from(bot: Bot) -> Result<Self, Self::Error> {
+ let Some(owner) = bot.owner else {
+ return Err(ToolCallError {
+ description: "bot is missing an owner and cannot be managed".to_string(),
+ internal_error: anyhow::anyhow!("owned bot missing owner"),
+ });
+ };
+
+ Ok(Self {
+ bot_id: bot.id.as_uuid(),
+ owner: owner.into(),
+ name: bot.name,
+ handle: bot.handle,
+ description: bot.description,
+ avatar_url: bot.avatar_url,
+ has_agent: bot.has_agent,
+ })
+ }
+}
+
+/// One channel-specific webhook URL for a bot.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BotWebhook {
+ /// Channel id the webhook posts into.
+ pub channel_id: Uuid,
+ /// Channel display name, when present.
+ pub channel_name: Option<String>,
+ /// Public URL to POST webhook content to.
+ pub webhook_url: String,
+}
+
+impl BotWebhook {
+ /// Build a webhook URL for a channel on the document-storage service.
+ pub fn for_channel(document_storage_service_url: &str, channel_id: Uuid) -> Self {
+ Self {
+ channel_id,
+ channel_name: None,
+ webhook_url: format!("{document_storage_service_url}/channels/{channel_id}/webhook"),
+ }
+ }
+}
+
+/// One-time credential and webhook created with a channel-scoped bot.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreatedBotChannelSetup {
+ /// Channel the bot can now post to.
+ pub channel_id: Uuid,
+ /// Token metadata id, used to revoke this credential through the bot API.
+ pub token_id: Uuid,
+ /// Raw bearer token. It is returned only when minted and must be stored securely.
+ pub bearer_token: String,
+ /// Channel webhook the credential authenticates against.
+ pub webhook: BotWebhook,
+ /// Header where callers send [`Self::bearer_token`].
+ pub credential_header: String,
+ /// Header where callers send [`Self::credential_scope`].
+ pub credential_scope_header: String,
+ /// Required scope value for the bot credential.
+ pub credential_scope: String,
+}
diff --git a/crates/bots/src/lib.rs b/crates/bots/src/lib.rs
index 88c9905921..40a491a9ad 100644
--- a/crates/bots/src/lib.rs
+++ b/crates/bots/src/lib.rs
@@ -3,8 +3,8 @@
/// Domain models, ports, and service.
pub mod domain;
-#[cfg(feature = "inbound")]
-/// HTTP adapters.
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
+/// Inbound HTTP and AI-tool adapters.
pub mod inbound;
#[cfg(feature = "outbound")]
/// Postgres adapters.
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index 75ee032f86..3b6a439590 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -7,6 +7,10 @@ use crate::domain::{
ports::{BotError, BotService},
service::BotServiceImpl,
};
+use entity_access::domain::models::{
+ Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole,
+ ParticipantRole,
+};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker, NoopMacroEventBroker};
use serde_json::{Value, json};
@@ -23,6 +27,23 @@ fn user_id(value: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")
}
+fn channel_member_receipt(
+ caller: &str,
+ channel_id: Uuid,
+) -> EntityAccessReceipt<MemberParticipantRole> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ user_id(caller),
+ Entity {
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ },
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ )
+ .expect("member role satisfies channel membership")
+}
+
fn create_req(handle: &str) -> CreateBotRequest {
CreateBotRequest {
team_id: None,
@@ -486,13 +507,13 @@ async fn add_remove_channel_bot_requires_bot_usability_and_soft_removes(
.await?;
let err = service
- .add_bot_to_channel(user_id(USER_OTHER), channel_id, bot.id)
+ .add_bot_to_channel(channel_member_receipt(USER_OTHER, channel_id), bot.id)
.await
.expect_err("non-owner must not add someone else's bot");
assert!(matches!(err, BotError::Unauthorized));
service
- .add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .add_bot_to_channel(channel_member_receipt(USER_OWNER, channel_id), bot.id)
.await?;
let active_count: i64 = sqlx::query_scalar(
@@ -570,13 +591,19 @@ async fn list_bot_channels_requires_manageable_bot_and_returns_only_active_chann
assert!(empty_channels.is_empty());
service
- .add_bot_to_channel(user_id(USER_OWNER), removed_channel_id, bot.id)
+ .add_bot_to_channel(
+ channel_member_receipt(USER_OWNER, removed_channel_id),
+ bot.id,
+ )
.await?;
service
.remove_bot_from_channel(user_id(USER_OWNER), removed_channel_id, bot.id)
.await?;
service
- .add_bot_to_channel(user_id(USER_OWNER), active_channel_id, bot.id)
+ .add_bot_to_channel(
+ channel_member_receipt(USER_OWNER, active_channel_id),
+ bot.id,
+ )
.await?;
let channels = service
@@ -800,7 +827,7 @@ async fn authenticate_channel_token_accepts_migrated_uuid_token(
.create_bot(user_id(USER_OWNER), create_req("migrated-uuid-token"))
.await?;
service
- .add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .add_bot_to_channel(channel_member_receipt(USER_OWNER, channel_id), bot.id)
.await?;
let token_id = Uuid::new_v4();
@@ -994,7 +1021,7 @@ async fn non_lifecycle_and_failed_operations_do_not_publish(pool: PgPool) -> any
service.get_bot(user_id(USER_OWNER), bot.id).await?;
service.list_channel_bots(channel_id).await?;
service
- .add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .add_bot_to_channel(channel_member_receipt(USER_OWNER, channel_id), bot.id)
.await?;
service
.list_bot_channels(BotChannelListCaller::User(user_id(USER_OWNER)), bot.id)
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index 1f4c7a1542..9aa6f13782 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -256,6 +256,12 @@ pub async fn build_tool_service_context(
pool.clone(),
Arc::new(lexical_client),
),
+ bot_tool_context: ai_tools::build_bot_tool_context(
+ pool.clone(),
+ ai_tools::ToolBotEventBroker::NoOp(Default::default()),
+ entity_access_service.clone(),
+ config.document_storage_service_url.clone(),
+ ),
team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),
skill_tool_context,
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 0110b90f39..2e3019d2b8 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -383,6 +383,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
pool.clone(),
std::sync::Arc::new(test_lexical_client),
),
+ bot_tool_context: ai_tools::build_bot_tool_context(
+ pool.clone(),
+ ai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),
+ entity_access_service.clone(),
+ "http://localhost:8086".to_string(),
+ ),
project_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/main.rs b/services/document_cognition_service/src/main.rs
index 06196e1ca1..6a47058bff 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -592,6 +592,12 @@ async fn main() -> anyhow::Result<()> {
),
chat_tool_context,
channel_tool_context,
+ bot_tool_context: ai_tools::build_bot_tool_context(
+ db.clone(),
+ ai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),
+ entity_access_service.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
+ ),
project_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 64d7fa8a13..5a6735b303 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -154,7 +154,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
let ai_editing_worker_url = AiEditingWorkerUrl::new()?.to_string();
let search_service_client =
- SearchServiceClient::new(document_storage_service_auth_key, dss_url);
+ SearchServiceClient::new(document_storage_service_auth_key, dss_url.clone());
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
config.internal_api_key.to_string(),
@@ -396,6 +396,12 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
channel_tool_context,
+ bot_tool_context: ai_tools::build_bot_tool_context(
+ db.clone(),
+ ai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),
+ entity_access_service.clone(),
+ dss_url,
+ ),
project_tool_context,
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),