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
import { $dfsIterator } from '@lexical/utils';
import { $getRoot, type LexicalNode } from 'lexical';
import { match, P } from 'ts-pattern';
import type { Widget_Serialize as Widget } from '../generated/dynamic-ui';
import {
$isAgentActivityNode,
isAgentActivityCard,
} from '../nodes/AgentActivityNode';
import {
$isAgentSessionMentionNode,
type AgentSessionMentionInfo,
type AgentSessionMentionNode,
buildAgentSessionMentionMarkdown,
} from '../nodes/AgentSessionMentionNode';
import {
$isContactMentionNode,
type ContactMentionInfo,
type ContactMentionNode,
} from '../nodes/ContactMentionNode';
import {
$isDateMentionNode,
type DateMentionInfo,
type DateMentionNode,
} from '../nodes/DateMentionNode';
import { $isDocumentCardNode } from '../nodes/DocumentCardNode';
import {
$isDocumentMentionNode,
type DocumentMentionInfo,
type DocumentMentionNode,
} from '../nodes/DocumentMentionNode';
import {
$isGroupMentionNode,
type GroupMentionNode,
} from '../nodes/GroupMentionNode';
import {
$isPullRequestMentionNode,
type PullRequestMentionInfo,
type PullRequestMentionNode,
} from '../nodes/PullRequestMentionNode';
import type { TagMentionInfo } from '../nodes/TagMentionNode';
import {
$isUserMentionNode,
type UserMentionInfo,
type UserMentionNode,
} from '../nodes/UserMentionNode';
import { wrapXml } from '../transformers/transformers';
import { messageReference } from './message-references';
function dropKey<T extends object, K extends keyof T>(
obj: T,
key: K
): Omit<T, K> {
const { [key]: _, ...rest } = obj;
return rest;
}
export type MentionNode =
| UserMentionNode
| DocumentMentionNode
| ContactMentionNode
| DateMentionNode
| AgentSessionMentionNode
| PullRequestMentionNode
| GroupMentionNode;
export function $isMentionNode(node: LexicalNode): node is MentionNode {
return (
$isUserMentionNode(node) ||
$isDocumentMentionNode(node) ||
$isContactMentionNode(node) ||
$isDateMentionNode(node) ||
$isAgentSessionMentionNode(node) ||
$isPullRequestMentionNode(node) ||
$isGroupMentionNode(node)
);
}
export function $extractAllMentions(): MentionNode[] {
const iterator = $dfsIterator($getRoot());
const out: MentionNode[] = [];
for (const { node } of iterator) {
if ($isMentionNode(node)) {
out.push(node);
}
}
return out;
}
/** An entity mention in the shape channel messages send to the backend. */
export type ChannelMention = {
entityType: string;
entityId: string;
};
/**
* Entity type for a document-mention block name, mirroring
* `$mentionItemFromNode` in the web editor's mentions plugin. Plain file
* block names (md, pdf, csv, ...) and unknown block names are all
* `document`.
*/
function documentMentionEntityType(blockName: string): string {
return (
match(blockName)
.with(
P.union(
'channel',
'project',
'chat',
'call',
'automation',
'form',
'database',
'external_chat'
),
(kind) => kind
)
// A routine is still referenced under its old item type.
.with('routine', () => 'automation')
.with('email', () => 'thread')
.with('calendar', () => 'calendar_event')
.with('company', () => 'crm_company')
.with('contact', () => 'crm_contact')
// A task project. Not a message reference type, so it is dropped below.
.with('initiative', () => 'initiative')
// Dropped below for the same reason.
.with('pipeline', () => 'crm_pipeline')
.with(P._, () => 'document')
.exhaustive()
);
}
/** The forms in a presented view's cards, nested containers included. */
function viewFormIds(widgets: readonly Widget[]): string[] {
return widgets.flatMap((widget) =>
match(widget)
.with({ type: 'cards' }, ({ items }) =>
items.filter((item) => item.type === 'form').map((item) => item.id)
)
.with({ type: 'container' }, ({ children }) => viewFormIds(children))
.otherwise(() => [])
);
}
/**
* Extracts the mentions in the current editor state as `ChannelMention`s,
* the way the web editor tracks them while composing a channel message.
* Document mentions map by block name; user mentions are re-tagged `bot`
* when they target a bot principal. Contact, date, and PR mentions
* carry no referencable entity and are skipped. Project (initiative) and CRM
* pipeline mentions are skipped too: channel references auto-share their
* target with members.
* Authored group mentions are preserved. Forms an agent reply presents as
* cards in its steps count as references, like a posted form card, so
* channel delivery can share them. Duplicates are dropped.
*/
export function $extractChannelMentions(): ChannelMention[] {
const out: ChannelMention[] = [];
const seen = new Set<string>();
const push = (raw: ChannelMention) => {
const mention = messageReference(raw.entityType, raw.entityId);
if (!mention?.entityId) return;
const key = `${mention.entityType}:${mention.entityId}`;
if (seen.has(key)) return;
seen.add(key);
out.push(mention);
};
for (const { node } of $dfsIterator($getRoot())) {
if (
$isDocumentMentionNode(node) ||
($isDocumentCardNode(node) &&
(node.getBlockName() === 'form' || node.getBlockName() === 'database'))
) {
push({
entityType: documentMentionEntityType(node.getBlockName()),
entityId: node.getDocumentId(),
});
} else if ($isAgentActivityNode(node)) {
for (const row of node.exportComponentProps().rows) {
if (!isAgentActivityCard(row.card)) continue;
for (const formId of viewFormIds(row.card.view.widgets)) {
push({ entityType: 'form', entityId: formId });
}
}
} else if ($isAgentSessionMentionNode(node)) {
push({ entityType: 'agent_session', entityId: node.getId() });
} else if ($isGroupMentionNode(node)) {
push({ entityType: 'group', entityId: node.getGroupAlias() });
} else if ($isUserMentionNode(node)) {
const userId = node.getUserId();
push({
entityType: userId.startsWith('bot|') ? 'bot' : 'user',
entityId: userId,
});
}
}
return out;
}
export type MentionInfo =
| (UserMentionInfo & { type: 'user' })
| (DocumentMentionInfo & { type: 'document' })
| (AgentSessionMentionInfo & { type: 'agent_session' })
| (PullRequestMentionInfo & { type: 'pr' })
| (ContactMentionInfo & { type: 'contact' })
| (DateMentionInfo & { type: 'date' })
| (TagMentionInfo & { type: 'tag' });
export function buildMentionMarkdownString(info: MentionInfo): string {
switch (info.type) {
case 'user':
return wrapXml('m-user-mention', dropKey(info, 'type'));
case 'document':
return wrapXml('m-document-mention', dropKey(info, 'type'));
case 'agent_session':
return buildAgentSessionMentionMarkdown(dropKey(info, 'type'));
case 'pr':
return wrapXml('m-pr-mention', dropKey(info, 'type'));
case 'contact':
return wrapXml('m-contact-mention', dropKey(info, 'type'));
case 'date':
return wrapXml('m-date-mention', dropKey(info, 'type'));
case 'tag':
return wrapXml('m-tag', dropKey(info, 'type'));
}
}
export {
markdownToEmbeddingText,
markdownToPlainText,
parseContactMentions,
parseDateMentions,
parseDocumentMentions,
parseGroupMentions,
parseLinks,
parsePullRequestMentions,
parseReplyTargets,
parseTagMentions,
parseUserMentions,
} from './parsers';