Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): ai in channels (#3692)
teoab0052a0db9d
diff --git a/.env-local.enc b/.env-local.encindex a9a8da2f7e..6f00be5c54 100644--- a/.env-local.enc+++ b/.env-local.enc@@ -91,7 +91,7 @@ REDIS_RATE_LIMIT_REQS=ENC[AES256_GCM,data:uwTjxUVcnA==,iv:X4djuAlXEWcRuTAD+1glAKREDIS_RATE_LIMIT_REQS_BACKFILL=ENC[AES256_GCM,data:I9MsQ0VD4A==,iv:XxQwJWuZu49i2nGce5IetnhTPWOQJkHealO+LkRF9EA=,tag:Ardw2EUGlD8WdjUPk6A+3Q==,type:str]REDIS_RATE_LIMIT_WINDOW_SECS=ENC[AES256_GCM,data:lTcCCg==,iv:i+fHBCRu51927ZMFlFN8mkxaWNrcx2pAJf6pZgqrh/o=,tag:91RTuTLnuxrR7LCewCX35w==,type:str]REDIS_URI=ENC[AES256_GCM,data:krrzu32oP6tGMhmSXGo1RlQQFvo=,iv:QpB3zw13z9fvopF/APqVx+4aX35bFdnlw2sEdZOwWic=,tag:KmfYnA4EArEa6YOnXnqIpg==,type:str]-RUST_LOG=ENC[AES256_GCM,data:g+DP8AlM,iv:2Ql39bdCMoFmghhHvYHQLUmLhgaf802H2qSqR9dJ/qQ=,tag:SS3wsa5YNmCbdIQAWVXjVg==,type:str]+RUST_LOG=ENC[AES256_GCM,data:p8MWJQ==,iv:fO67JltLh5kCMdCAUaHKksyDy10rpHyiVfcvri/MQNw=,tag:Uv/QamLY5xuQCIZRbfmPdw==,type:str]SEARCH_EVENT_QUEUE=ENC[AES256_GCM,data:d8JqukQpj7j16jEIZMhUiIKBXwnwTD1VLll+f1WjgnBwnI776oAW79GpxEqf6u2Gd4nVWzWIdgc=,iv:uVScG0WUfmW0clx2CfYR87oOsgWpqCFnITiSZcpAR9s=,tag:si70uSvBaeGsoqxyA/GVEA==,type:str]SEARCH_PROCESSING_SERVICE_QUEUE_MAX_MESSAGES=ENC[AES256_GCM,data:y3aMKQ==,iv:NtyOjGJywPmYw1kwa51oKXFikoT2QE+oAmKO2tUrQ6k=,tag:RRMMWaL4OVT0Q9L9l/vHUg==,type:str]SEARCH_PROCESSING_SERVICE_QUEUE_WAIT_TIME_SECONDS=ENC[AES256_GCM,data:TNjNlA==,iv:0UtBqP95eTEGTNzEifztqoHqkpGW/8+otL2PmaMgjxc=,tag:1g4HPQK0erfe+1p0kdAm2w==,type:str]@@ -135,7 +135,8 @@ LIVEKIT_TRANSCRIPTION_AGENT_NAME=ENC[AES256_GCM,data:RgXJ+WNruFiyg1Pjjzo++SDOLg=INTERNAL_CALL_SECRET=ENC[AES256_GCM,data:66UR3BO7Ddg5bQ0xmLNeY5EGb65L4tiXcsDNpTE=,iv:ovuMlw/k257Oh1CkosXjOXDWycQ4AoA9s+hhfHpeOvs=,tag:qXXYEFhSaM0Q4ffRdGtMRg==,type:str]URL_SIGNING_HMAC=ENC[AES256_GCM,data:2PtDBCM6BARI7Fl5MSCVbOzGsXvgR8eFghJPfTvUFP31YRnFHpF5CBIsSlOhGUJihSoq6Ydfr9L4+LKv1EXT9g8S,iv:7ZmNUdsYr3ujUZiPVStz5ymrtYBfhsmDeyISzGX+1h0=,tag:snvxFxHfT7NyXpKF4Onu6A==,type:str]NOTIFICATION_INGRESS_QUEUE=ENC[AES256_GCM,data:ZNMcAeqCNUOP9P763YB5kJgPRTKjIYLoamXheZKgeTtvHIfrtwYXIGjrd9PY/uWOR+RkrfevyRKTAlOEGeu95g==,iv:4Ag6GDV9B/g0feL1ayLau6fyA2j9udJt1AAIejy5Otw=,tag:3MgDj0sUU6kOv7H4NU1dmw==,type:str]-MCP_CREDENTIALS_KEY_SECRET_NAME=ENC[AES256_GCM,data:EJhxDEIW7Q2qmtM4YQ08Zha1ipgtRYkcWI7Yvfj4oOvkmstmheGWbAT8Ntk=,iv:ECaNGuT+50MBy23GW3qqUg/EEZuN4wDd5odS9IyPyAA=,tag:G3So5XWbsYd3xwJ2s22BGw==,type:str]+MCP_CREDENTIALS_KEY_SECRET_NAME=ENC[AES256_GCM,data:TWYjUgeijTBC7XWj32K2Whd7/EMO3y+fx69nbAqBQbUS5lDSy+7y+/J9/r+kWA==,iv:XiwwHHgSG10MbIl0vSqsKMHT47SmrI2h8c7UjDtoFtU=,tag:9QaK1AB9r05fPjeYpb40Uw==,type:str]+SLACK_MCP_CLIENT_ID=ENC[AES256_GCM,data:KbgA6OU1HPSbIaTP8gK4NIE=,iv:ypqeXszgB3eN5qRS0vL6nqdqz3imhIM5t9AnLnylct8=,tag:fqNltmVYhHFX2MkYm0MKkg==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBM1lmcDc3\nUENpRVorSGVGa3R2NFlrdkx1Mm43aEcyR1ZtbEswL2RnWHlqMwpVMnY4ck5makNC\nZzVZc3JrZ3NKV2x3RTY0TFovRXJtVzEyeFZOZWRheHBNCi0tLSBobjhCbHpJa25s\nZDhyQjhCaEYrOWNiWHZkRWpnRlkwTnNEbjMwYzdxcTUwCqxxxmXy3mFUAbAy29y8\n2DFYDATdVvmplHpDTvgrNyY+lAL/3Jp9vtIs5DGXW/r73Nv3AhISmuCid18qhpAY\nUqE=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -146,7 +147,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:07Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==-sops_lastmodified=2026-06-01T20:32:06Z-sops_mac=ENC[AES256_GCM,data:gzMq4zljBMsVCrmfQFxJJsyoLp5k9EXZfiBzAfRarKUub9QXPTjFJeBdcWYsjOwia8VOBD6Q7j7W+tD2P3KOiKyQpYlSA24r4h9sOixFELY1w54mnvx7bRDSmBi908/I4LTUGzh2r8CAXSh7BLZJDQpsW3s/E0FFQ8Y/L1CxLrs=,iv:YuZnxvLsPfYK7y1ezu6F9rp5/sHXR7YwpuNumvosz2s=,tag:nShIjQctV3ID9yVRPHXLfw==,type:str]+sops_lastmodified=2026-06-01T21:03:11Z+sops_mac=ENC[AES256_GCM,data:/OJeEm/FFCFsX/hscAxrF2KLG4lsGjccFxreYzw0JlmpQ1hNJ6WeIL/sACYjo43tAMoYdsiCWhC/CkSYy9lnAqbBK75NEqjCh1n/e5uGCmDY8nv+BJ1DOTd9q2vrJHVfFYZeVwCAP+lIEYNdZV9m79lKo5mNCNhzubyUFGUIl7Q=,iv:bzyw7ATfMjdTnKJFo1xjLI8y4UfATn41LatfaULT0nM=,tag:jm7k3i430F5Zn8ea5oQTEA==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.2diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 76e5690869..4b5a2f5a44 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -189,6 +189,18 @@ const contactsQueueArn: pulumi.Output<string> = contactsServiceStack.getOutput('contactsQueueArn').apply((arn) => arn as string);+const emailServiceStack = new pulumi.StackReference('email-service-stack', {+ name: `macro-inc/email-service/${stack}`,+});++const emailScheduledQueueName: pulumi.Output<string> = emailServiceStack+ .getOutput('scheduledQueueName')+ .apply((name) => name as string);++const emailScheduledQueueArn: pulumi.Output<string> = emailServiceStack+ .getOutput('scheduledQueueArn')+ .apply((arn) => arn as string);+const {notificationIngressQueueName,notificationIngressQueueArn,@@ -376,6 +388,7 @@ const cloudStorageService = new CloudStorageService(deleteDocumentHandler.queue.arn,notificationIngressQueueArn,contactsQueueArn,+ emailScheduledQueueArn,],vpc: coparse_api_vpc,platform: {@@ -569,6 +582,18 @@ const cloudStorageService = new CloudStorageService(name: ServiceUrl.CONNECTION_GATEWAY_URL,value: getServiceUrl(ServiceUrl.CONNECTION_GATEWAY_URL),},+ {+ name: ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL,+ value: getServiceUrl(ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL),+ },+ {+ name: ServiceUrl.EMAIL_SERVICE_URL,+ value: getServiceUrl(ServiceUrl.EMAIL_SERVICE_URL),+ },+ {+ name: ServiceUrl.STATIC_FILE_SERVICE_URL,+ value: getServiceUrl(ServiceUrl.STATIC_FILE_SERVICE_URL),+ },{name: 'BULK_UPLOAD_REQUESTS_TABLE',// TODO: this should be interpolated from the bulk upload resource@@ -583,6 +608,10 @@ const cloudStorageService = new CloudStorageService(name: 'SYNC_SERVICE_AUTH_KEY',value: pulumi.interpolate`${SYNC_SERVICE_AUTH_KEY}`,},+ {+ name: 'EMAIL_SCHEDULED_QUEUE',+ value: pulumi.interpolate`${emailScheduledQueueName}`,+ },{name: ServiceUrl.SYNC_SERVICE_URL,value: getServiceUrl(ServiceUrl.SYNC_SERVICE_URL),diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsxindex 1796f1df76..1dcbeaa896 100644--- a/js/app/packages/channel/Input/ChannelInput.tsx+++ b/js/app/packages/channel/Input/ChannelInput.tsx@@ -18,6 +18,7 @@ import {Show,Switch,} from 'solid-js';+import { MACRO_AI_BOT_ID, macroAiMentionUser } from '../macroAi';import { createInputAttachmentTracker } from './attachment-tracker';import { createConfiguredChannelMarkdownEditor } from './configured-markdown-editor';import { createInputState } from './create-input-state';@@ -162,10 +163,19 @@ export function ChannelInput(props: ChannelInputProps) {queueMicrotask(() => applySnapshot(snapshot));};+ // Macro AI is mentionable in every channel. It is surfaced through the same+ // `@`-mention typeahead as participants and re-tagged as a bot at send time.+ const mentionUsers: Accessor<IUser[]> = () => {+ const base = props.participants?.() ?? [];+ return base.some((user) => user.id === MACRO_AI_BOT_ID)+ ? base+ : [macroAiMentionUser(), ...base];+ };+const markdownEditor = createConfiguredChannelMarkdownEditor({namespace: props.markdownNamespace ?? 'channel-input-markdown',enableMentions: true,- users: props.participants,+ users: mentionUsers,scrollContainer,onMentionCreate: (mention) => {mentionsTracker.onMentionCreate(mention);diff --git a/js/app/packages/channel/Input/message-payload.ts b/js/app/packages/channel/Input/message-payload.tsindex d999013be8..5fe22a19b9 100644--- a/js/app/packages/channel/Input/message-payload.ts+++ b/js/app/packages/channel/Input/message-payload.ts@@ -4,6 +4,7 @@ import type { NewChannelAttachment as NewAttachment } from '@service-storage/genimport type { PostMessageRequest } from '@service-storage/generated/schemas/postMessageRequest';import type { SimpleMention } from '@service-storage/generated/schemas/simpleMention';import { match } from 'ts-pattern';+import { isMacroAiId } from '../macroAi';import type { InputAttachmentData, InputSnapshot } from './types';export function attachmentEntityType(@@ -55,11 +56,16 @@ export function expandMentions(for (const mention of mentions) {if (mention.itemType === 'group') {result.push(...expandGroupMention(mention, participantIds, seenUserIds));+ } else if (mention.itemType === 'user') {+ if (seenUserIds.has(mention.itemId)) continue;+ seenUserIds.add(mention.itemId);+ // Macro AI rides the user-mention machinery in the editor but is a bot;+ // re-tag it so the backend dispatches a bot trigger.+ result.push({+ entity_type: isMacroAiId(mention.itemId) ? 'bot' : 'user',+ entity_id: mention.itemId,+ });} else {- if (mention.itemType === 'user') {- if (seenUserIds.has(mention.itemId)) continue;- seenUserIds.add(mention.itemId);- }result.push({entity_type: mention.itemType,entity_id: mention.itemId,diff --git a/js/app/packages/channel/Message/AgentBadge.tsx b/js/app/packages/channel/Message/AgentBadge.tsxnew file mode 100644index 0000000000..04e6e329de--- /dev/null+++ b/js/app/packages/channel/Message/AgentBadge.tsx@@ -0,0 +1,31 @@+import { isBotSenderId } from '@queries/channel/message-sender';+import { cn } from '@ui';+import { Show } from 'solid-js';+import { useMessage } from './context';++type AgentBadgeProps = {+ class?: string;+};++/**+ * Small "Agent" badge shown next to a bot sender's name so it's clear the+ * message is from an agent rather than a person.+ */+export function AgentBadge(props: AgentBadgeProps) {+ const message = useMessage();+ const isAgent = () => isBotSenderId(message().sender_id);++ return (+ <Show when={isAgent()}>+ <span+ class={cn(+ 'inline-flex shrink-0 items-center rounded-sm bg-hover px-2 py-0.5',+ 'text-xs font-medium leading-none text-ink-muted',+ props.class+ )}+ >+ Agent+ </span>+ </Show>+ );+}diff --git a/js/app/packages/channel/Message/ChannelMessage.tsx b/js/app/packages/channel/Message/ChannelMessage.tsxindex 66d4f4c53e..b5ff4f472b 100644--- a/js/app/packages/channel/Message/ChannelMessage.tsx+++ b/js/app/packages/channel/Message/ChannelMessage.tsx@@ -123,6 +123,7 @@ function RegularMessageLayout(props: {</Message.Slot><Message.Slot placement="header" class="flex items-center gap-1 min-w-0"><Message.SenderName />+ <Message.AgentBadge /><Message.EditedIndicator />{/* On message hover, timestamp floats above actions. */}<div class="grow shrink-0 min-w-0 flex justify-end group-hover/message:absolute group-hover/message:right-1 group-hover/message:-top-9 group-hover/message:p-1 group-hover/message:bg-surface group-hover/message:rounded-md">diff --git a/js/app/packages/channel/Message/EditedIndicator.tsx b/js/app/packages/channel/Message/EditedIndicator.tsxindex 70330399dd..3e5ed0dd5d 100644--- a/js/app/packages/channel/Message/EditedIndicator.tsx+++ b/js/app/packages/channel/Message/EditedIndicator.tsx@@ -1,3 +1,4 @@+import { isBotSenderId } from '@queries/channel/message-sender';import { cn } from '@ui';import { Show } from 'solid-js';import { useMessage } from './context';@@ -9,8 +10,12 @@ type EditedIndicatorProps = {export function EditedIndicator(props: EditedIndicatorProps) {const message = useMessage();+ // Macro edits its own "thinking" message into the answer; that isn't a+ // user edit, so don't surface an "(edited)" marker for bot senders.return (- <Show when={message().edited_at != null}>+ <Show+ when={message().edited_at != null && !isBotSenderId(message().sender_id)}+ ><span class={cn('text-xs text-ink-placeholder', props.class)}>(edited)</span>diff --git a/js/app/packages/channel/Message/Message.ts b/js/app/packages/channel/Message/Message.tsindex 028d2394e3..6bab286a1d 100644--- a/js/app/packages/channel/Message/Message.ts+++ b/js/app/packages/channel/Message/Message.ts@@ -1,4 +1,5 @@import { ActionMenu } from './ActionMenu';+import { AgentBadge } from './AgentBadge';import { Attachments } from './Attachments';import { Content } from './Content';import { DateDivider } from './DateDivider';@@ -20,6 +21,7 @@ export const Message = {Layout,Slot,SenderName,+ AgentBadge,SenderIcon,Timestamp,Content,diff --git a/js/app/packages/channel/Message/SenderName.tsx b/js/app/packages/channel/Message/SenderName.tsxindex 6172d75d19..5dc18e2674 100644--- a/js/app/packages/channel/Message/SenderName.tsx+++ b/js/app/packages/channel/Message/SenderName.tsx@@ -1,6 +1,8 @@import { tryMacroId, useDisplayName } from '@core/user';+import { senderFromStorageId } from '@queries/channel/message-sender';import { cn } from '@ui';import { Show } from 'solid-js';+import { MACRO_AI_BOT_ID, MACRO_AI_NAME } from '../macroAi';import { useMessage } from './context';type SenderNameProps = {@@ -8,15 +10,23 @@ type SenderNameProps = {hidden?: boolean;};+/** Resolve a bot sender's display name, or `undefined` for user senders. */+function botName(senderId: string): string | undefined {+ const sender = senderFromStorageId(senderId);+ if (sender.type !== 'bot') return undefined;+ return sender.id === MACRO_AI_BOT_ID ? MACRO_AI_NAME : 'Bot';+}+export function SenderName(props: SenderNameProps) {const message = useMessage();const macroId = () => tryMacroId(message().sender_id);const [displayName] = useDisplayName(macroId());+ const agentName = () => botName(message().sender_id);return (<Show when={!props.hidden}><span class={cn('text-sm font-medium truncate', props.class)}>- {displayName()}+ {agentName() ?? displayName()}</span></Show>);diff --git a/js/app/packages/channel/StandaloneThread/ParentMessage.tsx b/js/app/packages/channel/StandaloneThread/ParentMessage.tsxindex 16e97ab48a..59a4118512 100644--- a/js/app/packages/channel/StandaloneThread/ParentMessage.tsx+++ b/js/app/packages/channel/StandaloneThread/ParentMessage.tsx@@ -33,6 +33,7 @@ export function ParentMessage(props: ParentMessageProps) {class="flex items-center gap-1 min-w-0"><Message.SenderName />+ <Message.AgentBadge /><Message.EditedIndicator /><Message.Timestampclass="ml-auto shrink-0"diff --git a/js/app/packages/channel/StandaloneThread/Replies.tsx b/js/app/packages/channel/StandaloneThread/Replies.tsxindex bdd98eceea..6f26d61c68 100644--- a/js/app/packages/channel/StandaloneThread/Replies.tsx+++ b/js/app/packages/channel/StandaloneThread/Replies.tsx@@ -92,6 +92,7 @@ export function Replies(props: RepliesProps) {class="flex items-center gap-1 min-w-0"><Message.SenderName />+ <Message.AgentBadge /><Message.EditedIndicator /><Message.Timestampclass="ml-auto shrink-0"diff --git a/js/app/packages/channel/macroAi.ts b/js/app/packages/channel/macroAi.tsnew file mode 100644index 0000000000..ebf8231f8e--- /dev/null+++ b/js/app/packages/channel/macroAi.ts@@ -0,0 +1,27 @@+import {+ MACRO_AGENT_BOT_ID,+ MACRO_AGENT_NAME,+} from '@core/constant/macroAgent';+import type { IUser } from '@core/user/types';++// Re-export the shared Macro identity under the names used in this package.+export {+ isMacroAgentId as isMacroAiId,+ MACRO_AGENT_BOT_ID as MACRO_AI_BOT_ID,+ MACRO_AGENT_HANDLE as MACRO_AI_HANDLE,+ MACRO_AGENT_NAME as MACRO_AI_NAME,+} from '@core/constant/macroAgent';++/**+ * A synthetic [`IUser`] entry so Macro appears in the channel `@`-mention+ * typeahead. The mention rides the existing user-mention machinery and is+ * re-tagged as a bot mention at send time (see `expandMentions`). `email` is set+ * to the display name so the typeahead shows just "Macro".+ */+export function macroAiMentionUser(): IUser {+ return {+ id: MACRO_AGENT_BOT_ID,+ name: MACRO_AGENT_NAME,+ email: MACRO_AGENT_NAME,+ };+}diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 8da07794e9..d1d2fa469d 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -11,6 +11,7 @@ import type { HeadingNode, QuoteNode } from '@lexical/rich-text';import type { TableCellNode, TableNode, TableRowNode } from '@lexical/table';import {$isClassedBlockNode,+ type AwaitNode,type ClassedBlockNode,type ContactMentionNode,type DateMentionNode,@@ -68,6 +69,7 @@ import type { SearchMatchNode } from '@lexical-core/nodes/SearchMatchNode';import { theme as baseTheme, createTheme } from '../../theme';import { forceSingleLine, setEditorStateFromMarkdown } from '../../utils';import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';+import { Await as AwaitDecorator } from '../decorator/Await';import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';import { DateMention as DateMentionDecorator } from '../decorator/DateMention';import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCard';@@ -368,6 +370,24 @@ const GroupMention: RenderableEntity<GroupMentionNode> = {),};+const Await: RenderableEntity<AwaitNode> = {+ guard: (node: LexicalNode): node is AwaitNode => node.__type === 'await',+ render: (props) => {+ const componentProps = props.node.exportComponentProps();+ return (+ <span>+ {AwaitDecorator({+ awaitId: componentProps.awaitId,+ text: componentProps.text,+ inline: componentProps.inline ?? true,+ key: props.node.getKey(),+ theme: props.theme,+ })}+ </span>+ );+ },+};+const Snapshot: RenderableEntity<SnapshotNode> = {guard: (node: LexicalNode): node is SnapshotNode =>node.__type === 'snapshot',@@ -703,6 +723,7 @@ const InlineEntities: Array<RenderableEntity> = [ContactMention,DateMention,GroupMention,+ Await,Snapshot,Image,Video,diff --git a/js/app/packages/core/component/UserIcon.tsx b/js/app/packages/core/component/UserIcon.tsxindex 625cbb8e0d..fc8a2e40d7 100644--- a/js/app/packages/core/component/UserIcon.tsx+++ b/js/app/packages/core/component/UserIcon.tsx@@ -1,4 +1,5 @@import { ENABLE_PROFILE_PICTURES } from '@core/constant/featureFlags';+import { isMacroAgentId } from '@core/constant/macroAgent';import { staticFileSizedUrl } from '@core/constant/servers';import { internalDrag } from '@core/directive/internalDragState';import { useProfilePictureUrl } from '@core/signal/profilePicture';@@ -8,9 +9,10 @@ import {useDisplayName,useDisplayNameParts,} from '@core/user';+import MacroLogo from '@icon/macro-logo.svg';import Trash from '@phosphor-icons/core/regular/trash.svg?component-solid';import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';-import { Avatar, type AvatarSize } from '@ui';+import { Avatar, type AvatarSize, cn } from '@ui';import {createMemo,createSignal,@@ -169,6 +171,20 @@ export function UserIcon(props: UserIconProps) {return (<Switch>+ <Match when={isMacroAgentId(props.id)}>+ <Avatar+ size={size()}+ class={cn(+ 'bg-surface text-accent ring-1 ring-edge-muted',+ props.class+ )}+ >+ <Avatar.Fallback>+ <MacroLogo class="size-[62%]" />+ </Avatar.Fallback>+ </Avatar>+ </Match>+<Match when={!showTooltip() || !hasTooltipContent()}><Avatarsize={size()}diff --git a/js/app/packages/core/constant/macroAgent.ts b/js/app/packages/core/constant/macroAgent.tsnew file mode 100644index 0000000000..883fed1f7a--- /dev/null+++ b/js/app/packages/core/constant/macroAgent.ts@@ -0,0 +1,22 @@+/**+ * Identity for the first-party "Macro" system bot. Mirrors+ * `bot_id::MACRO_AI_BOT_ID` on the backend. Macro is a global system bot+ * available in every channel; mentioning it triggers an AI reply in a thread.+ */+export const MACRO_AGENT_BOT_ID = '00000000-0000-0000-0000-00000000a1a1';++/** Display name for Macro. */+export const MACRO_AGENT_NAME = 'Macro';++/** Handle used to find Macro in the mention typeahead (`@macro`). */+export const MACRO_AGENT_HANDLE = 'macro';++/**+ * Whether an id refers to the Macro bot. Accepts both the bare UUID and+ * the `bot|<uuid>` participant/sender form.+ */+export function isMacroAgentId(id: string | undefined): boolean {+ if (!id) return false;+ const bare = id.startsWith('bot|') ? id.slice('bot|'.length) : id;+ return bare === MACRO_AGENT_BOT_ID;+}diff --git a/js/app/packages/queries/channel/message-sender.ts b/js/app/packages/queries/channel/message-sender.tsindex 5659729d4d..bdd8e75701 100644--- a/js/app/packages/queries/channel/message-sender.ts+++ b/js/app/packages/queries/channel/message-sender.ts@@ -30,6 +30,10 @@ export function senderFromStorageId(senderId: string): ApiMessageSender {return { type: 'user', id: senderId };}+export function isBotSenderId(senderId: string): boolean {+ return senderFromStorageId(senderId).type === 'bot';+}+export function normalizeMessageSender<T extends { sender_id: string; sender?: ApiMessageSender },>(message: T): T & { sender: ApiMessageSender } {diff --git a/js/bun.lock b/js/bun.lockindex 9af37d685c..102287cfcb 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -824,7 +824,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2544,7 +2544,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/js/lexical-core/decoratorRegistry.ts b/js/lexical-core/decoratorRegistry.tsindex d46790b1e1..98db423468 100644--- a/js/lexical-core/decoratorRegistry.ts+++ b/js/lexical-core/decoratorRegistry.ts@@ -24,10 +24,6 @@ import type {EquationDecoratorProps,EquationNode,} from './nodes/EquationNode';-import type {- SnapshotDecoratorProps,- SnapshotNode,-} from './nodes/SnapshotNode';import type {GroupMentionDecoratorProps,GroupMentionNode,@@ -42,22 +38,26 @@ import type {} from './nodes/HtmlRenderNode';import type { ImageDecoratorProps, ImageNode } from './nodes/ImageNode';import type {- UserMentionDecoratorProps,- UserMentionNode,-} from './nodes/UserMentionNode';-import type { VideoDecoratorProps, VideoNode } from './nodes/VideoNode';+ SnapshotDecoratorProps,+ SnapshotNode,+} from './nodes/SnapshotNode';import type {ThemeMentionDecoratorProps,ThemeMentionNode,} from './nodes/ThemeMentionNode';+import type {+ UnknownMentionDecoratorProps,+ UnknownMentionNode,+} from './nodes/UnknownMentionNode';+import type {+ UserMentionDecoratorProps,+ UserMentionNode,+} from './nodes/UserMentionNode';+import type { VideoDecoratorProps, VideoNode } from './nodes/VideoNode';import type {WatermarkDecoratorProps,WatermarkNode,} from './nodes/WatermarkNode';-import type {- UnknownMentionNode,- UnknownMentionDecoratorProps,-} from './nodes/UnknownMentionNode';// Generic component type to be overridden by solid-js on the front end// and nothing on the backend.diff --git a/js/lexical-core/index.ts b/js/lexical-core/index.tsindex d35fe75ec9..003232990d 100644--- a/js/lexical-core/index.ts+++ b/js/lexical-core/index.ts@@ -16,18 +16,18 @@ export * from './nodes/DiffNode';export * from './nodes/DocumentCardNode';export * from './nodes/DocumentMentionNode';export * from './nodes/EquationNode';-export * from './nodes/SnapshotNode';export * from './nodes/GroupMentionNode';export * from './nodes/HorizontalRuleNode';export * from './nodes/HtmlRenderNode';export * from './nodes/ImageNode';export * from './nodes/InlineSearchNode';export * from './nodes/MediaNode';-export * from './nodes/UnlinkedTextNode';+export * from './nodes/SnapshotNode';+export * from './nodes/ThemeMentionNode';export * from './nodes/UnknownMentionNode';+export * from './nodes/UnlinkedTextNode';export * from './nodes/UserMentionNode';export * from './nodes/VideoNode';-export * from './nodes/ThemeMentionNode';export * from './nodes/WatermarkNode';export * from './plugins/nodeIdPlugin';diff --git a/js/lexical-core/node-list.ts b/js/lexical-core/node-list.tsindex 6c24541c24..522d961618 100644--- a/js/lexical-core/node-list.ts+++ b/js/lexical-core/node-list.ts@@ -21,23 +21,23 @@ import { ContactMentionNode } from './nodes/ContactMentionNode';import { CustomCodeNode } from './nodes/CustomCodeNode';import { DateMentionNode } from './nodes/DateMentionNode';import { DiffDeleteNode } from './nodes/DiffDeleteNode';-import { GroupMentionNode } from './nodes/GroupMentionNode';import { DiffInsertNode } from './nodes/DiffInsertNode';import { DiffNode } from './nodes/DiffNode';import { DocumentCardNode } from './nodes/DocumentCardNode';import { DocumentMentionNode } from './nodes/DocumentMentionNode';import { EquationNode } from './nodes/EquationNode';-import { SnapshotNode } from './nodes/SnapshotNode';+import { GroupMentionNode } from './nodes/GroupMentionNode';import { HorizontalRuleNode } from './nodes/HorizontalRuleNode';import { HtmlRenderNode } from './nodes/HtmlRenderNode';import { ImageNode } from './nodes/ImageNode';import { InlineSearchNode } from './nodes/InlineSearchNode';import { SearchMatchNode } from './nodes/SearchMatchNode';+import { SnapshotNode } from './nodes/SnapshotNode';+import { ThemeMentionNode } from './nodes/ThemeMentionNode';+import { UnknownMentionNode } from './nodes/UnknownMentionNode';import { UnlinkedTextNode } from './nodes/UnlinkedTextNode';import { UserMentionNode } from './nodes/UserMentionNode';import { VideoNode } from './nodes/VideoNode';-import { ThemeMentionNode } from './nodes/ThemeMentionNode';-import { UnknownMentionNode } from './nodes/UnknownMentionNode';import { WatermarkNode } from './nodes/WatermarkNode';/**diff --git a/js/lexical-core/plugins/peerIdPlugin.ts b/js/lexical-core/plugins/peerIdPlugin.tsindex 2e71a6cc4c..fe432bd7dc 100644--- a/js/lexical-core/plugins/peerIdPlugin.ts+++ b/js/lexical-core/plugins/peerIdPlugin.ts@@ -17,7 +17,7 @@ import {type NodeKey,type SerializedLexicalNode,} from 'lexical';-import { $isSerializedNode } from '../utils';+import { $isSerializedNode } from '../utils/serializedNode';/*** An update tag that signifies this update only included updates to the local status of nodes.diff --git a/js/lexical-core/transformers/await.ts b/js/lexical-core/transformers/await.tsnew file mode 100644index 0000000000..6fd2dc3806--- /dev/null+++ b/js/lexical-core/transformers/await.ts@@ -0,0 +1,42 @@+import type { TextMatchTransformer } from '@lexical/markdown';+import type { TextNode } from 'lexical';+import {+ $createAwaitNode,+ $isAwaitNode,+ AwaitNode,+} from '../nodes/AwaitNode';++/**+ * Internal transformer for persisted await placeholders.+ *+ * Await nodes are normally inserted by editor commands for local pending work,+ * but server-authored pending messages need an internal markdown sentinel so+ * static channel markdown can render the same placeholder node.+ */+export const I_AWAIT_NODE: TextMatchTransformer = {+ dependencies: [AwaitNode],+ type: 'text-match',+ regExp: /<m-await>(.*?)<\/m-await>/,+ importRegExp: /<m-await>(.*?)<\/m-await>/,+ export: (node) => {+ if (!$isAwaitNode(node)) {+ return null;+ }+ const data = JSON.stringify(node.exportComponentProps());+ return `<m-await>${data}</m-await>`;+ },+ replace: (node: TextNode, match: RegExpMatchArray) => {+ try {+ const data = JSON.parse(match[1]);+ node.replace(+ $createAwaitNode({+ awaitId: typeof data.awaitId === 'string' ? data.awaitId : undefined,+ text: typeof data.text === 'string' ? data.text : undefined,+ inline: typeof data.inline === 'boolean' ? data.inline : true,+ })+ );+ } catch (e) {+ console.error('Error in I_AWAIT_NODE replace:', e);+ }+ },+};diff --git a/js/lexical-core/transformers/index.ts b/js/lexical-core/transformers/index.tsindex 6feaa49c79..61def58cf3 100644--- a/js/lexical-core/transformers/index.ts+++ b/js/lexical-core/transformers/index.ts@@ -1,8 +1,8 @@import type { Transformer } from '@lexical/markdown';+import { I_AWAIT_NODE } from './await';import { I_MACRO_QUOTE } from './classedBlock';import { CUSTOM_TRANSFORMERS } from './customTransformers';import { I_IMAGE_CONSTRAINED, IMAGE } from './image';-import { I_VIDEO } from './video';import {E_BLOCK_EQUATION_NODE,E_INLINE_EQUATION_NODE,@@ -37,6 +37,7 @@ import {SEARCH_MATCH,} from './transformers';import { UNKNOWN_MENTION } from './unknownMention';+import { I_VIDEO } from './video';import { E_WATERMARK, I_WATERMARK } from './watermark';export { isConversionOnlyTransformer };@@ -62,6 +63,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_DOCUMENT_CARD,I_CONTACT_MENTION,I_DATE_MENTION,+ I_AWAIT_NODE,I_TABLE_NODE,I_MACRO_QUOTE,I_EQUATION_NODE,@@ -129,6 +131,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [E_CONTACT_MENTION,I_DATE_MENTION,E_DATE_MENTION,+ I_AWAIT_NODE,I_MACRO_QUOTE,I_EQUATION_NODE,I_THEME_MENTION,diff --git a/js/lexical-core/utils/index.ts b/js/lexical-core/utils/index.tsindex 03ef00f7af..7834c2cf5f 100644--- a/js/lexical-core/utils/index.ts+++ b/js/lexical-core/utils/index.ts@@ -1,22 +1,12 @@import { $isCodeNode } from '@lexical/code';import { $findMatchingParent } from '@lexical/utils';-import type { LexicalNode, SerializedLexicalNode } from 'lexical';+import type { LexicalNode } from 'lexical';export * from './document';export * from './languageSupport';export * from './media';export * from './mentions';--export function $isSerializedNode(- node: LexicalNode | SerializedLexicalNode-): node is SerializedLexicalNode {- return (- typeof node === 'object' &&- 'type' in node &&- typeof node.type === 'string' &&- (node.$ === undefined || typeof node.$ === 'object')- );-}+export * from './serializedNode';export const isEmptyOrMatches = (str: string, regex: RegExp) =>str === '' || regex.test(str);diff --git a/js/lexical-core/utils/serializedNode.ts b/js/lexical-core/utils/serializedNode.tsnew file mode 100644index 0000000000..d9289d9d71--- /dev/null+++ b/js/lexical-core/utils/serializedNode.ts@@ -0,0 +1,12 @@+import type { LexicalNode, SerializedLexicalNode } from 'lexical';++export function $isSerializedNode(+ node: LexicalNode | SerializedLexicalNode+): node is SerializedLexicalNode {+ return (+ typeof node === 'object' &&+ 'type' in node &&+ typeof node.type === 'string' &&+ (node.$ === undefined || typeof node.$ === 'object')+ );+}diff --git a/rust/cloud-storage/.sqlx/query-5202bbfa20ba1bb7f8f28a42e4e35dd42ea503b82a670c2d648a1889eaf6936e.json b/rust/cloud-storage/.sqlx/query-5202bbfa20ba1bb7f8f28a42e4e35dd42ea503b82a670c2d648a1889eaf6936e.jsonnew file mode 100644index 0000000000..a752bf3ee2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-5202bbfa20ba1bb7f8f28a42e4e35dd42ea503b82a670c2d648a1889eaf6936e.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO comms_channel_participants (channel_id, role, user_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (channel_id, user_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ {+ "Custom": {+ "name": "comms_participant_role",+ "kind": {+ "Enum": [+ "owner",+ "admin",+ "member"+ ]+ }+ }+ },+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5202bbfa20ba1bb7f8f28a42e4e35dd42ea503b82a670c2d648a1889eaf6936e"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 6990366e58..f76122230c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1992,6 +1992,26 @@ dependencies = ["rand_core 0.10.1",]+[[package]]+name = "channel_bots"+version = "0.1.0"+dependencies = [+ "agent",+ "ai_tools",+ "ai_toolset",+ "anyhow",+ "async-trait",+ "bot_id",+ "channels",+ "chrono",+ "futures",+ "macro_user_id",+ "models_pagination",+ "tokio",+ "tracing",+ "uuid",+]+[[package]]name = "channels"version = "0.1.0"@@ -3373,6 +3393,7 @@ dependencies = [name = "document_storage_service"version = "0.1.0"dependencies = [+ "ai_tools","analytics_client","anyhow","aws-sdk-dynamodb",@@ -3388,6 +3409,7 @@ dependencies = ["bzip2","cal","call",+ "channel_bots","channels","chrono","clap",@@ -3426,6 +3448,7 @@ dependencies = ["macro_env_var","macro_middleware","macro_project_utils",+ "macro_service_urls","macro_sha_count_client","macro_user_id","macro_uuid",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 91ad27095b..14eaf468d1 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -7,6 +7,7 @@ members = ["backfill_entity_access","bot_id","bots",+ "channel_bots","connection_gateway","contacts_service","convert_service",diff --git a/rust/cloud-storage/bot_id/src/lib.rs b/rust/cloud-storage/bot_id/src/lib.rsindex 4c1ae4af21..e54de67230 100644--- a/rust/cloud-storage/bot_id/src/lib.rs+++ b/rust/cloud-storage/bot_id/src/lib.rs@@ -7,6 +7,21 @@ use uuid::Uuid;const BOT_STORAGE_PREFIX: &str = "bot|";+/// Stable UUID for the first-party "Macro AI" system bot.+///+/// This id is seeded by a migration and referenced directly by services so+/// that Macro AI can be recognized without a database lookup.+pub const MACRO_AI_BOT_UUID: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_a1a1);++/// Stable [`BotId`] for the first-party "Macro AI" system bot.+pub const MACRO_AI_BOT_ID: BotId = BotId::from_uuid(MACRO_AI_BOT_UUID);++/// Stable handle for the "Macro AI" system bot (used for `@` mentions).+pub const MACRO_AI_HANDLE: &str = "macro";++/// Display name for the "Macro" system bot.+pub const MACRO_AI_NAME: &str = "Macro";+/// A bot id.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(transparent)]diff --git a/rust/cloud-storage/channel_bots/Cargo.toml b/rust/cloud-storage/channel_bots/Cargo.tomlnew file mode 100644index 0000000000..9a3d353525--- /dev/null+++ b/rust/cloud-storage/channel_bots/Cargo.toml@@ -0,0 +1,23 @@+[package]+edition = "2024"+name = "channel_bots"+publish = false+version = "0.1.0"++[dependencies]+agent = { path = "../agent" }+ai_tools = { path = "../ai_tools" }+ai_toolset = { path = "../ai_toolset" }+anyhow = { workspace = true }+async-trait = { workspace = true }+bot_id = { path = "../bot_id" }+channels = { path = "../channels", features = ["inbound", "outbound"] }+futures = { workspace = true }+macro_user_id = { path = "../macro_user_id" }+tokio = { workspace = true, features = ["rt", "sync"] }+tracing = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+chrono = { workspace = true }+models_pagination = { path = "../models_pagination" }diff --git a/rust/cloud-storage/channel_bots/src/domain/mod.rs b/rust/cloud-storage/channel_bots/src/domain/mod.rsnew file mode 100644index 0000000000..fe0bba6896--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/domain/mod.rs@@ -0,0 +1,5 @@+//! Domain layer: bot trigger models, ports, and service implementation.++pub mod models;+pub mod ports;+pub mod service;diff --git a/rust/cloud-storage/channel_bots/src/domain/models.rs b/rust/cloud-storage/channel_bots/src/domain/models.rsnew file mode 100644index 0000000000..dd3ad76eb2--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/domain/models.rs@@ -0,0 +1,28 @@+//! Domain models for channel bot triggers.++use channels::domain::models::MutatedMessage;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++/// The kind of event that triggered a bot.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BotTrigger {+ /// The bot was `@`-mentioned in a channel message.+ Mention,+}++/// A normalized trigger delivered to a system bot handler.+#[derive(Debug, Clone)]+pub struct BotEvent {+ /// What triggered the bot.+ pub trigger: BotTrigger,+ /// Channel the trigger occurred in.+ pub channel_id: Uuid,+ /// The user-authored message that triggered the bot.+ pub message: MutatedMessage,+ /// Thread the bot should reply in. For a top-level message this is the+ /// message id; for a reply it is the existing thread id.+ pub reply_thread_id: Uuid,+ /// The user who triggered the bot.+ pub requesting_user: MacroUserIdStr<'static>,+}diff --git a/rust/cloud-storage/channel_bots/src/domain/ports.rs b/rust/cloud-storage/channel_bots/src/domain/ports.rsnew file mode 100644index 0000000000..6ef7cf94f8--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/domain/ports.rs@@ -0,0 +1,10 @@+//! Port definitions for channel bot domain dependencies.++use async_trait::async_trait;++/// Produces an assistant response for a channel message.+#[async_trait]+pub trait AgentResponder: Send + Sync {+ /// Run the agent on behalf of `user_id` with `prompt`, returning the reply.+ async fn respond(&self, user_id: &str, prompt: String) -> anyhow::Result<String>;+}diff --git a/rust/cloud-storage/channel_bots/src/domain/service.rs b/rust/cloud-storage/channel_bots/src/domain/service.rsnew file mode 100644index 0000000000..687167ee59--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/domain/service.rs@@ -0,0 +1,191 @@+//! Domain service for built-in channel bots.++use std::fmt::Write as _;+use std::sync::Arc;++use channels::domain::models::{+ ChannelContextMessage, ParticipantRole, PatchMessageRequest, PostMessageRequest, Sender,+};+use channels::domain::ports::ChannelService;+use uuid::Uuid;++use super::models::BotEvent;+use super::ports::AgentResponder;++/// How many channel messages to include around the trigger.+///+/// Together with the trigger message itself, this yields a bounded nine-message+/// local context window.+const CONTEXT_MESSAGES_BEFORE: i64 = 4;+const CONTEXT_MESSAGES_AFTER: i64 = 4;++/// Human-readable label for a message sender storage id.+fn sender_label(sender_id: &str) -> String {+ if let Ok(bot) = bot_id::BotId::parse_storage_str(sender_id) {+ return if bot == bot_id::MACRO_AI_BOT_ID {+ bot_id::MACRO_AI_NAME.to_string()+ } else {+ "Bot".to_string()+ };+ }+ // User ids look like `macro|<email>`; show the email's local part.+ sender_id+ .rsplit('|')+ .next()+ .unwrap_or(sender_id)+ .split('@')+ .next()+ .unwrap_or(sender_id)+ .to_string()+}++fn append_messages(+ prompt: &mut String,+ heading: &str,+ messages: &[ChannelContextMessage],+ skip: Uuid,+) {+ let mut wrote_heading = false;+ for message in messages {+ if message.id == skip || message.deleted_at.is_some() || message.content.trim().is_empty() {+ continue;+ }+ if !wrote_heading {+ let _ = write!(prompt, "\n{heading}\n");+ wrote_heading = true;+ }+ let _ = writeln!(+ prompt,+ "{}: {}",+ sender_label(&message.sender_id),+ message.content+ );+ }+}++/// Message Macro posts immediately, then replaces with its answer.+///+/// Rendered by the channel markdown as the existing pulsing AwaitNode.+const THINKING_MESSAGE: &str = r#"<m-await>{"text":"Macro is thinking…","inline":true}</m-await>"#;+const EMPTY_RESPONSE_FALLBACK: &str = "I wasn't able to come up with a response.";+const ERROR_FALLBACK: &str = "Sorry — I ran into an error while responding.";++/// In-process handler for the Macro AI system bot.+///+/// Posts an immediate "thinking" reply in a thread, runs the agent loop, then+/// edits that same message with the final answer.+pub struct MacroAiHandler<C, R> {+ channels: Arc<C>,+ responder: Arc<R>,+}++impl<C, R> MacroAiHandler<C, R>+where+ C: ChannelService,+ R: AgentResponder,+{+ /// Create a Macro AI handler.+ pub fn new(channels: Arc<C>, responder: Arc<R>) -> Self {+ Self {+ channels,+ responder,+ }+ }++ /// Build the prompt: who mentioned the agent, local channel context around+ /// the triggering message, and the triggering message itself.+ async fn build_prompt(&self, event: &BotEvent) -> String {+ let mentioner = sender_label(event.requesting_user.as_ref());+ let trigger_id = event.message.id;++ let nearby = self+ .channels+ .get_message_context(+ event.channel_id,+ trigger_id,+ CONTEXT_MESSAGES_BEFORE,+ CONTEXT_MESSAGES_AFTER,+ )+ .await+ .inspect_err(|err| tracing::warn!(error=?err, "failed to load local channel context"))+ .unwrap_or_default();++ let mut prompt = String::new();+ let _ = writeln!(prompt, "{mentioner} mentioned you (@macro) in a channel.");+ append_messages(+ &mut prompt,+ "Channel messages around the mention (oldest to newest):",+ &nearby,+ trigger_id,+ );+ let _ = write!(+ prompt,+ "\n{mentioner} said:\n{}\n\nReply to {mentioner}.",+ event.message.content.trim()+ );+ prompt+ }++ /// React to a Macro AI mention.+ #[tracing::instrument(skip(self, event), fields(channel_id = %event.channel_id), err)]+ pub(crate) async fn handle(&self, event: &BotEvent) -> anyhow::Result<()> {+ let actor = Sender::Bot(bot_id::MACRO_AI_BOT_ID);++ // 1. Gather conversational context (before posting, so our own+ // "thinking" message is not included).+ let prompt = self.build_prompt(event).await;++ // 2. Post the immediate "thinking" message in the thread.+ let thinking = self+ .channels+ .post_message(+ actor.clone(),+ event.channel_id,+ PostMessageRequest {+ content: THINKING_MESSAGE.to_string(),+ mentions: Vec::new(),+ thread_id: Some(event.reply_thread_id),+ attachments: Vec::new(),+ nonce: None,+ },+ )+ .await?;+ let message_id = Uuid::parse_str(&thinking.id)?;++ // 3. Run the agent loop to produce the reply.+ let reply = match self+ .responder+ .respond(event.requesting_user.as_ref(), prompt)+ .await+ {+ Ok(text) if !text.trim().is_empty() => text,+ Ok(_) => EMPTY_RESPONSE_FALLBACK.to_string(),+ Err(err) => {+ tracing::error!(error=?err, "macro ai responder failed");+ ERROR_FALLBACK.to_string()+ }+ };++ // 4. Replace the "thinking" message with the answer.+ self.channels+ .patch_message(+ actor,+ ParticipantRole::Member,+ event.channel_id,+ message_id,+ PatchMessageRequest {+ content: Some(reply),+ mentions: None,+ attachment_ids_to_delete: None,+ attachments_to_add: None,+ nonce: None,+ },+ )+ .await?;++ Ok(())+ }+}++#[cfg(test)]+mod tests;diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rsnew file mode 100644index 0000000000..a9536fb325--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs@@ -0,0 +1,195 @@+use std::sync::{Arc, Mutex};++use async_trait::async_trait;+use channels::domain::models::{+ AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,+ ChannelParticipant, MessagePageDirection, MutatedMessage, ResolvedChannelMessage, Sender,+ ThreadReply,+};+use channels::domain::ports::{+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelService,+};+use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use models_pagination::{CreatedAt, Query};+use uuid::Uuid;++use super::*;+use crate::domain::{+ models::{BotEvent, BotTrigger},+ ports::AgentResponder,+};++struct TestChannelService {+ around_args: Mutex<Option<(Uuid, Uuid, i64, i64)>>,+ around_messages: Vec<ChannelContextMessage>,+}++impl ChannelService for TestChannelService {+ fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _direction: MessagePageDirection,+ _limit: u16,+ _filters: &ChannelMessageFilters,+ _notification_user_id: Option<MacroUserIdStr<'static>>,+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ _attachment_type: Option<ChannelAttachmentType>,+ ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn get_message_context(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ before: i64,+ after: i64,+ ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {+ *self.around_args.lock().unwrap() = Some((channel_id, message_id, before, after));+ let messages = self.around_messages.clone();+ async move { Ok(messages) }+ }++ fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send+ {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _limit: u16,+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }++ fn resolve_message(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for prompt tests") }+ }+}++struct TestResponder;++#[async_trait]+impl AgentResponder for TestResponder {+ async fn respond(&self, _user_id: &str, _prompt: String) -> anyhow::Result<String> {+ unimplemented!("not needed for prompt tests")+ }+}++fn user_id(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()+}++fn context_message(+ channel_id: Uuid,+ id: Uuid,+ sender_id: &str,+ content: &str,+) -> ChannelContextMessage {+ let now = Utc::now();+ ChannelContextMessage {+ id,+ channel_id,+ thread_id: None,+ sender_id: sender_id.to_string(),+ content: content.to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ deleted_at: None,+ }+}++#[tokio::test]+async fn prompt_uses_local_context_around_trigger() {+ let channel_id = Uuid::new_v4();+ let trigger_id = Uuid::new_v4();+ let before_id = Uuid::new_v4();+ let after_id = Uuid::new_v4();+ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: vec![+ context_message(channel_id, before_id, "macro|[email protected]", "before"),+ context_message(+ channel_id,+ trigger_id,+ "macro|[email protected]",+ "@macro help",+ ),+ context_message(channel_id, after_id, "macro|[email protected]", "after"),+ ],+ });+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let event = BotEvent {+ trigger: BotTrigger::Mention,+ channel_id,+ message: MutatedMessage {+ id: trigger_id,+ channel_id,+ thread_id: None,+ sender_id: Sender::User(user_id("[email protected]")),+ content: "@macro help".to_string(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ edited_at: None,+ deleted_at: None,+ },+ reply_thread_id: trigger_id,+ requesting_user: user_id("[email protected]"),+ };++ let prompt = handler.build_prompt(&event).await;++ assert_eq!(+ *channels.around_args.lock().unwrap(),+ Some((+ channel_id,+ trigger_id,+ CONTEXT_MESSAGES_BEFORE,+ CONTEXT_MESSAGES_AFTER+ ))+ );+ assert!(prompt.contains("Channel messages around the mention"));+ assert!(prompt.contains("alice: before"));+ assert!(prompt.contains("bob: after"));+ assert!(!prompt.contains("teo: @macro help"));+ assert!(prompt.contains("teo said:\n@macro help"));+ assert!(!prompt.contains("Recent channel messages"));+ assert!(!prompt.contains("Messages in the thread"));+}diff --git a/rust/cloud-storage/channel_bots/src/inbound/bot_trigger_router.rs b/rust/cloud-storage/channel_bots/src/inbound/bot_trigger_router.rsnew file mode 100644index 0000000000..f81af4e04a--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/inbound/bot_trigger_router.rs@@ -0,0 +1,87 @@+//! Routes channel bot triggers to the appropriate handler.++use std::sync::Arc;++use channels::domain::ports::ChannelService;+use channels::domain::side_effects::ChannelBotTrigger;+use tokio::sync::mpsc::UnboundedReceiver;++use crate::domain::{+ models::{BotEvent, BotTrigger},+ ports::AgentResponder,+ service::MacroAiHandler,+};++/// Resolves the bots mentioned in a channel message and runs their handlers.+///+/// Receives triggers derived by the channel side-effect service. Dispatch is+/// fire-and-forget: each trigger is handled on a spawned task.+///+/// System bots are defined in code and require no database row. Unknown bot ids+/// are ignored for now; only Macro AI is handled by this branch.+pub struct BotTriggerRouter<C, R> {+ macro_ai: Arc<MacroAiHandler<C, R>>,+}++impl<C, R> Clone for BotTriggerRouter<C, R> {+ fn clone(&self) -> Self {+ Self {+ macro_ai: self.macro_ai.clone(),+ }+ }+}++impl<C, R> BotTriggerRouter<C, R>+where+ C: ChannelService,+ R: AgentResponder,+{+ /// Create a router with the built-in system bots registered.+ pub fn new(channels: Arc<C>, responder: Arc<R>) -> Self {+ Self {+ macro_ai: Arc::new(MacroAiHandler::new(channels, responder)),+ }+ }++ /// Start consuming channel bot triggers.+ pub fn spawn(self, mut triggers: UnboundedReceiver<ChannelBotTrigger>)+ where+ R: 'static,+ {+ tokio::spawn(async move {+ while let Some(trigger) = triggers.recv().await {+ let router = self.clone();+ tokio::spawn(async move {+ router.run(trigger).await;+ });+ }+ });+ }++ async fn run(&self, trigger: ChannelBotTrigger) {+ // Guarded upstream, but double-check: only user messages trigger bots.+ let Some(requesting_user) = trigger.message.sender_id.as_user().cloned() else {+ return;+ };+ let reply_thread_id = trigger.message.thread_id.unwrap_or(trigger.message.id);++ for id in &trigger.bot_ids {+ let event = BotEvent {+ trigger: BotTrigger::Mention,+ channel_id: trigger.channel_id,+ message: trigger.message.clone(),+ reply_thread_id,+ requesting_user: requesting_user.clone(),+ };++ // System bots are defined in code — no database lookup required.+ if *id == bot_id::MACRO_AI_BOT_ID {+ if let Err(err) = self.macro_ai.handle(&event).await {+ tracing::error!(error=?err, bot_id = %id, "system bot handler failed");+ }+ } else {+ tracing::debug!(bot_id = %id, "no system bot handler registered for bot trigger");+ }+ }+ }+}diff --git a/rust/cloud-storage/channel_bots/src/inbound/mod.rs b/rust/cloud-storage/channel_bots/src/inbound/mod.rsnew file mode 100644index 0000000000..3fa93dbabb--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/inbound/mod.rs@@ -0,0 +1,5 @@+//! Inbound adapters for channel bot triggers.++mod bot_trigger_router;++pub use bot_trigger_router::BotTriggerRouter;diff --git a/rust/cloud-storage/channel_bots/src/lib.rs b/rust/cloud-storage/channel_bots/src/lib.rsnew file mode 100644index 0000000000..fdf4fa1c05--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/lib.rs@@ -0,0 +1,21 @@+#![deny(missing_docs)]++//! Channel bots: trigger built-in bot behavior from channel events.+//!+//! Channels emit [`ChannelBotTrigger`](channels::domain::side_effects::ChannelBotTrigger)s+//! when a user message mentions one or more bots. The inbound+//! [`BotTriggerRouter`](inbound::BotTriggerRouter) resolves each mentioned+//! system bot and runs the appropriate domain service:+//!+//! * **System bots** (defined inside Macro) run in-process. The only one today+//! is Macro AI, handled by+//! [`MacroAiHandler`](domain::service::MacroAiHandler), which posts an+//! immediate "thinking" message, runs the agent loop, then edits the message+//! with the answer.++/// Domain layer: bot trigger models, ports, and service implementation.+pub mod domain;+/// Inbound adapters for channel bot triggers.+pub mod inbound;+/// Outbound adapters for channel bot dependencies.+pub mod outbound;diff --git a/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rsnew file mode 100644index 0000000000..4acfd7e1fe--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs@@ -0,0 +1,73 @@+//! In-process agent-loop adapter for channel bot responses.++use std::sync::Arc;++use agent::{AgentLoop, StreamPart, to_rig_messages};+use ai_tools::{AiToolSet, ToolServiceContext, ToolSetWithPrompt};+use async_trait::async_trait;+use futures::StreamExt;+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::ports::AgentResponder;++const CHANNEL_SYSTEM_PROMPT: &str = "You are Macro, a helpful assistant participating in a Macro channel. \+You were mentioned in a message and are replying in a thread. The prompt includes channel \+messages around the mention for context, labeled by sender. \+Be concise and directly useful. Use your tools to look things up when helpful. \+Respond in Markdown.";++/// [`AgentResponder`] backed by the in-process agent loop and AI toolset.+pub struct AgentLoopResponder {+ agent_loop: AgentLoop,+ tool_context: Arc<ToolServiceContext>,+ toolset: Arc<AiToolSet>,+ system_prompt: String,+}++impl AgentLoopResponder {+ /// Create a responder from a pre-configured tool context and toolset.+ pub fn new(tool_context: ToolServiceContext, tools: ToolSetWithPrompt) -> Self {+ Self {+ agent_loop: AgentLoop::new(),+ tool_context: Arc::new(tool_context),+ toolset: tools.toolset,+ system_prompt: format!("{CHANNEL_SYSTEM_PROMPT}\n\n{}", tools.prompt),+ }+ }+}++#[async_trait]+impl AgentResponder for AgentLoopResponder {+ #[tracing::instrument(skip(self, prompt, user_id), err)]+ async fn respond(&self, user_id: &str, prompt: String) -> anyhow::Result<String> {+ let user_id = MacroUserIdStr::try_from(user_id.to_string())?;+ let toolset: Arc<dyn ai_toolset::ToolSet<ToolServiceContext> + Send + Sync> =+ self.toolset.clone();++ let mut session = self+ .agent_loop+ .session(+ toolset,+ self.tool_context.clone(),+ &self.system_prompt,+ user_id,+ )+ .await;++ let messages = vec![agent::types::ChatMessage {+ role: agent::types::Role::User,+ content: agent::types::ChatMessageContent::Text(prompt),+ attachments: None,+ }];++ let mut stream = session.send_message(to_rig_messages(&messages)).await?;+ let mut text = String::new();+ while let Some(part) = stream.next().await {+ if let StreamPart::Content(chunk) = part? {+ text.push_str(&chunk);+ }+ }++ Ok(text.trim().to_string())+ }+}diff --git a/rust/cloud-storage/channel_bots/src/outbound/mod.rs b/rust/cloud-storage/channel_bots/src/outbound/mod.rsnew file mode 100644index 0000000000..628915d71b--- /dev/null+++ b/rust/cloud-storage/channel_bots/src/outbound/mod.rs@@ -0,0 +1,5 @@+//! Outbound adapters for channel bot dependencies.++mod agent_loop_responder;++pub use agent_loop_responder::AgentLoopResponder;diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.tomlindex 8747d7c20b..9d3b67182c 100644--- a/rust/cloud-storage/channels/Cargo.toml+++ b/rust/cloud-storage/channels/Cargo.toml@@ -67,7 +67,7 @@ share_permission_db_utils = { path = "../share_permission_db_utils", optional =sqlx = { workspace = true, optional = true }sqs_client = { path = "../sqs_client", default-features = false, features = ["search"], optional = true }thiserror = { workspace = true }-tokio = { workspace = true, features = ["macros"], optional = true }+tokio = { workspace = true, features = ["macros", "sync"], optional = true }tracing = { workspace = true }utoipa = { workspace = true, optional = true }uuid = { workspace = true }diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rsindex e17cbd65db..1a307c3400 100644--- a/rust/cloud-storage/channels/src/domain/side_effects.rs+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs@@ -3,8 +3,8 @@use crate::domain::{events::ChannelEvent,models::{- ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,- MutatedMessage, Sender, SimpleMention, TypingAction,+ BotId, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,+ MutatedAttachment, MutatedMessage, Sender, SimpleMention, TypingAction,},ports::{ChannelContactsDispatcher, ChannelEventDispatcher, ChannelEventHandler,@@ -14,8 +14,54 @@ use crate::domain::{};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use std::collections::HashSet;+use tokio::sync::mpsc::UnboundedSender;use uuid::Uuid;+/// Entity type used by message mentions that target a bot.+pub const BOT_MENTION_ENTITY_TYPE: &str = "bot";++/// A trigger derived from a channel message that mentions one or more bots.+#[derive(Debug, Clone)]+pub struct ChannelBotTrigger {+ /// Channel containing the triggering message.+ pub channel_id: Uuid,+ /// The user-authored message that mentioned the bot(s).+ pub message: MutatedMessage,+ /// Bots mentioned in the message.+ pub bot_ids: Vec<BotId>,+}++/// Sender for bot triggers derived from channel messages.+pub type ChannelBotTriggerSender = UnboundedSender<ChannelBotTrigger>;++/// Collect the bot ids mentioned in a message.+///+/// Bot mentions normally arrive tagged `bot`, but Macro AI is surfaced through+/// the user-mention UI, so a `user` mention whose id is exactly the Macro AI+/// bot is recognized as a bot mention too.+fn bot_mention_ids(mentions: &[SimpleMention]) -> Vec<BotId> {+ let mut seen = HashSet::new();+ mentions+ .iter()+ .filter_map(|mention| match mention.entity_type.as_str() {+ BOT_MENTION_ENTITY_TYPE => BotId::parse_uuid_str(&mention.entity_id).ok(),+ "user" => BotId::parse_uuid_str(&mention.entity_id)+ .ok()+ .filter(|id| *id == bot_id::MACRO_AI_BOT_ID),+ _ => None,+ })+ .filter(|id| seen.insert(*id))+ .collect()+}++/// Whether a `user`-tagged mention actually targets a bot (and so must not be+/// treated as a user recipient). Real user ids are not bare UUIDs, so this only+/// matches the Macro AI bot surfaced through the user-mention UI.+fn is_bot_user_mention(mention: &SimpleMention) -> bool {+ mention.entity_type == "user"+ && BotId::parse_uuid_str(&mention.entity_id).ok() == Some(bot_id::MACRO_AI_BOT_ID)+}+/// Realtime update requested by the channel domain.#[derive(Debug, Clone)]pub enum ChannelRealtimeEffect {@@ -202,6 +248,7 @@ pub struct ChannelSideEffectService<C, R, N, S, K> {notifications: N,search: S,contacts: K,+ bot_triggers: Option<ChannelBotTriggerSender>,}struct MessagePostedSideEffects {@@ -234,6 +281,47 @@ impl<C, R, N, S, K> ChannelSideEffectService<C, R, N, S, K> {notifications,search,contacts,+ bot_triggers: None,+ }+ }++ /// Configure a sender for bot triggers derived from channel messages.+ pub fn with_bot_trigger_sender(mut self, bot_triggers: ChannelBotTriggerSender) -> Self {+ self.bot_triggers = Some(bot_triggers);+ self+ }++ /// Dispatch bot triggers for any bots mentioned in a user-authored message.+ fn dispatch_bot_triggers(+ &self,+ channel_id: Uuid,+ message: &MutatedMessage,+ mentions: &[SimpleMention],+ ) {+ // Only user-authored messages can trigger bots; this prevents bots+ // (including Macro AI) from triggering each other in a loop.+ if message.sender_id.as_user().is_none() {+ return;+ }+ let bot_ids = bot_mention_ids(mentions);+ if bot_ids.is_empty() {+ return;+ }++ if let Some(bot_triggers) = &self.bot_triggers+ && bot_triggers+ .send(ChannelBotTrigger {+ channel_id,+ message: message.clone(),+ bot_ids,+ })+ .is_err()+ {+ tracing::warn!(+ channel_id = %channel_id,+ message_id = %message.id,+ "unable to enqueue channel bot trigger; receiver was dropped"+ );}}}@@ -458,6 +546,7 @@ where}self.search.index_message(channel_id, message.id).await;+ self.dispatch_bot_triggers(channel_id, &message, &mentions);if message.sender_id.is_bot() {return;}@@ -572,7 +661,9 @@ where(Vec::new(), Vec::new()),|(mut users, mut docs), mention| {match mention.entity_type.as_str() {- "user" => users.push(mention.entity_id),+ // The Macro AI bot is mentioned via the user-mention UI; it+ // is handled as a bot trigger, not a user notification.+ "user" if !is_bot_user_mention(&mention) => users.push(mention.entity_id),"document" => docs.push(mention.entity_id),_ => {}}@@ -874,9 +965,17 @@ struct PostedMessageNotificationContext {is_first_top_level_message: bool,}+/// Whether a participant principal id refers to a bot (e.g. `bot|<uuid>`).+/// Bots are not user recipients and are not valid `MacroUserIdStr`s, so they are+/// skipped before parsing to avoid spurious parse warnings.+fn is_bot_principal(id: &str) -> bool {+ BotId::parse_storage_str(id).is_ok()+}+fn participant_ids(participants: &[ChannelParticipant]) -> Vec<MacroUserIdStr<'static>> {participants.iter()+ .filter(|p| !is_bot_principal(&p.user_id)).filter_map(|p| MacroUserIdStr::parse_from_str(&p.user_id).ok()).map(|id| id.into_owned()).collect()@@ -890,6 +989,7 @@ fn recipients_excluding<'a>(recipients.into_iter().filter(move |id| !exclude_set.contains(id))+ .filter(|id| !is_bot_principal(id)).filter_map(|id| MacroUserIdStr::parse_from_str(id).ok()).map(|u| u.into_owned())}@@ -1210,6 +1310,79 @@ mod tests {assert!(notifications.effects.lock().unwrap().is_empty());}+ #[tokio::test]+ async fn user_message_with_bot_mention_enqueues_bot_trigger() {+ let channel_id = Uuid::new_v4();+ let message_id = Uuid::new_v4();+ let sender = user("[email protected]");+ let recipient = user("[email protected]");+ let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();+ let service = ChannelSideEffectService::new(+ FakeContext {+ message_count: 2,+ document_mentions: Vec::new(),+ },+ FakeRealtime::default(),+ FakeNotifications::default(),+ FakeSearch::default(),+ FakeContacts::default(),+ )+ .with_bot_trigger_sender(bot_trigger_sender);+ let now = Utc::now();++ service+ .handle(ChannelEvent::MessagePosted {+ channel_id,+ metadata: ChannelMetadata {+ channel_type: ChannelType::Private,+ channel_name: "Project".to_string(),+ },+ participants: vec![+ ChannelParticipant {+ channel_id,+ user_id: sender.as_ref().to_string(),+ role: ParticipantRole::Member,+ joined_at: now,+ left_at: None,+ },+ ChannelParticipant {+ channel_id,+ user_id: recipient.as_ref().to_string(),+ role: ParticipantRole::Member,+ joined_at: now,+ left_at: None,+ },+ ],+ message: MutatedMessage {+ id: message_id,+ channel_id,+ thread_id: None,+ sender_id: Sender::User(sender),+ content: "@macro help".to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ deleted_at: None,+ },+ mentions: vec![SimpleMention {+ entity_type: "user".to_string(),+ entity_id: bot_id::MACRO_AI_BOT_ID.to_string(),+ }],+ has_attachments: false,+ attachments: Vec::new(),+ nonce: None,+ })+ .await;++ let trigger = bot_trigger_receiver+ .try_recv()+ .expect("expected bot trigger");+ assert_eq!(trigger.channel_id, channel_id);+ assert_eq!(trigger.message.id, message_id);+ assert_eq!(trigger.bot_ids, vec![bot_id::MACRO_AI_BOT_ID]);+ assert!(bot_trigger_receiver.try_recv().is_err());+ }+#[tokio::test]async fn document_mentions_notify_participants_except_sender() {let channel_id = Uuid::new_v4();@@ -1382,4 +1555,53 @@ mod tests {assert!(contact_sync_users_for_event(&event).is_none());}++ fn mention(entity_type: &str, entity_id: &str) -> SimpleMention {+ SimpleMention {+ entity_type: entity_type.to_string(),+ entity_id: entity_id.to_string(),+ }+ }++ #[test]+ fn bot_mentions_recognize_bot_and_macro_ai_user_tags() {+ let macro_ai = bot_id::MACRO_AI_BOT_ID.as_uuid().to_string();+ let other_bot = Uuid::new_v4().to_string();+ let mentions = vec![+ // Macro AI surfaced through the user-mention UI.+ mention("user", ¯o_ai),+ // Duplicate bot mentions are dispatched once.+ mention("user", ¯o_ai),+ // A real user mention is ignored.+ mention("user", "macro|[email protected]"),+ // An explicitly bot-tagged mention.+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot),+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot),+ ];++ let bots = bot_mention_ids(&mentions);+ assert_eq!(+ bots,+ vec![+ bot_id::MACRO_AI_BOT_ID,+ BotId::parse_uuid_str(&other_bot).unwrap()+ ]+ );+ }++ #[test]+ fn macro_ai_user_mention_is_not_a_user_recipient() {+ assert!(is_bot_user_mention(&mention(+ "user",+ &bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()+ )));+ assert!(!is_bot_user_mention(&mention(+ "user",+ "macro|[email protected]"+ )));+ assert!(is_bot_principal(+ &bot_id::MACRO_AI_BOT_ID.to_storage_string()+ ));+ assert!(!is_bot_principal("macro|[email protected]"));+ }}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsindex 142ec7a363..9c8f01cfa6 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -75,6 +75,17 @@ impl<S: ChannelService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {access_service: Arc::new(access_service),}}++ /// Create a router state from an already-shared channel service.+ ///+ /// Used when the channel service must also be shared with other components+ /// (such as the bot trigger dispatcher) that post messages through it.+ pub fn from_arc(service: Arc<S>, access_service: Svc) -> Self {+ Self {+ service,+ access_service: Arc::new(access_service),+ }+ }}impl<S, Svc> FromRef<ChannelsRouterState<S, Svc>> for Arc<Svc> {diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex 0f08bf8822..871ef4457c 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -109,7 +109,7 @@ fn api_router(api_context: ApiContext) -> Router {macro_middleware::auth::initialize_user_context::handler,)).layer(axum::middleware::from_fn_with_state(- api_context.jwt_args,+ api_context.jwt_args.clone(),macro_middleware::auth::attach_user::handler,)),);diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex aa2d51c902..74ef0ca924 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -26,6 +26,7 @@ location_check = [][dependencies]anyhow = { workspace = true }+ai_tools = { path = "../ai_tools" }aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }@@ -42,6 +43,7 @@ bzip2 = { workspace = true, default-features = false, features = [analytics_client = { path = "../analytics_client" }cal = { path = "../cal", features = ["axum", "outbound"] }call = { path = "../call" }+channel_bots = { path = "../channel_bots" }channels = { path = "../channels", features = ["inbound", "outbound"] }chrono = { workspace = true }clap = { workspace = true }@@ -84,6 +86,7 @@ macro_cors = { path = "../macro_cors" }macro_db_client = { path = "../macro_db_client" }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env" }+macro_service_urls = { path = "../macro_service_urls" }macro_env_var = { path = "../macro_env_var" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["auth",diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 28c23343ab..0e3411e28b 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -586,21 +586,40 @@ async fn main() -> anyhow::Result<()> {)),));let channels_repo = PgChannelsRepo::new(db.clone());- let bots_service = bots::domain::service::BotServiceImpl::new(- bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone()),- );+ let bots_repo = bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone());+ let bots_service = bots::domain::service::BotServiceImpl::new(bots_repo.clone());+ let (bot_trigger_sender, bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();++ let channel_side_effects = ChannelSideEffectService::new(+ PgChannelSideEffectContext::new(db.clone()),+ ConnectionGatewayChannelRealtimePublisher::new(conn_gateway_client.clone()),+ NotificationChannelSender::new(notification_ingress_service.clone()),+ SqsChannelSearchIndexer::new(sqs_client.clone()),+ ContactsChannelDispatcher::new(contacts_ingress.clone()),+ )+ .with_bot_trigger_sender(bot_trigger_sender);- let channels_service = ChannelServiceImpl::with_dependencies(+ let channels_service = Arc::new(ChannelServiceImpl::with_dependencies(channels_repo,- SpawnedChannelEventDispatcher::new(ChannelSideEffectService::new(- PgChannelSideEffectContext::new(db.clone()),- ConnectionGatewayChannelRealtimePublisher::new(conn_gateway_client.clone()),- NotificationChannelSender::new(notification_ingress_service.clone()),- SqsChannelSearchIndexer::new(sqs_client.clone()),- ContactsChannelDispatcher::new(contacts_ingress.clone()),- )),+ SpawnedChannelEventDispatcher::new(channel_side_effects),PgChannelReferenceSharePermissions::new(db.clone(), entity_access_service.clone()),+ ));++ // Wire Macro AI to react to mentions. The router posts replies through the+ // channel service we just built and runs the agent loop in-process with the+ // same pre-configured toolset used by other AI hosts.+ let macro_agent_tool_context = ai_tools::build_tool_service_context_from_env(db.clone())+ .await+ .context("failed to build Macro agent tool context")?;+ let macro_agent_tools = ai_tools::all_tools();+ let bot_trigger_router = channel_bots::inbound::BotTriggerRouter::new(+ channels_service.clone(),+ Arc::new(channel_bots::outbound::AgentLoopResponder::new(+ macro_agent_tool_context,+ macro_agent_tools,+ )),);+ bot_trigger_router.spawn(bot_trigger_receiver);let api_context = ApiContext {contacts_ingress: contacts_ingress.clone(),@@ -650,7 +669,7 @@ async fn main() -> anyhow::Result<()> {documents_hex::outbound::document_bytes_upload::ReqwestDocumentBytesUploader::default(),),},- channels_state: ChannelsRouterState::new(+ channels_state: ChannelsRouterState::from_arc(channels_service,(*entity_access_service).clone(),),