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(editor): add booking link mention pill with smart paste (#8038)
Jacob Beckerman3b8c537691ba
diff --git a/apps/docs/AI/mcp/tools/create-booking-link.mdx b/apps/docs/AI/mcp/tools/create-booking-link.mdxindex 603d17d92c..024ffbd872 100644--- a/apps/docs/AI/mcp/tools/create-booking-link.mdx+++ b/apps/docs/AI/mcp/tools/create-booking-link.mdx@@ -6,7 +6,7 @@ description: >-# CreateBookingLink-Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.+Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an \<m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.## Parametersdiff --git a/apps/docs/AI/mcp/tools/edit-booking-link.mdx b/apps/docs/AI/mcp/tools/edit-booking-link.mdxindex 0b106a46dd..194e0d1075 100644--- a/apps/docs/AI/mcp/tools/edit-booking-link.mdx+++ b/apps/docs/AI/mcp/tools/edit-booking-link.mdx@@ -6,7 +6,7 @@ description: >-# EditBookingLink-Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.+Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an \<m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.## Parametersdiff --git a/apps/docs/AI/mcp/tools/edit-document.mdx b/apps/docs/AI/mcp/tools/edit-document.mdxindex 999b93cff7..590501e599 100644--- a/apps/docs/AI/mcp/tools/edit-document.mdx+++ b/apps/docs/AI/mcp/tools/edit-document.mdx@@ -7,12 +7,12 @@ description: >-# EditDocument-Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.+Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- || `document_id` | string | Yes | The ID of the markdown document to edit. If you are not certain the document is markdown, call ReadMetadata first and check that `fileType` is `md` -- passing an uploaded file here fails. |-| `instructions` | string | Yes | Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up. |+| `instructions` | string | Yes | Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips; profileId/slug/url for booking links. For document-card(s), include documentId and documentName per document. You may need to look these up. || `fast` | boolean | No | Set true for one quick, contained edit -- rewrite this paragraph, translate the selected list, fix a heading, bold a phrase. A single model applies it directly in a few seconds. Leave false (the default) for anything with several parts or that restructures the document; the default pipeline plans, dispatches, and reviews its own work, which takes longer but is what multi-step edits need. |diff --git a/apps/docs/AI/mcp/tools/list-booking-links.mdx b/apps/docs/AI/mcp/tools/list-booking-links.mdxindex d961d61917..b6f0d25e01 100644--- a/apps/docs/AI/mcp/tools/list-booking-links.mdx+++ b/apps/docs/AI/mcp/tools/list-booking-links.mdx@@ -6,7 +6,7 @@ description: >-# ListBookingLinks-Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings.+Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings. When sharing a returned URL in Markdown, use an \<m-booking-link-mention> chip with profileId/slug/url, not a bare URL.## Parametersdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsxindex a145ff9538..b9c98c7c7f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx@@ -23,6 +23,18 @@ vi.mock('../decorator/AgentSessionMention', () => ({},}));+vi.mock('../decorator/BookingLinkMention', () => ({+ BookingLinkMention: (props: {+ profileId: string;+ slug?: string;+ url: string;+ }) => (+ <span data-test-booking-link={props.profileId} data-test-url={props.url}>+ {props.slug ?? props.profileId}+ </span>+ ),+}));+vi.mock('../decorator/PullRequestMention', () => ({PullRequestMention: (props: { id: string; url?: string; label?: string }) => (<span data-pr-chip={props.id || props.url}>{props.label}</span>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 09a8537324..15af32bbb5 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -14,6 +14,7 @@ import {type AgentContextNode,type AgentSessionMentionNode,type AwaitNode,+ type BookingLinkMentionNode,type ClassedBlockNode,type ConnectAppNode,type ContactMentionNode,@@ -85,6 +86,7 @@ import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';import { AgentContext as AgentContextDecorator } from '../decorator/AgentContext';import { AgentSessionMention as AgentSessionMentionDecorator } from '../decorator/AgentSessionMention';import { Await as AwaitDecorator } from '../decorator/Await';+import { BookingLinkMention as BookingLinkMentionDecorator } from '../decorator/BookingLinkMention';import { ConnectApp as ConnectAppDecorator } from '../decorator/ConnectApp';import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';import { CursorSystemNotification as CursorSystemNotificationDecorator } from '../decorator/CursorSystemNotification';@@ -249,6 +251,7 @@ function getTextClassName(| DocumentMentionNode| AgentSessionMentionNode| PullRequestMentionNode+ | BookingLinkMentionNode| ContactMentionNode| DateMentionNode| WatermarkNode,@@ -437,6 +440,20 @@ const PullRequestMention: TypedRenderableEntity<PullRequestMentionNode> = {),};+const BookingLinkMention: TypedRenderableEntity<BookingLinkMentionNode> = {+ guard: (node: LexicalNode): node is BookingLinkMentionNode =>+ node.__type === 'booking-link-mention',+ render: (props) => (+ <span class={getTextClassName(props.node, props.theme)}>+ <BookingLinkMentionDecorator+ {...props.node.exportComponentProps()}+ key={props.node.getKey()}+ theme={props.theme}+ />+ </span>+ ),+};+const ThemeMention: TypedRenderableEntity<ThemeMentionNode> = {guard: (node: LexicalNode): node is ThemeMentionNode =>node.__type === 'theme-mention',@@ -992,6 +1009,7 @@ const InlineEntities: RenderableEntity[] = [eraseRenderableEntity(DocumentMention),eraseRenderableEntity(AgentSessionMention),eraseRenderableEntity(PullRequestMention),+ eraseRenderableEntity(BookingLinkMention),eraseRenderableEntity(DocumentCard),eraseRenderableEntity(ContactMention),eraseRenderableEntity(DateMention),diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/BookingLinkMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/BookingLinkMention.tsxnew file mode 100644index 0000000000..5c288fd2bf--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/BookingLinkMention.tsx@@ -0,0 +1,186 @@+import { HoverCard } from '@core/component/HoverCard';+import { openExternalUrl } from '@core/util/url';+import { useNativeSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';+import {+ $isBookingLinkMentionNode,+ type BookingLinkMentionDecoratorProps,+ HISTORIC_TAG,+ parseBookingUrl,+ SKIP_DOM_SELECTION_TAG,+ SKIP_SCROLL_INTO_VIEW_TAG,+} from '@macro-inc/lexical-core';+import OpenIcon from '@phosphor/arrows-out.svg';+import CalendarBlank from '@phosphor/calendar-blank.svg';+import { cn, Surface } from '@ui';+import {+ $getNodeByKey,+ COMMAND_PRIORITY_NORMAL,+ KEY_ENTER_COMMAND,+} from 'lexical';+import { createEffect, createMemo, Show, useContext } from 'solid-js';+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';+import { autoRegister } from '../../plugins';+import { MentionTooltip } from './MentionTooltip';++function BookingLinkIcon(props: { class?: string }) {+ return <CalendarBlank class={cn('size-full text-accent', props.class)} />;+}++function fallbackLabel(props: BookingLinkMentionDecoratorProps): string {+ if (props.label) return props.label;+ if (props.slug) return props.slug;+ const parsed = parseBookingUrl(props.url);+ if (parsed?.slug) return parsed.slug;+ return 'Booking link';+}++function BookingLinkPreviewCard(props: {+ label: string;+ url: string;+ profileId: string;+ slug?: string;+}) {+ return (+ <div class="select-none w-72 text-ink">+ <Surface depth={3} class="glass bg-menu-glass rounded-xl">+ <div class="w-full flex flex-col">+ <div class="flex items-center justify-between gap-2 p-2">+ <div class="flex items-center gap-2 min-w-0">+ <span class="relative size-4 shrink-0 inline-flex">+ <BookingLinkIcon />+ </span>+ <span class="text-sm font-semibold truncate">{props.label}</span>+ </div>+ <a+ href={props.url}+ target="_blank"+ rel="noreferrer"+ class="shrink-0 text-link hover:text-link-hover visited:text-link-visited"+ onClick={(e) => e.stopPropagation()}+ >+ <OpenIcon class="size-4" />+ </a>+ </div>+ <Show when={props.slug}>+ <div class="px-2 pb-2 text-xs text-ink-muted truncate">+ /{props.slug}+ </div>+ </Show>+ </div>+ </Surface>+ </div>+ );+}++function BookingLinkMentionContent(props: BookingLinkMentionDecoratorProps) {+ const lexicalWrapper = useContext(LexicalWrapperContext);+ const editor = lexicalWrapper?.editor;++ const label = createMemo(() => fallbackLabel(props));++ createEffect(() => {+ const nextLabel = label();+ const labelChanged = !!nextLabel && nextLabel !== props.label;+ if (!editor || !labelChanged) return;++ editor.update(+ () => {+ const node = $getNodeByKey(props.key);+ if ($isBookingLinkMentionNode(node)) {+ node.setLabel(nextLabel);+ }+ },+ {+ tag: [HISTORIC_TAG, SKIP_DOM_SELECTION_TAG, SKIP_SCROLL_INTO_VIEW_TAG],+ discrete: true,+ }+ );+ });++ return (+ <span+ data-booking-link-mention="true"+ data-booking-profile-id={props.profileId}+ data-booking-label={label()}+ class="pointer-events-auto inline-flex max-w-[min(20em,100%)] items-baseline"+ >+ <span class="relative top-[0.125em] size-[1em] shrink-0 inline-flex mx-1">+ <BookingLinkIcon />+ </span>+ <span class="flex min-w-0 items-baseline underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">+ <span class="min-w-0 truncate">{label()}</span>+ <Show when={props.slug && label() !== props.slug}>+ <span class="shrink-0 whitespace-pre text-ink-extra-muted text-[0.8em]">+ {` /${props.slug}`}+ </span>+ </Show>+ </span>+ </span>+ );+}++export function BookingLinkMention(props: BookingLinkMentionDecoratorProps) {+ const lexicalWrapper = useContext(LexicalWrapperContext);+ const editor = lexicalWrapper?.editor;+ const selection = () => lexicalWrapper?.selection;++ const isSelectedAsNode = () => {+ const sel = selection();+ if (!sel) return false;+ return sel.type === 'node' && sel.nodeKeys.has(props.key);+ };++ // Booking pages are full-page public routes outside the split layout, so+ // open the shareable URL the same way an unsynced PR falls back to GitHub.+ const open = (_e: MouseEvent | KeyboardEvent | null) => {+ openExternalUrl(props.url);+ };++ if (editor) {+ autoRegister(+ editor.registerCommand(+ KEY_ENTER_COMMAND,+ (e) => {+ if (isSelectedAsNode()) {+ open(e);+ return true;+ }+ return false;+ },+ COMMAND_PRIORITY_NORMAL+ )+ );+ }++ const navHandlers = useNativeSplitNavigationHandler<HTMLSpanElement>((e) => {+ e.stopPropagation();+ open(e);+ });++ return (+ <HoverCard+ trigger={+ <span class="relative">+ <span+ class={cn(+ 'size-full py-0.5 cursor-default rounded-xs hover:bg-hover focus:bg-active',+ isSelectedAsNode() && 'bg-active text-ink'+ )}+ {...navHandlers}+ >+ <BookingLinkMentionContent {...props} />+ </span>+ <MentionTooltip show={isSelectedAsNode()} text="Open" />+ </span>+ }+ content={+ <BookingLinkPreviewCard+ label={fallbackLabel(props)}+ url={props.url}+ profileId={props.profileId}+ slug={props.slug}+ />+ }+ />+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.tsindex 5038cd1474..ca5e406171 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts@@ -3,6 +3,7 @@ import {AgentContextNode,AgentSessionMentionNode,AwaitNode,+ BookingLinkMentionNode,ConnectAppNode,ContactMentionNode,CursorSystemNotificationNode,@@ -37,6 +38,7 @@ import { createComponent, Suspense } from 'solid-js';import { AgentContext } from './component/decorator/AgentContext';import { AgentSessionMention } from './component/decorator/AgentSessionMention';import { Await } from './component/decorator/Await';+import { BookingLinkMention } from './component/decorator/BookingLinkMention';import { ConnectApp } from './component/decorator/ConnectApp';import { ContactMention } from './component/decorator/ContactMention';import { CursorSystemNotification } from './component/decorator/CursorSystemNotification';@@ -88,6 +90,7 @@ export function initializeLexical() {setDecorator(DocumentCardNode, DocumentCard);setDecorator(PasteNodeClass, PasteNode);setDecorator(PullRequestMentionNode, PullRequestMention);+ setDecorator(BookingLinkMentionNode, BookingLinkMention);setDecorator(AgentSessionMentionNode, AgentSessionMention);setDecorator(ReplyTargetNode, ReplyTarget);setDecorator(ContactMentionNode, ContactMention);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.tsindex c635a57cf9..3c877dcad3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts@@ -15,12 +15,16 @@ import { $isCodeNode } from '@lexical/code';import { $createLinkNode, $isLinkNode, LinkNode } from '@lexical/link';import { $findMatchingParent, mergeRegister } from '@lexical/utils';import {+ $createBookingLinkMentionNode,$createPasteNode,$createPullRequestMentionNode,$isCustomCodeNode,+ BookingLinkMentionNode,HISTORY_MERGE_TAG,+ isMacroBookingUrl,PasteNode,PullRequestMentionNode,+ parseBookingUrl,} from '@macro-inc/lexical-core';import {fetchPullRequestByGithubKey,@@ -299,6 +303,34 @@ function registerTextPastePlugin(return true;}+ const trimmedPaste = pastedText.trim();+ if (+ isMacroBookingUrl(trimmedPaste) &&+ editor.hasNode(BookingLinkMentionNode)+ ) {+ const selection = $getSelection();+ if (+ !$isRangeSelection(selection) ||+ !selection.isCollapsed() ||+ $isSelectionInCode()+ ) {+ return false;+ }++ const parsed = parseBookingUrl(trimmedPaste);+ if (parsed) {+ event.preventDefault();+ const mention = $createBookingLinkMentionNode({+ profileId: parsed.profileId,+ slug: parsed.slug,+ label: parsed.slug,+ url: trimmedPaste,+ });+ $insertNodes([mention]);+ return true;+ }+ }+const parsedMacroAppUrl = resolvePastedMacroAppUrl(pastedText,resolveAppLinkdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex e81bcc1411..97bfc5ac5b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -33,5 +33,6 @@* (persisted check-list task filters).* Version 7.1 - Oct 2026. PullRequestMentionNode: optional GitHub `url`; `id` may be empty* when an agent mentions a PR by URL, and the decorator resolves the synced PR.+ * Version 8.0 - Oct 2026. Added BookingLinkMentionNode for Macro `/app/book/…` URLs.*/-export const MARKDOWN_VERSION_COUNTER = 7.1;+export const MARKDOWN_VERSION_COUNTER = 8.0;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex d190b33628..d25c74c25c 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@@ -6204,7 +6204,7 @@ export interface SearchGotoAgentSession {author: AgentSessionAuthor;}/**- * Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.+ * Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an <m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.*/export interface CreateBookingLink {/**@@ -8169,7 +8169,7 @@ export interface DuplicateItemResponse {message: string;}/**- * Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.+ * Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an <m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.*/export interface EditBookingLink {/**@@ -8226,7 +8226,7 @@ export interface EditChannelMessageResponse {summary: string;}/**- * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.+ * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.*/export interface EditDocument {/**@@ -8234,7 +8234,7 @@ export interface EditDocument {*/document_id: string;/**- * Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up.+ * Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips; profileId/slug/url for booking links. For document-card(s), include documentId and documentName per document. You may need to look these up.*/instructions: string;/**@@ -9971,7 +9971,7 @@ export interface ListAgentsResponse {summary: string;}/**- * Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings.+ * Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings. When sharing a returned URL in Markdown, use an <m-booking-link-mention> chip with profileId/slug/url, not a bare URL.*/export interface ListBookingLinks {/**diff --git a/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rsindex ea596de607..971952e26f 100644--- a/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs+++ b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs@@ -12,7 +12,7 @@ use uuid::Uuid;#[serde(rename_all = "camelCase", deny_unknown_fields)]#[schemars(title = "CreateBookingLink",- description = "Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation."+ description = "Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an <m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.")]pub struct CreateBookingLink {/// Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.diff --git a/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rsindex e1c2490711..55b93d85d2 100644--- a/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs+++ b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs@@ -12,7 +12,7 @@ use uuid::Uuid;#[serde(rename_all = "camelCase", deny_unknown_fields)]#[schemars(title = "EditBookingLink",- description = "Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation."+ description = "Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location, Macro call, or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. After execution, share the saved URL with an <m-booking-link-mention> chip (profileId/slug/url from the result), not a bare URL. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar. For video, set macroCall (preferred) or googleMeet, never both. Booking a macroCall link creates the call and attaches its join link to the invitation.")]pub struct EditBookingLink {/// Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.diff --git a/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs b/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rsindex 519f438fb4..9447ce8adf 100644--- a/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs+++ b/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs@@ -12,7 +12,7 @@ use uuid::Uuid;#[serde(rename_all = "camelCase", deny_unknown_fields)]#[schemars(title = "ListBookingLinks",- description = "Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings."+ description = "Discover and reuse the user's booking links before creating one. Returns shareable URLs, enabled/paused state, full drafts and revision for EditBookingLink, plus reusable availability schedules and the user's host ID. Searches title, slug and description; omit query for all (at most 100). Omit teamId for personal links; use a team ID returned in teamIds for team links. This read never creates settings. These are reusable scheduling pages, not calendar meetings. When sharing a returned URL in Markdown, use an <m-booking-link-mention> chip with profileId/slug/url, not a bare URL.")]pub struct ListBookingLinks {/// Existing Macro team ID, or null for personal links.diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rsindex cd9a9ec1ab..304314ef49 100644--- a/crates/documents/src/inbound/toolset/edit_document.rs+++ b/crates/documents/src/inbound/toolset/edit_document.rs@@ -27,7 +27,7 @@ pub(super) mod test;#[derive(Debug, Deserialize, JsonSchema)]#[schemars(title = "EditDocument",- description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName."+ description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.")]pub struct EditDocument {#[schemars(@@ -35,7 +35,7 @@ pub struct EditDocument {)]pub document_id: String,#[schemars(- description = "Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up."+ description = "Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips; profileId/slug/url for booking links. For document-card(s), include documentId and documentName per document. You may need to look these up.")]pub instructions: String,#[serde(default)]diff --git a/crates/mention_utils/src/parse.rs b/crates/mention_utils/src/parse.rsindex 0406e68fb4..739bae01ac 100644--- a/crates/mention_utils/src/parse.rs+++ b/crates/mention_utils/src/parse.rs@@ -206,6 +206,34 @@ impl<'de> XmlTaggedParsed<'de> for ParsedPullRequestMention<'de> {const TAG_NAME: &'static str = "m-pr-mention";}+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+#[non_exhaustive]+pub struct ParsedBookingLinkMention<'a> {+ #[serde(borrow, default)]+ pub profile_id: Cow<'a, str>,+ #[serde(borrow, default)]+ pub slug: Option<Cow<'a, str>>,+ #[serde(borrow, default)]+ pub label: Option<Cow<'a, str>>,+ #[serde(borrow, default)]+ pub url: Cow<'a, str>,+}++impl ParsedBookingLinkMention<'_> {+ pub fn display_label(&self) -> &str {+ self.label+ .as_deref()+ .filter(|label| !label.is_empty())+ .or_else(|| self.slug.as_deref().filter(|slug| !slug.is_empty()))+ .unwrap_or("Booking link")+ }+}++impl<'de> XmlTaggedParsed<'de> for ParsedBookingLinkMention<'de> {+ const TAG_NAME: &'static str = "m-booking-link-mention";+}+#[derive(Debug)]pub enum XmlTag<'de> {Link(ParsedLink<'de>),@@ -216,6 +244,7 @@ pub enum XmlTag<'de> {Group(ParsedGroupMention<'de>),AgentSession(ParsedAgentSessionMention<'de>),PullRequest(ParsedPullRequestMention<'de>),+ BookingLink(ParsedBookingLinkMention<'de>),}fn parse_xml_tag(s: &str) -> IResult<&str, XmlTag<'_>> {@@ -228,6 +257,7 @@ fn parse_xml_tag(s: &str) -> IResult<&str, XmlTag<'_>> {ParsedGroupMention::parse.map(XmlTag::Group),ParsedAgentSessionMention::parse.map(XmlTag::AgentSession),ParsedPullRequestMention::parse.map(XmlTag::PullRequest),+ ParsedBookingLinkMention::parse.map(XmlTag::BookingLink),)).parse(s)}@@ -242,6 +272,7 @@ fn is_recognized_tag_name(name: &str) -> bool {ParsedGroupMention::TAG_NAME,ParsedAgentSessionMention::TAG_NAME,ParsedPullRequestMention::TAG_NAME,+ ParsedBookingLinkMention::TAG_NAME,].iter().any(|recognized| recognized.eq_ignore_ascii_case(name))@@ -326,6 +357,10 @@ pub trait XmlFormatter: Sized {pr: &ParsedPullRequestMention<'_>,f: &mut Formatter<'_>,) -> std::fmt::Result;+ fn format_booking_link(+ link: &ParsedBookingLinkMention<'_>,+ f: &mut Formatter<'_>,+ ) -> std::fmt::Result;fn format_xml_text(text: ParsedXmlText<'_>) -> ReformattedXmlText<Self> {use std::fmt::Display;@@ -395,6 +430,13 @@ pub trait XmlFormatter: Sized {Adapter(|f: &mut Formatter<'_>| Self::format_pull_request(&p, f)))}+ TextSegment::Xml(XmlTag::BookingLink(b)) => {+ write!(+ acc,+ "{}",+ Adapter(|f: &mut Formatter<'_>| Self::format_booking_link(&b, f))+ )+ }TextSegment::Plain(s) => {write!(acc,@@ -475,6 +517,13 @@ impl XmlFormatter for PlainTextFormatter {),}}++ fn format_booking_link(+ link: &ParsedBookingLinkMention<'_>,+ f: &mut Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", link.display_label())+ }}/// xml formatter which completely removes the inner text of all xml tags@@ -525,4 +574,11 @@ impl XmlFormatter for NullXmlFormatter {) -> std::fmt::Result {write!(f, "")}++ fn format_booking_link(+ _link: &ParsedBookingLinkMention<'_>,+ f: &mut Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "")+ }}diff --git a/crates/mention_utils/src/tests.rs b/crates/mention_utils/src/tests.rsindex 6678925a64..3d4e9a1a25 100644--- a/crates/mention_utils/src/tests.rs+++ b/crates/mention_utils/src/tests.rs@@ -1,9 +1,10 @@use cool_asserts::assert_matches;use crate::parse::{- NullXmlFormatter, ParsedAgentSessionMention, ParsedContactMention, ParsedDateMention,- ParsedDocumentMention, ParsedGroupMention, ParsedLink, ParsedPullRequestMention,- ParsedUserMention, ParsedXmlText, PlainTextFormatter, TextSegment, XmlFormatter, XmlTag,+ NullXmlFormatter, ParsedAgentSessionMention, ParsedBookingLinkMention, ParsedContactMention,+ ParsedDateMention, ParsedDocumentMention, ParsedGroupMention, ParsedLink,+ ParsedPullRequestMention, ParsedUserMention, ParsedXmlText, PlainTextFormatter, TextSegment,+ XmlFormatter, XmlTag,};// =============================================================================@@ -846,6 +847,27 @@ fn pull_request_github_ref_ignores_non_pull_urls() {assert_eq!(rendered, "a/b#12");}+#[test]+fn parse_booking_link_mention() {+ let input = r#"Book here: <m-booking-link-mention>{"profileId":"profile-1","slug":"intro","url":"https://macro.com/app/book/profile-1/intro","label":""}</m-booking-link-mention>"#;+ let rendered = PlainTextFormatter::format_xml_text(ParsedXmlText::parse(input).unwrap()).0;+ assert_eq!(rendered, "Book here: intro");+ let out = ParsedXmlText::parse(input).unwrap();+ assert_matches!(&out.0[..], [+ TextSegment::Plain("Book here: "),+ TextSegment::Xml(XmlTag::BookingLink(ParsedBookingLinkMention {+ profile_id,+ slug,+ url,+ ..+ })),+ ] => {+ assert_eq!(profile_id.as_ref(), "profile-1");+ assert_eq!(slug.as_deref(), Some("intro"));+ assert_eq!(url.as_ref(), "https://macro.com/app/book/profile-1/intro");+ });+}+// =============================================================================// Unknown / unrecognized tag tests// =============================================================================diff --git a/crates/prompt/src/document_content_links.rs b/crates/prompt/src/document_content_links.rsindex 2186d74390..f48132f392 100644--- a/crates/prompt/src/document_content_links.rs+++ b/crates/prompt/src/document_content_links.rs@@ -27,18 +27,21 @@ For Markdown document content, link to other Macro documents, channels, chats, p`<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>`-The same Markdown parser also renders the other in-app chip tags: `<m-date-mention>` for a day or time, `<m-agent-session-mention>` for an agent session (add `"expanded":true` for the card that follows the latest turn), `<m-user-mention>` / `<m-contact-mention>` / `<m-group-mention>` for people and groups, and `<m-pr-mention>` for a pull request. Use those tags in document content the same way you would in a chat reply.+The same Markdown parser also renders the other in-app chip tags: `<m-date-mention>` for a day or time, `<m-agent-session-mention>` for an agent session (add `"expanded":true` for the card that follows the latest turn), `<m-user-mention>` / `<m-contact-mention>` / `<m-group-mention>` for people and groups, `<m-pr-mention>` for a pull request, and `<m-booking-link-mention>` for a booking link. Use those tags in document content the same way you would in a chat reply.Reference a GitHub pull request with a PR chip rather than a Markdown link or bare URL: `<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>`. Put the PR's github.com URL in `url`; no Macro id is needed. This applies to Markdown document content and to `SendChannelMessage` content, which uses the same Markdown syntax. The chip shows the PR's number, title, and live status and opens it in Macro, so leave `label` empty and do not repeat the number or title beside it. Issues, commits, and other GitHub pages stay Markdown links. Your own chat replies to the MCP client still link pull requests as plain Markdown URLs.+Reference a Macro booking link with a booking-link chip rather than a Markdown link or bare URL: `<m-booking-link-mention>{"profileId":"{profile_id}","slug":"{slug}","url":"https://macro.com/app/book/{profile_id}/{slug}","label":""}</m-booking-link-mention>` (`slug` optional when linking the profile page). Put the shareable URL in `url` and the path's profile id (and slug when present) in `profileId`/`slug`. Leave `label` empty. Your own chat replies to the MCP client still link booking pages as plain Markdown URLs.+This holds true even when `CreateDocument` is called through the MCP server, where you are otherwise told to link items in your own chat replies as plain Markdown URLs — that rule is about your conversational responses to the MCP client, not about content you write into a Macro document. Do NOT use plain Markdown links or bare URLs to reference other Macro items inside document content; only `<m-document-mention>` tags (and the other chip tags above) render as working links there.-The same applies to `EditDocument`: when its `instructions` ask for a mention chip (person, date/time, document, agent session, and so on) or a document-card, include the referenced item's ids and details so the editing worker can construct the correct in-app markup itself. Date chips need an ISO datetime and displayFormat; they do not need a looked-up id.+The same applies to `EditDocument`: when its `instructions` ask for a mention chip (person, date/time, document, agent session, booking link, and so on) or a document-card, include the referenced item's ids and details so the editing worker can construct the correct in-app markup itself. Date chips need an ISO datetime and displayFormat; they do not need a looked-up id. Booking-link chips need profileId, url, and slug when the URL has one."##;static INTENT: &str = "Content written into Markdown documents via CreateDocument or EditDocument \links other Macro items with `<m-document-mention>` XML tags and the other in-app chip tags \-(dates, agent sessions, people, and `<m-pr-mention>` by URL for GitHub pull requests, also in \+(dates, agent sessions, people, `<m-pr-mention>` by URL for GitHub pull requests, and \+`<m-booking-link-mention>` for Macro booking links, also in \SendChannelMessage content) — never plain Markdown URLs — \regardless of whether the tool call arrived in-app or over MCP, while non-Markdown documents carry \no Markdown syntax or mention tags at all.";diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex 34ff2490ae..345d84e697 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -300,6 +300,14 @@ mod tests {assert!(mcp_instructions("https://macro.com").contains(TAG));}+ #[test]+ fn mentions_and_document_content_links_share_the_booking_link_mention_tag() {+ const TAG: &str = r#"<m-booking-link-mention>{"profileId":"{profile_id}","slug":"{slug}","url":"https://macro.com/app/book/{profile_id}/{slug}","label":""}</m-booking-link-mention>"#;+ assert!(mentions::PROMPT.instructions.contains(TAG));+ assert!(document_content_links::PROMPT.instructions.contains(TAG));+ assert!(mcp_instructions("https://macro.com").contains(TAG));+ }+#[test]fn agent_session_preamble_tells_the_model_to_emit_mention_tags() {let preamble = agent_session::PROMPT.to_string();diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rsindex 9db6cf51d1..76dfe1d006 100644--- a/crates/prompt/src/mentions.rs+++ b/crates/prompt/src/mentions.rs@@ -52,7 +52,7 @@ The `blockName` for an email thread is always exactly `email` — never `thread`The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention opens for people who have that event on their own calendar. After it is shared with a channel, current members who do not have a copy see a read-only preview instead. Private and confidential events are never shared.When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.-### People, groups, dates, agent sessions, and pull requests+### People, groups, dates, agent sessions, pull requests, and booking linksThese use their own tags — never wrap them in `<m-document-mention>`:@@ -62,18 +62,21 @@ These use their own tags — never wrap them in `<m-document-mention>`:- Date/time: `<m-date-mention>{"date":"{iso_datetime}","displayFormat":"{label}"}</m-date-mention>`- Agent session: `<m-agent-session-mention>{"id":"{session_id}","label":""}</m-agent-session-mention>`- GitHub pull request: `<m-pr-mention>{"url":"https://github.com/{owner}/{repo}/pull/{number}","label":""}</m-pr-mention>`, or `<m-pr-mention>{"id":"{id}","label":""}</m-pr-mention>` when a tool returned the PR's Macro id+- Booking link: `<m-booking-link-mention>{"profileId":"{profile_id}","slug":"{slug}","url":"https://macro.com/app/book/{profile_id}/{slug}","label":""}</m-booking-link-mention>` (`slug` optional when linking the profile page)Date/time chips do not need a looked-up id. `date` is an ISO 8601 datetime; `displayFormat` is the chip label the user sees (e.g. "Mon, Dec 1, 2025", "Today", "Tomorrow", "3:00 PM"). Prefer a date chip over typing a date as plain text when you are naming a specific day or time.Reference a GitHub pull request with a PR chip, never a Markdown link or bare URL, whenever you name one: a PR a tool returned, one you opened, or one in a list. Put its github.com pull request URL in `url` (a `/files` or other subpage URL works too); you do not need to look up a Macro id. The chip shows the PR's number, title, and live status, opens it in Macro, and falls back to GitHub when Macro has not synced the PR, so leave `label` empty and do not repeat the number or title beside it. Issues, commits, repositories, and other GitHub pages stay Markdown links. A PR chip in a message you receive carries the pull request's GitHub URL in `url` (and its `owner/repo#number` in `label`); use them to read or work on that PR.+Reference a Macro booking link with a booking-link chip, never a Markdown link or bare URL, whenever you share one: a link `ListBookingLinks`, `CreateBookingLink`, or `EditBookingLink` returned, or one you are inviting someone to use. Put the shareable URL in `url`, the profile id from that URL's `/app/book/{profileId}/…` path in `profileId`, and the event slug (when present) in `slug`. Leave `label` empty so the chip shows the slug; do not paste the raw URL beside it.+Agent session chips reference an existing session by id from a tool result. An empty `label` is fine. Set `"expanded":true` to insert the card (Magic Chip) that follows the session's latest turn instead of the compact underlined title. Do not invent session ids.If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. In agent sessions, where `DiscoverConnectors` is available, the button resumes the conversation after a successful connection; tell the user to connect to continue, without asking for a separate confirmation message. In other hosts, ask them to let you know once they have connected the app so you can try again.Only the tag formats listed here can be mentioned. Never invent a tag name or put an id in the wrong tag. A calendar itself is NOT a mentionable entity: never put a `calendarId` (e.g. from ListCalendars) in a mention tag — the frontend cannot resolve it and renders a broken chip. Refer to a calendar by name in plain text and mention only individual events on it. The same goes for any other id with no mention format listed here: plain text, never an improvised tag.-`EditDocument` does not take mention tags in `instructions`. Include each referenced item's ids and details (userId/email, documentId/blockName, session id, ISO date and displayFormat, and so on) so the editing worker can insert the chip itself.+`EditDocument` does not take mention tags in `instructions`. Include each referenced item's ids and details (userId/email, documentId/blockName, session id, ISO date and displayFormat, booking-link profileId/slug/url, and so on) so the editing worker can insert the chip itself.### Example Response@@ -84,7 +87,8 @@ If no inline or node ids are present:static INTENT: &str = "Entities, people, dates, agent sessions, and other chips are referenced \with the matching XML mention tag (m-document-mention with the right blockName/blockParams, \m-user-mention, m-date-mention, m-agent-session-mention, m-pr-mention for GitHub pull \-requests by URL, and the other listed chip tags) across every Markdown surface (AI chat replies, agent session replies, channel messages, \+requests by URL, m-booking-link-mention for Macro booking links by URL, and the other \+listed chip tags) across every Markdown surface (AI chat replies, agent session replies, channel messages, \email bodies, and Markdown documents) — never inside non-Markdown documents, and never for \ids outside the listed types (a calendar id from ListCalendars is not mentionable; \only individual events are).";diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rsindex 1ad607c684..9af27456e4 100644--- a/crates/prompt/src/user_tools.rs+++ b/crates/prompt/src/user_tools.rs@@ -32,7 +32,8 @@ static INSTRUCTIONS: &str = r##"- Booking links use conversational confirmation`userConfirmation`. Do not quote the original request or invent approval. These tools saveimmediately, with no booking review form. Do not use `AskUser` or an elicitation for bookingdetails. For edits preserve unrequested settings, and re-read and reconfirm if the revision- conflicts. Return the saved URL. If the same proposal is already approved, do not ask again.+ conflicts. Share the saved URL with an `<m-booking-link-mention>` chip (see Mentions), not a+ bare URL. If the same proposal is already approved, do not ask again.- User tools are tools that must be executed by a user on the frontend.A user tool will return "PendingUserExecution" until a user chooses to@@ -76,7 +77,8 @@ static SESSION_INSTRUCTIONS: &str = r##"- Booking links use conversational confi`userConfirmation`. Do not quote the original request or invent approval. These tools saveimmediately, with no booking review form. Do not use `AskUser` or an elicitation for bookingdetails. For edits preserve unrequested settings, and re-read and reconfirm if the revision- conflicts. Return the saved URL. If the same proposal is already approved, do not ask again.+ conflicts. Share the saved URL with an `<m-booking-link-mention>` chip (see Mentions), not a+ bare URL. If the same proposal is already approved, do not ask again.- Before reaching for `SendEmail` or `CreateCalendarEvent`, look at where the newest prompt camefrom. The context block names a conversation parent when that prompt was posted in adiff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 2a72a60700..becb2d2439 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -1623,12 +1623,14 @@ calling `CreateBookingLink` or `EditBookingLink`. An initial request to create alink is not approval of the proposal. IDs and revisions are discovered throughtools; you should never be asked to enter a team ID, host ID or JSON.-A successful result returns the saved URL. Link creation itself sends no calendar-invitations; guests receive an invitation when they book. Editing hours affects-only that link. If another edit makes the revision stale, the AI reads the latest-settings and confirms a fresh proposal. Identical retries reuse the saved link.-Old pending booking review requests can be dismissed so the agent can resume with-conversational confirmation.+A successful result returns the saved URL, which the AI shares as a booking-link+mention chip (`<m-booking-link-mention>`) rather than a bare URL. Pasting that+same `/app/book/…` URL into chat, channels, or a document also becomes a chip.+Link creation itself sends no calendar invitations; guests receive an invitation+when they book. Editing hours affects only that link. If another edit makes the+revision stale, the AI reads the latest settings and confirms a fresh proposal.+Identical retries reuse the saved link. Old pending booking review requests can+be dismissed so the agent can resume with conversational confirmation.## Image attachments and model selectiondiff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.tsindex 33b2d20c07..26bc030ce5 100644--- a/packages/lexical-core/index.ts+++ b/packages/lexical-core/index.ts@@ -5,6 +5,7 @@ export * from './node-list';export * from './nodes/AgentContextNode';export * from './nodes/AgentSessionMentionNode';export * from './nodes/AwaitNode';+export * from './nodes/BookingLinkMentionNode';export * from './nodes/ClassedBlockNode';export * from './nodes/CommentNode';export * from './nodes/CompletionNode';diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.tsindex d0bc81ca6f..b6e357c1ee 100644--- a/packages/lexical-core/node-list.ts+++ b/packages/lexical-core/node-list.ts@@ -16,6 +16,7 @@ import {import { AgentContextNode } from './nodes/AgentContextNode';import { AgentSessionMentionNode } from './nodes/AgentSessionMentionNode';import { AwaitNode } from './nodes/AwaitNode';+import { BookingLinkMentionNode } from './nodes/BookingLinkMentionNode';import { ClassedBlockNode } from './nodes/ClassedBlockNode';import { CommentNode } from './nodes/CommentNode';import { CompletionNode } from './nodes/CompletionNode';@@ -90,6 +91,7 @@ export const SupportedNodeTypes = [ContactMentionNode,DateMentionNode,PullRequestMentionNode,+ BookingLinkMentionNode,AgentSessionMentionNode,ReplyTargetNode,GroupMentionNode,diff --git a/packages/lexical-core/nodes/BookingLinkMentionNode.ts b/packages/lexical-core/nodes/BookingLinkMentionNode.tsnew file mode 100644index 0000000000..05e41d2f04--- /dev/null+++ b/packages/lexical-core/nodes/BookingLinkMentionNode.ts@@ -0,0 +1,278 @@+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMConversion,+ type DOMConversionMap,+ type EditorConfig,+ type EditorThemeClasses,+ type LexicalEditor,+ type LexicalNode,+ type NodeKey,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';++const VERSION = 1;++export type BookingLinkMentionInfo = {+ /** The profile ID from the booking URL (e.g., the UUID or profile slug). */+ profileId: string;+ /** The event type slug from the booking URL (optional). */+ slug?: string;+ /** The display label for the booking link. */+ label?: string;+ /** The booking link URL. */+ url: string;+};++/** Pattern to match Macro booking URLs: /app/book/:profile/:slug? */+const MACRO_BOOKING_URL_PATTERN =+ /^https?:\/\/(?:www\.)?(?:macro\.com|localhost:\d+|dev\.macro\.com|staging\.macro\.com)\/app\/book\/([^/?#]+)(?:\/([^/?#]+))?(?:[?#].*)?$/;++/** Check whether a URL is a valid Macro booking link. */+export function isMacroBookingUrl(url: string): boolean {+ return MACRO_BOOKING_URL_PATTERN.test(url);+}++/** Parse a booking URL into its parts. */+export function parseBookingUrl(+ url: string+): { profileId: string; slug?: string } | null {+ const match = url.match(MACRO_BOOKING_URL_PATTERN);+ if (!match) return null;+ const profileId = decodeURIComponent(match[1]);+ const slug = match[2] ? decodeURIComponent(match[2]) : undefined;+ return { profileId, slug };+}++export type SerializedBookingLinkMentionNode = Spread<+ BookingLinkMentionInfo,+ SerializedLexicalNode+>;++export type BookingLinkMentionDecoratorProps = BookingLinkMentionInfo & {+ key: NodeKey;+ theme: EditorThemeClasses;+};++export class BookingLinkMentionNode extends DecoratorNode<+ DecoratorComponent<BookingLinkMentionDecoratorProps> | undefined+> {+ __profileId: string;+ __slug: string | undefined;+ __label: string | undefined;+ __url: string;++ static getType() {+ return 'booking-link-mention';+ }++ isInline(): boolean {+ return true;+ }++ isKeyboardSelectable(): boolean {+ return true;+ }++ static clone(node: BookingLinkMentionNode) {+ return new BookingLinkMentionNode(+ node.__profileId,+ node.__slug,+ node.__label,+ node.__url,+ node.__key+ );+ }++ constructor(+ profileId: string,+ slug?: string,+ label?: string,+ url?: string,+ key?: NodeKey+ ) {+ super(key);+ this.__profileId = profileId;+ this.__slug = slug;+ this.__label = label;+ this.__url =+ url ||+ buildBookingUrl(profileId, slug) ||+ `https://macro.com/app/book/${profileId}`;+ }++ static importJSON(serializedNode: SerializedBookingLinkMentionNode) {+ const node = $createBookingLinkMentionNode({+ profileId: serializedNode.profileId,+ slug: serializedNode.slug,+ label: serializedNode.label,+ url: serializedNode.url,+ });+ $applyIdFromSerialized(node, serializedNode);+ return node;+ }++ exportJSON(): SerializedBookingLinkMentionNode {+ return {+ ...super.exportJSON(),+ profileId: this.__profileId,+ slug: this.__slug,+ label: this.__label,+ url: this.__url,+ type: BookingLinkMentionNode.getType(),+ version: VERSION,+ };+ }++ exportComponentProps(): BookingLinkMentionInfo {+ return {+ profileId: this.__profileId,+ slug: this.__slug,+ label: this.__label,+ url: this.__url,+ };+ }++ createDOM(_config: EditorConfig): HTMLElement {+ const span = document.createElement('span');+ span.setAttribute('data-booking-link-mention', 'true');+ return span;+ }++ updateDOM(_prevNode: BookingLinkMentionNode, _dom: HTMLElement): boolean {+ return false;+ }++ static importDOM(): DOMConversionMap<HTMLElement> | null {+ const convert = (domNode: HTMLElement) => {+ const profileId = domNode.getAttribute('data-booking-profile-id');+ const slug = domNode.getAttribute('data-booking-slug') || undefined;+ const label = domNode.getAttribute('data-booking-label') || undefined;+ const url = domNode.getAttribute('data-booking-url') || undefined;++ if (profileId && url) {+ return {+ node: $createBookingLinkMentionNode({+ profileId,+ slug,+ label,+ url,+ }),+ };+ }++ return null;+ };++ const wrapInCheck = (conversion: DOMConversion) => {+ return (node: HTMLElement) =>+ node.hasAttribute('data-booking-link-mention') ? conversion : null;+ };++ return {+ span: wrapInCheck({ conversion: convert, priority: 1 }),+ a: wrapInCheck({ conversion: convert, priority: 1 }),+ };+ }++ getDataAttrs(): Record<string, string> {+ return {+ 'data-booking-link-mention': 'true',+ 'data-booking-profile-id': this.__profileId,+ 'data-booking-slug': this.__slug || '',+ 'data-booking-label': this.__label || '',+ 'data-booking-url': this.__url,+ };+ }++ exportDOM() {+ const element = document.createElement('span');+ const attrs = this.getDataAttrs();+ for (const [k, v] of Object.entries(attrs)) {+ if (v) {+ element.setAttribute(k, v);+ }+ }+ element.textContent = this.getTextContent();+ return { element };+ }++ getTextContent(): string {+ return this.__label || this.__slug || 'Booking link';+ }++ getSearchText(): string {+ return this.getTextContent();+ }++ getProfileId(): string {+ return this.__profileId;+ }++ getSlug(): string | undefined {+ return this.__slug;+ }++ getLabel(): string | undefined {+ return this.__label;+ }++ getUrl(): string {+ return this.__url;+ }++ setLabel(label: string | undefined) {+ const self = this.getWritable();+ self.__label = label;+ }++ setUrl(url: string) {+ const self = this.getWritable();+ self.__url = url;+ }++ decorate(_: LexicalEditor, config: EditorConfig) {+ const Component = getDecorator<BookingLinkMentionDecoratorProps>(+ BookingLinkMentionNode+ );++ if (!Component) return undefined;++ return () =>+ Component({+ ...this.exportComponentProps(),+ key: this.getKey(),+ theme: config.theme,+ });+ }+}++function buildBookingUrl(profileId: string, slug?: string): string | undefined {+ if (typeof window === 'undefined') return undefined;+ const hostname = window.location.hostname;+ const cleanHost =+ hostname === 'localhost' ? 'dev.macro.com' : hostname.replace('www.', '');+ const path = slug+ ? `/app/book/${encodeURIComponent(profileId)}/${encodeURIComponent(slug)}`+ : `/app/book/${encodeURIComponent(profileId)}`;+ return `https://${cleanHost}${path}`;+}++export function $createBookingLinkMentionNode(params: BookingLinkMentionInfo) {+ const node = new BookingLinkMentionNode(+ params.profileId,+ params.slug,+ params.label,+ params.url+ );+ return $applyNodeReplacement(node);+}++export function $isBookingLinkMentionNode(+ node: BookingLinkMentionNode | LexicalNode | null | undefined+): node is BookingLinkMentionNode {+ return node instanceof BookingLinkMentionNode;+}diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex 0c23059547..d4643cd2fa 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -16,6 +16,7 @@ import {import { I_MAGIC_CHIP } from './magicChip';import {E_AGENT_SESSION_MENTION,+ E_BOOKING_LINK_MENTION,E_CONTACT_MENTION,E_DATE_MENTION,E_DOCUMENT_CARD,@@ -26,6 +27,7 @@ import {E_USER_MENTION,I_AGENT_SESSION_CARD,I_AGENT_SESSION_MENTION,+ I_BOOKING_LINK_MENTION,I_CONNECT_APP,I_CONTACT_MENTION,I_DATE_MENTION,@@ -82,6 +84,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_DOCUMENT_MENTION,I_DOCUMENT_CARD,I_PR_MENTION,+ I_BOOKING_LINK_MENTION,I_AGENT_SESSION_CARD,I_AGENT_SESSION_MENTION,I_CONTACT_MENTION,@@ -125,8 +128,10 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [I_DOCUMENT_CARD, // for internal representationE_DOCUMENT_CARD,I_PR_MENTION,+ I_BOOKING_LINK_MENTION,I_AGENT_SESSION_MENTION,E_PR_MENTION,+ E_BOOKING_LINK_MENTION,E_AGENT_SESSION_MENTION,E_CONTACT_MENTION,E_DATE_MENTION,@@ -177,10 +182,12 @@ export const ALL_TRANSFORMERS: Transformer[] = [I_DOCUMENT_CARD,E_DOCUMENT_CARD,I_PR_MENTION,+ I_BOOKING_LINK_MENTION,I_AGENT_SESSION_CARD,I_AGENT_SESSION_MENTION,E_AGENT_SESSION_MENTION,E_PR_MENTION,+ E_BOOKING_LINK_MENTION,I_CONTACT_MENTION,E_CONTACT_MENTION,I_DATE_MENTION,diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.tsindex 846aca02cb..df338471f8 100644--- a/packages/lexical-core/transformers/mentions.ts+++ b/packages/lexical-core/transformers/mentions.ts@@ -8,6 +8,11 @@ import {AgentSessionMentionNode,buildAgentSessionMentionMarkdown,} from '../nodes/AgentSessionMentionNode';+import {+ $createBookingLinkMentionNode,+ BookingLinkMentionNode,+ isMacroBookingUrl,+} from '../nodes/BookingLinkMentionNode';import {CONNECT_APP_TAG,ConnectAppNode,@@ -737,3 +742,68 @@ export const E_DOCUMENT_CARD: ElementTransformer = {return false;},};++// Internal Booking Link Mentions+export const I_BOOKING_LINK_MENTION: TextMatchTransformer = {+ dependencies: [BookingLinkMentionNode, UnknownMentionNode],+ type: 'text-match',+ regExp: /<m-booking-link-mention>(.*?)<\/m-booking-link-mention>/,+ importRegExp: /<m-booking-link-mention>(.*?)<\/m-booking-link-mention>/,+ export: (node) => {+ if (!(node instanceof BookingLinkMentionNode)) return null;+ const data = JSON.stringify({+ profileId: node.getProfileId(),+ slug: node.getSlug(),+ label: node.getLabel(),+ url: node.getUrl(),+ });+ return `<m-booking-link-mention>${data}</m-booking-link-mention>`;+ },+ replace: (node: TextNode, match: RegExpMatchArray) => {+ try {+ const data = JSON.parse(match[1]);+ const profileId =+ typeof data.profileId === 'string' ? data.profileId : '';+ const url =+ typeof data.url === 'string' && isMacroBookingUrl(data.url)+ ? data.url+ : undefined;+ if (!profileId && !url) {+ throw new Error('Missing field profileId or url');+ }+ const bookingMentionNode = $createBookingLinkMentionNode({+ profileId,+ slug: typeof data.slug === 'string' ? data.slug : undefined,+ label: typeof data.label === 'string' ? data.label : undefined,+ url: url || `https://macro.com/app/book/${profileId}`,+ });+ node.replace(bookingMentionNode);+ } catch (e) {+ console.error('Error in I_BOOKING_LINK_MENTION replace:', e);+ replaceTextWithUnknownMention(node, 'Unknown Booking Link');+ }+ },+};++// External Booking Link Mentions+export const E_BOOKING_LINK_MENTION: ElementTransformer = {+ dependencies: [BookingLinkMentionNode],+ type: 'element',+ regExp: /$^/,+ export: (node) => {+ if (!(node instanceof BookingLinkMentionNode)) return null;++ const url = node.getUrl();+ const label = node.getLabel() || node.getSlug() || 'Booking link';++ return `[${label}](${url})`;+ },+ replace: (+ _parentNode: ElementNode,+ _children: Array<LexicalNode>,+ _match: Array<string>,+ _isImport: boolean+ ) => {+ return false;+ },+};diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.tsindex cdb68f45f1..4ff8ed4c2a 100644--- a/packages/lexical-core/transformers/xml/codecs.ts+++ b/packages/lexical-core/transformers/xml/codecs.ts@@ -90,6 +90,7 @@ const KNOWN_TYPES: Record<KnownNode['type'], 1> = {'contact-mention': 1,'group-mention': 1,'pr-mention': 1,+ 'booking-link-mention': 1,'agent-session-mention': 1,'tag-mention': 1,'theme-mention': 1,@@ -380,6 +381,18 @@ export function serializeNode(node: SerNode): FxpNode {})))+ .with({ type: 'booking-link-mention' }, (n) =>+ el(+ 'booking-link-mention',+ [],+ nodeAttrs(n, {+ profileId: n.profileId,+ url: n.url,+ ...(n.slug && { slug: n.slug }),+ ...(n.label && { label: n.label }),+ })+ )+ ).with({ type: 'theme-mention' }, (n) =>el('theme-mention', [], nodeAttrs(n, { ...(n.name && { name: n.name }) })))diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.tsindex 00ef8ab404..734258028d 100644--- a/packages/lexical-core/transformers/xml/nodes.ts+++ b/packages/lexical-core/transformers/xml/nodes.ts@@ -209,6 +209,15 @@ export type PullRequestMentionNode = Id & {url?: string;};+export type BookingLinkMentionNode = Id & {+ type: 'booking-link-mention';+ version: number;+ profileId: string;+ slug?: string;+ label?: string;+ url: string;+};+export type ThemeMentionNode = Id & {type: 'theme-mention';version: number;@@ -260,6 +269,7 @@ export type KnownNode =| GroupMentionNode| AgentSessionMentionNode| PullRequestMentionNode+ | BookingLinkMentionNode| TagMentionNode| ThemeMentionNode| UnknownMentionNode;diff --git a/services/ai-editing-worker/src/ai-editing/doc/doc.ts b/services/ai-editing-worker/src/ai-editing/doc/doc.tsindex 844fa359b9..5565182acb 100644--- a/services/ai-editing-worker/src/ai-editing/doc/doc.ts+++ b/services/ai-editing-worker/src/ai-editing/doc/doc.ts@@ -32,6 +32,7 @@ import {type TableNode,} from '@lexical/table';import { $createAgentSessionMentionNode } from '@macro-inc/lexical-core/nodes/AgentSessionMentionNode';+import { $createBookingLinkMentionNode } from '@macro-inc/lexical-core/nodes/BookingLinkMentionNode';import { $createContactMentionNode } from '@macro-inc/lexical-core/nodes/ContactMentionNode';import {$createDateMentionNode,@@ -1050,6 +1051,14 @@ export function buildNode(spec: NodeSpec): LexicalNode {.with({ kind: 'pr' }, (m) =>$createPullRequestMentionNode({ id: m.id, label: m.label }))+ .with({ kind: 'booking_link' }, (m) =>+ $createBookingLinkMentionNode({+ profileId: m.profileId,+ url: m.url,+ slug: m.slug,+ label: m.label,+ })+ ).with({ kind: 'tag' }, (m) =>$createTagMentionNode({optionId: m.optionId,diff --git a/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts b/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.tsindex 68a07f9697..74c5465a96 100644--- a/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts+++ b/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts@@ -451,6 +451,23 @@ describe('DocumentEditor — mention methods push insertInline ops', () => {kind: 'insertInline',spec: { inline: 'mention', mention: { kind: 'pr', id: 'pr-1' } },});+ const ebl = ed();+ ebl.mentionBookingLink('b1', 0, {+ profileId: 'profile-1',+ slug: 'intro',+ url: 'https://macro.com/app/book/profile-1/intro',+ });+ expect(ebl.drain()[0]).toMatchObject({+ kind: 'insertInline',+ spec: {+ inline: 'mention',+ mention: {+ kind: 'booking_link',+ profileId: 'profile-1',+ slug: 'intro',+ },+ },+ });const et = ed();et.mentionTag('b1', 0, {optionId: 'o',diff --git a/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts b/services/ai-editing-worker/src/ai-editing/editor/document-editor.tsindex 8174b53106..9ec51cb643 100644--- a/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts+++ b/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts@@ -685,6 +685,19 @@ export class DocumentEditor {return this.insertMention(blockId, at, { kind: 'pr', ...entity });}+ public mentionBookingLink(+ blockId: NodeId,+ at: number,+ entity: {+ profileId: string;+ url: string;+ slug?: string;+ label?: string;+ }+ ): Ref {+ return this.insertMention(blockId, at, { kind: 'booking_link', ...entity });+ }+public mentionTag(blockId: NodeId,at: number,diff --git a/services/ai-editing-worker/src/ai-editing/editor/ops.ts b/services/ai-editing-worker/src/ai-editing/editor/ops.tsindex 079d2abd00..27c9483677 100644--- a/services/ai-editing-worker/src/ai-editing/editor/ops.ts+++ b/services/ai-editing-worker/src/ai-editing/editor/ops.ts@@ -97,6 +97,13 @@ export type MentionSpec =}| { kind: 'agent_session'; id: string; label?: string; expanded?: boolean }| { kind: 'pr'; id: string; label?: string }+ | {+ kind: 'booking_link';+ profileId: string;+ url: string;+ slug?: string;+ label?: string;+ }| {kind: 'tag';optionId: string;diff --git a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.mdindex f617e6a54c..a37dab8184 100644--- a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md+++ b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md@@ -36,7 +36,7 @@ The writer has the complete API reference. Use this compact list to help yoursel## Native Objects- Block objects: `insertDivider`, `insertImage`, `insertVideo`, `insertEquation`; or via `insertBlockAfter`/`appendBlock` with specs `document-card` (documentId, documentName, blockName, blockParams?) and `html-render` (html)-- Inline objects: `insertInlineEquation`, `insertLineBreak`, `insertDate`/`mentionDate` (time chip), `insertMention`, `mentionUser`, `mentionContact`, `mentionGroup`, `mentionDocument`, `mentionAgentSession`, `mentionPullRequest`, `mentionTag`+- Inline objects: `insertInlineEquation`, `insertLineBreak`, `insertDate`/`mentionDate` (time chip), `insertMention`, `mentionUser`, `mentionContact`, `mentionGroup`, `mentionDocument`, `mentionAgentSession`, `mentionPullRequest`, `mentionBookingLink`, `mentionTag`- To place text after an inline object: `insertTextAfterInline(inlineRef, text)`. Do **not** use `appendText` for this — it targets the block's last text node and misplaces the text when an inline object is the last child.- Updates: `setImageAlt`, `setImageUrl`, `setVideoUrl`, `setVideoControls`, `setDate`diff --git a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.mdindex 82daf0cffb..25f5bd9376 100644--- a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md+++ b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md@@ -384,7 +384,7 @@ After:These insert the same @-mention chips the user inserts from the `@` menu. Use the ids and details supplied in the task -- do not invent entity ids. Date/time chips do not need a looked-up id.-Existing chips in the document XML look like `<user-mention>`, `<date-mention>`, `<document-mention>`, `<agent-session-mention>`, `<contact-mention>`, `<group-mention>`, `<pr-mention>`, `<tag-mention>`. Leave them intact unless the task asks to change them.+Existing chips in the document XML look like `<user-mention>`, `<date-mention>`, `<document-mention>`, `<agent-session-mention>`, `<contact-mention>`, `<group-mention>`, `<pr-mention>`, `<booking-link-mention>`, `<tag-mention>`. Leave them intact unless the task asks to change them.- `insertDate(blockId, at, isoDate, displayFormat?)` · `mentionDate(...)` — time chip. `isoDate` is ISO 8601; `displayFormat` is the label on the chip (e.g. `'Mon, Dec 1, 2025'`, `'Today'`, `'3:00 PM'`).- `insertMention(blockId, at, mention)`@@ -394,6 +394,7 @@ Existing chips in the document XML look like `<user-mention>`, `<date-mention>`,- `mentionDocument(blockId, at, { documentId, documentName, blockName, blockParams? })` — documents, channels, chats, folders, projects, tasks, emails, calendar events, skills, calls, automations (`blockName` is `md`/`channel`/`chat`/`project`/`initiative`/`task`/`email`/`calendar`/`skill`/`call`/`automation`/…). A project (initiative) is `blockName: 'initiative'` with the initiative id as `documentId`; `project` is a folder. `blockParams` is for channel messages (`channel_message_id`) and calendar occurrences (`occurrenceKey`).- `mentionAgentSession(blockId, at, { id, label?, expanded? })` — existing agent session. `expanded: true` inserts the card that follows the session's latest turn.- `mentionPullRequest(blockId, at, { id, label? })`+- `mentionBookingLink(blockId, at, { profileId, url, slug?, label? })` — Macro booking page (`/app/book/{profileId}/{slug?}`). Prefer the shareable URL from a booking-link tool.- `mentionTag(blockId, at, { optionId, propertyDefinitionId, scope, name, color? })````tsdiff --git a/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md b/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.mdindex 00cf9c793f..f9a6c3b14b 100644--- a/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md+++ b/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md@@ -20,7 +20,7 @@ You should aim to complete the task in few dispatch rounds, and should plan careYou should provide high level English instructions to writers about the changes you want different writers to do. For example, "move paragraph Mz5qcIFm to be right above the q3IMz52m heading." Our writers are non technical and can't understand Markdown or coding terms. Try to avoid telling them *how* to do things. Figuring out how to make changes to documents what they are trained to do.- Mention existing XML ids for the target region. The writers only get to see context surrounding mentioned nodes.-- To mention a person, date/time, document, channel, agent session, or other chip, use the ids and details from the request (userId/email, documentId/documentName/blockName, session id, ISO date plus displayFormat). Date chips do not need a looked-up id. To add a document-card, use the `documentId`/`documentName`/`blockName` from the request. Do not write literal XML/Markdown unless the user wants those literal characters. Do not type `@Name` as plain text when a mention chip exists.+- To mention a person, date/time, document, channel, agent session, booking link, or other chip, use the ids and details from the request (userId/email, documentId/documentName/blockName, session id, ISO date plus displayFormat, booking-link profileId/slug/url). Date chips do not need a looked-up id. To add a document-card, use the `documentId`/`documentName`/`blockName` from the request. Do not write literal XML/Markdown unless the user wants those literal characters. Do not type `@Name` as plain text when a mention chip exists.- Do not invent or preserve ids. New ids are assigned automatically and existing ids may change.- Do not write code yourself; describe the change mechanically.- Do not try to inject formatting like bullet unicode into your snippets. Let the writer handle the formatting.diff --git a/services/ai-editing-worker/src/editor-sandbox-code.ts b/services/ai-editing-worker/src/editor-sandbox-code.tsindex d8ff918e24..5ba938e525 100644--- a/services/ai-editing-worker/src/editor-sandbox-code.ts+++ b/services/ai-editing-worker/src/editor-sandbox-code.ts@@ -2,4 +2,4 @@// Source of truth: src/ai-editing/editor/document-editor.ts// biome-ignore-all lint/suspicious/noTemplateCurlyInString: generated JS contains template literalsexport const SANDBOX_CODE =- 'class EditError extends Error {\n constructor(message) {\n super(message);\n this.name = "EditError";\n }\n}\n\nfunction describeBadId(value) {\n if (value === null)\n return "null";\n if (value === undefined)\n return "undefined";\n if (Array.isArray(value))\n return `an array of ${value.length}`;\n if (typeof value === "object") {\n const keys = Object.keys(value).slice(0, 4);\n return `an object with keys [${keys.join(", ")}]`;\n }\n return `a ${typeof value} (${String(value)})`;\n}\n\nclass DocumentEditor {\n ops = [];\n valid;\n refs;\n refIdx = 0;\n constructor(opts) {\n this.valid = new Set(opts.validIds);\n this.refs = opts.refs;\n }\n push(op) {\n this.ops.push(op);\n return this;\n }\n requireId(id) {\n if (typeof id !== "string") {\n throw new EditError(`expected a node id string but got ${describeBadId(id)}. ` + "Insert helpers return the new node\'s id directly, so use that value " + "as-is rather than a property of it.");\n }\n if (id.length === 0)\n throw new EditError("node id is an empty string");\n if (!this.valid.has(id)) {\n throw new EditError(`unknown id "${id}"`);\n }\n }\n requireMatch(match) {\n if (match.length === 0)\n throw new EditError("match string is empty");\n }\n mintRef() {\n const ref = this.refs[this.refIdx++];\n if (!ref) {\n throw new EditError("too many inserts in one snippet (id pool exhausted)");\n }\n this.valid.add(ref);\n return ref;\n }\n drain() {\n const out = this.ops;\n this.ops = [];\n return out;\n }\n format(id, match, format, on = true, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({\n kind: "formatText",\n node: id,\n match,\n format,\n on,\n scope\n });\n }\n bold(id, match, scope) {\n return this.format(id, match, "bold", true, scope);\n }\n italic(id, match, scope) {\n return this.format(id, match, "italic", true, scope);\n }\n underline(id, match, scope) {\n return this.format(id, match, "underline", true, scope);\n }\n strike(id, match, scope) {\n return this.format(id, match, "strike", true, scope);\n }\n inlineCode(id, match, scope) {\n return this.format(id, match, "code", true, scope);\n }\n unbold(id, match, scope) {\n return this.format(id, match, "bold", false, scope);\n }\n unitalic(id, match, scope) {\n return this.format(id, match, "italic", false, scope);\n }\n ununderline(id, match, scope) {\n return this.format(id, match, "underline", false, scope);\n }\n unstrike(id, match, scope) {\n return this.format(id, match, "strike", false, scope);\n }\n uninlineCode(id, match, scope) {\n return this.format(id, match, "code", false, scope);\n }\n clearFormat(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n if (match !== undefined)\n this.requireMatch(match);\n return this.push({ kind: "clearFormat", node: id, match, scope });\n }\n clearAllFormat(id) {\n return this.clearFormat(id);\n }\n highlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: true, scope });\n }\n unhighlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: false, scope });\n }\n link(id, match, url, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url, scope });\n }\n unlink(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url: null, scope });\n }\n formatNode(node, format, on = true) {\n this.requireId(node);\n return this.push({ kind: "formatNode", node, format, on });\n }\n boldNode(node) {\n return this.formatNode(node, "bold");\n }\n italicNode(node) {\n return this.formatNode(node, "italic");\n }\n underlineNode(node) {\n return this.formatNode(node, "underline");\n }\n strikeNode(node) {\n return this.formatNode(node, "strike");\n }\n codeNode(node) {\n return this.formatNode(node, "code");\n }\n clearNodeFormat(node) {\n this.requireId(node);\n return this.push({ kind: "clearNodeFormat", node });\n }\n setText(id, text) {\n this.requireId(id);\n return this.push({ kind: "setText", node: id, text });\n }\n setEquation(id, tex) {\n this.requireId(id);\n return this.push({ kind: "setEquation", node: id, tex });\n }\n replace(id, find, to, scope = { kind: "all" }) {\n this.requireId(id);\n if (find.length === 0)\n throw new EditError("find string is empty");\n return this.push({ kind: "replaceText", node: id, find, to, scope });\n }\n appendText(id, text) {\n this.requireId(id);\n return this.push({ kind: "appendText", node: id, text });\n }\n prependText(id, text) {\n this.requireId(id);\n return this.push({ kind: "prependText", node: id, text });\n }\n setBlockType(id, args) {\n this.requireId(id);\n return this.push({ kind: "setBlockType", node: id, ...args });\n }\n requireLanguage(language) {\n if (typeof language !== "string" || language.trim().length === 0)\n throw new EditError("code block language is required");\n }\n convertToParagraph(id) {\n return this.setBlockType(id, { block: "paragraph" });\n }\n convertToHeading(id, level) {\n if (level < 1 || level > 6)\n throw new EditError(`heading level must be 1-6, got ${level}`);\n return this.setBlockType(id, { block: "heading", level });\n }\n convertToQuote(id) {\n return this.setBlockType(id, { block: "quote" });\n }\n convertToCodeBlock(id, language) {\n this.requireLanguage(language);\n return this.setBlockType(id, { block: "code", language });\n }\n setLanguage(id, language) {\n return this.convertToCodeBlock(id, language);\n }\n toList(idOrIds, list) {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n if (ids.length === 0)\n throw new EditError("list requires at least one block");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "setListType", nodes: ids, list });\n }\n bulletList(idOrIds) {\n return this.toList(idOrIds, "bullet");\n }\n numberedList(idOrIds) {\n return this.toList(idOrIds, "number");\n }\n checklist(idOrIds) {\n return this.toList(idOrIds, "check");\n }\n setListType(id, list) {\n return this.toList(id, list);\n }\n check(id) {\n return this.setChecked(id, true);\n }\n uncheck(id) {\n return this.setChecked(id, false);\n }\n setChecked(id, checked) {\n this.requireId(id);\n return this.push({ kind: "setChecked", node: id, checked });\n }\n indent(id, by = 1) {\n this.requireId(id);\n return this.push({\n kind: "setIndent",\n node: id,\n indent: by >= 0 ? "in" : "out"\n });\n }\n outdent(id, by = 1) {\n return this.indent(id, -Math.abs(by));\n }\n setIndent(id, level) {\n this.requireId(id);\n if (level < 0)\n throw new EditError(`indent level must be >= 0, got ${level}`);\n return this.push({ kind: "setIndent", node: id, indent: level });\n }\n insertListItemAfter(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemAfter", ref, node: id, text, list });\n return ref;\n }\n insertListItemBefore(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemBefore", ref, node: id, text, list });\n return ref;\n }\n appendListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "appendListItem", ref, node: listId, text });\n return ref;\n }\n prependListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "prependListItem", ref, node: listId, text });\n return ref;\n }\n removeListItem(id) {\n this.requireId(id);\n return this.push({ kind: "removeListItem", node: id });\n }\n insert(spec, at) {\n this.requireAt(at);\n const ref = this.mintRef();\n this.push({ kind: "insertNode", ref, spec, at });\n return ref;\n }\n requireAt(at) {\n if ("after" in at)\n this.requireId(at.after);\n else if ("before" in at)\n this.requireId(at.before);\n }\n insertParagraphAfter(id, text = "") {\n return this.insert({ block: "paragraph", text }, { after: id });\n }\n insertParagraphBefore(id, text = "") {\n return this.insert({ block: "paragraph", text }, { before: id });\n }\n insertHeadingAfter(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { after: id });\n }\n insertHeadingBefore(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { before: id });\n }\n insertQuoteAfter(id, text = "") {\n return this.insert({ block: "quote", text }, { after: id });\n }\n insertCodeBlockAfter(id, language, text = "") {\n this.requireLanguage(language);\n return this.insert({ block: "code", language, text }, { after: id });\n }\n insertBlockAfter(id, spec) {\n return this.insert(spec, { after: id });\n }\n insertBlockBefore(id, spec) {\n return this.insert(spec, { before: id });\n }\n appendParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { appendToRoot: true });\n }\n prependParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { prependToRoot: true });\n }\n appendBlock(spec) {\n return this.insert(spec, { appendToRoot: true });\n }\n prependBlock(spec) {\n return this.insert(spec, { prependToRoot: true });\n }\n move(id, at) {\n this.requireId(id);\n this.requireAt(at);\n return this.push({ kind: "moveNode", node: id, at });\n }\n remove(id) {\n this.requireId(id);\n return this.push({ kind: "removeNode", node: id });\n }\n removeMany(ids) {\n for (const id of ids)\n this.remove(id);\n return this;\n }\n merge(ids, separator = " ") {\n if (ids.length < 2)\n throw new EditError("merge requires at least two blocks");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "mergeBlocks", nodes: ids, separator });\n }\n insertTableAfter(id, rows) {\n return this.buildTable(rows, { after: id });\n }\n insertTableBefore(id, rows) {\n return this.buildTable(rows, { before: id });\n }\n appendTable(rows) {\n return this.buildTable(rows, { appendToRoot: true });\n }\n buildTable(rows, at) {\n if (rows.length === 0)\n throw new EditError("table requires at least one row");\n const empty = rows.map((row) => row.map(() => ""));\n const ref = this.insert({ block: "table", rows: empty }, at);\n rows.forEach((row, r) => void row.forEach((cell, c) => {\n if (cell)\n this.setCell(ref, r, c, cell);\n }));\n return ref;\n }\n setCell(table, row, col, text) {\n this.requireId(table);\n this.requireCell(row, col);\n return this.push({ kind: "setCell", table, row, col, text });\n }\n addRow(table, at) {\n this.requireId(table);\n return this.push({ kind: "addRow", table, at });\n }\n addColumn(table, at) {\n this.requireId(table);\n return this.push({ kind: "addColumn", table, at });\n }\n removeRow(table, row) {\n this.requireId(table);\n this.requireCell(row, 0);\n return this.push({ kind: "removeRow", table, row });\n }\n removeColumn(table, col) {\n this.requireId(table);\n this.requireCell(0, col);\n return this.push({ kind: "removeColumn", table, col });\n }\n requireCell(row, col) {\n if (row < 0 || col < 0)\n throw new EditError(`cell indices must be >= 0, got (${row}, ${col})`);\n }\n insertDivider(afterId) {\n return this.insert({ block: "divider" }, { after: afterId });\n }\n insertImage(afterId, img) {\n return this.insert({ block: "image", ...img }, { after: afterId });\n }\n insertVideo(afterId, vid) {\n return this.insert({ block: "video", ...vid }, { after: afterId });\n }\n insertEquation(afterId, tex) {\n return this.insert({ block: "equation", tex }, { after: afterId });\n }\n insertInlineEquation(blockId, at, tex) {\n return this.insertInline(blockId, at, { inline: "equation", tex });\n }\n insertTextAfterInline(inlineRef, text) {\n return this.push({\n kind: "insertTextAfterInline",\n inline: inlineRef,\n text\n });\n }\n insertLineBreak(blockId, at) {\n return this.insertInline(blockId, at, { inline: "linebreak" });\n }\n insertDate(blockId, at, isoDate, displayFormat) {\n return this.insertInline(blockId, at, {\n inline: "date",\n date: isoDate,\n displayFormat\n });\n }\n mentionDate(blockId, at, isoDate, displayFormat) {\n return this.insertDate(blockId, at, isoDate, displayFormat);\n }\n insertInline(id, at, spec) {\n this.requireId(id);\n if (at < 0)\n throw new EditError(`inline offset must be >= 0, got ${at}`);\n const ref = this.mintRef();\n this.push({ kind: "insertInline", ref, node: id, at, spec });\n return ref;\n }\n insertMention(blockId, at, mention) {\n return this.insertInline(blockId, at, { inline: "mention", mention });\n }\n mentionUser(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "user", ...entity });\n }\n mentionContact(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "contact", ...entity });\n }\n mentionGroup(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "group", ...entity });\n }\n mentionDocument(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "document", ...entity });\n }\n mentionAgentSession(blockId, at, entity) {\n return this.insertMention(blockId, at, {\n kind: "agent_session",\n ...entity\n });\n }\n mentionPullRequest(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "pr", ...entity });\n }\n mentionTag(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "tag", ...entity });\n }\n setImageAlt(id, alt) {\n this.requireId(id);\n return this.push({ kind: "setImageAlt", node: id, alt });\n }\n setImageUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setImageUrl", node: id, url });\n }\n setVideoUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setVideoUrl", node: id, url });\n }\n setVideoControls(id, controls) {\n this.requireId(id);\n return this.push({ kind: "setVideoControls", node: id, controls });\n }\n setDate(id, date, displayFormat) {\n this.requireId(id);\n return this.push({ kind: "setDate", node: id, date, displayFormat });\n }\n}\nfunction editorMethodNames(target) {\n const names = new Set;\n for (let proto = target;proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key === "constructor" || key.startsWith("_"))\n continue;\n if (typeof target[key] === "function") {\n names.add(key);\n }\n }\n }\n return [...names];\n}\nfunction suggestMethods(wanted, names) {\n const normalizedWanted = wanted.toLowerCase();\n const scored = names.map((name) => {\n const normalizedName = name.toLowerCase();\n let score = 0;\n if (normalizedName === normalizedWanted)\n score = 1000;\n else if (normalizedName.includes(normalizedWanted) || normalizedWanted.includes(normalizedName)) {\n score = 100 + Math.min(normalizedName.length, normalizedWanted.length);\n } else {\n while (score < normalizedName.length && score < normalizedWanted.length && normalizedName[score] === normalizedWanted[score]) {\n score++;\n }\n }\n return { name, score };\n });\n scored.sort((a, b) => b.score - a.score);\n return scored.filter(({ score }) => score >= 3).slice(0, 3).map(({ name }) => name);\n}\nfunction createDocumentEditor(options) {\n const target = new DocumentEditor(options);\n return new Proxy(target, {\n get(editor, property) {\n const value = editor[property];\n if (value !== undefined || typeof property !== "string") {\n return typeof value === "function" ? value.bind(editor) : value;\n }\n return () => {\n const suggestions = suggestMethods(property, editorMethodNames(editor));\n throw new Error(`editor.${property} does not exist` + (suggestions.length ? `. Did you mean: ${suggestions.join(", ")}?` : ".") + " The editor is write-only — to inspect the document use the readDocument tool, not a call inside the snippet.");\n };\n }\n });\n}';+ 'class EditError extends Error {\n constructor(message) {\n super(message);\n this.name = "EditError";\n }\n}\n\nfunction describeBadId(value) {\n if (value === null)\n return "null";\n if (value === undefined)\n return "undefined";\n if (Array.isArray(value))\n return `an array of ${value.length}`;\n if (typeof value === "object") {\n const keys = Object.keys(value).slice(0, 4);\n return `an object with keys [${keys.join(", ")}]`;\n }\n return `a ${typeof value} (${String(value)})`;\n}\n\nclass DocumentEditor {\n ops = [];\n valid;\n refs;\n refIdx = 0;\n constructor(opts) {\n this.valid = new Set(opts.validIds);\n this.refs = opts.refs;\n }\n push(op) {\n this.ops.push(op);\n return this;\n }\n requireId(id) {\n if (typeof id !== "string") {\n throw new EditError(`expected a node id string but got ${describeBadId(id)}. ` + "Insert helpers return the new node\'s id directly, so use that value " + "as-is rather than a property of it.");\n }\n if (id.length === 0)\n throw new EditError("node id is an empty string");\n if (!this.valid.has(id)) {\n throw new EditError(`unknown id "${id}"`);\n }\n }\n requireMatch(match) {\n if (match.length === 0)\n throw new EditError("match string is empty");\n }\n mintRef() {\n const ref = this.refs[this.refIdx++];\n if (!ref) {\n throw new EditError("too many inserts in one snippet (id pool exhausted)");\n }\n this.valid.add(ref);\n return ref;\n }\n drain() {\n const out = this.ops;\n this.ops = [];\n return out;\n }\n format(id, match, format, on = true, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({\n kind: "formatText",\n node: id,\n match,\n format,\n on,\n scope\n });\n }\n bold(id, match, scope) {\n return this.format(id, match, "bold", true, scope);\n }\n italic(id, match, scope) {\n return this.format(id, match, "italic", true, scope);\n }\n underline(id, match, scope) {\n return this.format(id, match, "underline", true, scope);\n }\n strike(id, match, scope) {\n return this.format(id, match, "strike", true, scope);\n }\n inlineCode(id, match, scope) {\n return this.format(id, match, "code", true, scope);\n }\n unbold(id, match, scope) {\n return this.format(id, match, "bold", false, scope);\n }\n unitalic(id, match, scope) {\n return this.format(id, match, "italic", false, scope);\n }\n ununderline(id, match, scope) {\n return this.format(id, match, "underline", false, scope);\n }\n unstrike(id, match, scope) {\n return this.format(id, match, "strike", false, scope);\n }\n uninlineCode(id, match, scope) {\n return this.format(id, match, "code", false, scope);\n }\n clearFormat(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n if (match !== undefined)\n this.requireMatch(match);\n return this.push({ kind: "clearFormat", node: id, match, scope });\n }\n clearAllFormat(id) {\n return this.clearFormat(id);\n }\n highlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: true, scope });\n }\n unhighlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: false, scope });\n }\n link(id, match, url, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url, scope });\n }\n unlink(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url: null, scope });\n }\n formatNode(node, format, on = true) {\n this.requireId(node);\n return this.push({ kind: "formatNode", node, format, on });\n }\n boldNode(node) {\n return this.formatNode(node, "bold");\n }\n italicNode(node) {\n return this.formatNode(node, "italic");\n }\n underlineNode(node) {\n return this.formatNode(node, "underline");\n }\n strikeNode(node) {\n return this.formatNode(node, "strike");\n }\n codeNode(node) {\n return this.formatNode(node, "code");\n }\n clearNodeFormat(node) {\n this.requireId(node);\n return this.push({ kind: "clearNodeFormat", node });\n }\n setText(id, text) {\n this.requireId(id);\n return this.push({ kind: "setText", node: id, text });\n }\n setEquation(id, tex) {\n this.requireId(id);\n return this.push({ kind: "setEquation", node: id, tex });\n }\n replace(id, find, to, scope = { kind: "all" }) {\n this.requireId(id);\n if (find.length === 0)\n throw new EditError("find string is empty");\n return this.push({ kind: "replaceText", node: id, find, to, scope });\n }\n appendText(id, text) {\n this.requireId(id);\n return this.push({ kind: "appendText", node: id, text });\n }\n prependText(id, text) {\n this.requireId(id);\n return this.push({ kind: "prependText", node: id, text });\n }\n setBlockType(id, args) {\n this.requireId(id);\n return this.push({ kind: "setBlockType", node: id, ...args });\n }\n requireLanguage(language) {\n if (typeof language !== "string" || language.trim().length === 0)\n throw new EditError("code block language is required");\n }\n convertToParagraph(id) {\n return this.setBlockType(id, { block: "paragraph" });\n }\n convertToHeading(id, level) {\n if (level < 1 || level > 6)\n throw new EditError(`heading level must be 1-6, got ${level}`);\n return this.setBlockType(id, { block: "heading", level });\n }\n convertToQuote(id) {\n return this.setBlockType(id, { block: "quote" });\n }\n convertToCodeBlock(id, language) {\n this.requireLanguage(language);\n return this.setBlockType(id, { block: "code", language });\n }\n setLanguage(id, language) {\n return this.convertToCodeBlock(id, language);\n }\n toList(idOrIds, list) {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n if (ids.length === 0)\n throw new EditError("list requires at least one block");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "setListType", nodes: ids, list });\n }\n bulletList(idOrIds) {\n return this.toList(idOrIds, "bullet");\n }\n numberedList(idOrIds) {\n return this.toList(idOrIds, "number");\n }\n checklist(idOrIds) {\n return this.toList(idOrIds, "check");\n }\n setListType(id, list) {\n return this.toList(id, list);\n }\n check(id) {\n return this.setChecked(id, true);\n }\n uncheck(id) {\n return this.setChecked(id, false);\n }\n setChecked(id, checked) {\n this.requireId(id);\n return this.push({ kind: "setChecked", node: id, checked });\n }\n indent(id, by = 1) {\n this.requireId(id);\n return this.push({\n kind: "setIndent",\n node: id,\n indent: by >= 0 ? "in" : "out"\n });\n }\n outdent(id, by = 1) {\n return this.indent(id, -Math.abs(by));\n }\n setIndent(id, level) {\n this.requireId(id);\n if (level < 0)\n throw new EditError(`indent level must be >= 0, got ${level}`);\n return this.push({ kind: "setIndent", node: id, indent: level });\n }\n insertListItemAfter(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemAfter", ref, node: id, text, list });\n return ref;\n }\n insertListItemBefore(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemBefore", ref, node: id, text, list });\n return ref;\n }\n appendListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "appendListItem", ref, node: listId, text });\n return ref;\n }\n prependListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "prependListItem", ref, node: listId, text });\n return ref;\n }\n removeListItem(id) {\n this.requireId(id);\n return this.push({ kind: "removeListItem", node: id });\n }\n insert(spec, at) {\n this.requireAt(at);\n const ref = this.mintRef();\n this.push({ kind: "insertNode", ref, spec, at });\n return ref;\n }\n requireAt(at) {\n if ("after" in at)\n this.requireId(at.after);\n else if ("before" in at)\n this.requireId(at.before);\n }\n insertParagraphAfter(id, text = "") {\n return this.insert({ block: "paragraph", text }, { after: id });\n }\n insertParagraphBefore(id, text = "") {\n return this.insert({ block: "paragraph", text }, { before: id });\n }\n insertHeadingAfter(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { after: id });\n }\n insertHeadingBefore(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { before: id });\n }\n insertQuoteAfter(id, text = "") {\n return this.insert({ block: "quote", text }, { after: id });\n }\n insertCodeBlockAfter(id, language, text = "") {\n this.requireLanguage(language);\n return this.insert({ block: "code", language, text }, { after: id });\n }\n insertBlockAfter(id, spec) {\n return this.insert(spec, { after: id });\n }\n insertBlockBefore(id, spec) {\n return this.insert(spec, { before: id });\n }\n appendParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { appendToRoot: true });\n }\n prependParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { prependToRoot: true });\n }\n appendBlock(spec) {\n return this.insert(spec, { appendToRoot: true });\n }\n prependBlock(spec) {\n return this.insert(spec, { prependToRoot: true });\n }\n move(id, at) {\n this.requireId(id);\n this.requireAt(at);\n return this.push({ kind: "moveNode", node: id, at });\n }\n remove(id) {\n this.requireId(id);\n return this.push({ kind: "removeNode", node: id });\n }\n removeMany(ids) {\n for (const id of ids)\n this.remove(id);\n return this;\n }\n merge(ids, separator = " ") {\n if (ids.length < 2)\n throw new EditError("merge requires at least two blocks");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "mergeBlocks", nodes: ids, separator });\n }\n insertTableAfter(id, rows) {\n return this.buildTable(rows, { after: id });\n }\n insertTableBefore(id, rows) {\n return this.buildTable(rows, { before: id });\n }\n appendTable(rows) {\n return this.buildTable(rows, { appendToRoot: true });\n }\n buildTable(rows, at) {\n if (rows.length === 0)\n throw new EditError("table requires at least one row");\n const empty = rows.map((row) => row.map(() => ""));\n const ref = this.insert({ block: "table", rows: empty }, at);\n rows.forEach((row, r) => void row.forEach((cell, c) => {\n if (cell)\n this.setCell(ref, r, c, cell);\n }));\n return ref;\n }\n setCell(table, row, col, text) {\n this.requireId(table);\n this.requireCell(row, col);\n return this.push({ kind: "setCell", table, row, col, text });\n }\n addRow(table, at) {\n this.requireId(table);\n return this.push({ kind: "addRow", table, at });\n }\n addColumn(table, at) {\n this.requireId(table);\n return this.push({ kind: "addColumn", table, at });\n }\n removeRow(table, row) {\n this.requireId(table);\n this.requireCell(row, 0);\n return this.push({ kind: "removeRow", table, row });\n }\n removeColumn(table, col) {\n this.requireId(table);\n this.requireCell(0, col);\n return this.push({ kind: "removeColumn", table, col });\n }\n requireCell(row, col) {\n if (row < 0 || col < 0)\n throw new EditError(`cell indices must be >= 0, got (${row}, ${col})`);\n }\n insertDivider(afterId) {\n return this.insert({ block: "divider" }, { after: afterId });\n }\n insertImage(afterId, img) {\n return this.insert({ block: "image", ...img }, { after: afterId });\n }\n insertVideo(afterId, vid) {\n return this.insert({ block: "video", ...vid }, { after: afterId });\n }\n insertEquation(afterId, tex) {\n return this.insert({ block: "equation", tex }, { after: afterId });\n }\n insertInlineEquation(blockId, at, tex) {\n return this.insertInline(blockId, at, { inline: "equation", tex });\n }\n insertTextAfterInline(inlineRef, text) {\n return this.push({\n kind: "insertTextAfterInline",\n inline: inlineRef,\n text\n });\n }\n insertLineBreak(blockId, at) {\n return this.insertInline(blockId, at, { inline: "linebreak" });\n }\n insertDate(blockId, at, isoDate, displayFormat) {\n return this.insertInline(blockId, at, {\n inline: "date",\n date: isoDate,\n displayFormat\n });\n }\n mentionDate(blockId, at, isoDate, displayFormat) {\n return this.insertDate(blockId, at, isoDate, displayFormat);\n }\n insertInline(id, at, spec) {\n this.requireId(id);\n if (at < 0)\n throw new EditError(`inline offset must be >= 0, got ${at}`);\n const ref = this.mintRef();\n this.push({ kind: "insertInline", ref, node: id, at, spec });\n return ref;\n }\n insertMention(blockId, at, mention) {\n return this.insertInline(blockId, at, { inline: "mention", mention });\n }\n mentionUser(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "user", ...entity });\n }\n mentionContact(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "contact", ...entity });\n }\n mentionGroup(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "group", ...entity });\n }\n mentionDocument(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "document", ...entity });\n }\n mentionAgentSession(blockId, at, entity) {\n return this.insertMention(blockId, at, {\n kind: "agent_session",\n ...entity\n });\n }\n mentionPullRequest(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "pr", ...entity });\n }\n mentionBookingLink(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "booking_link", ...entity });\n }\n mentionTag(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "tag", ...entity });\n }\n setImageAlt(id, alt) {\n this.requireId(id);\n return this.push({ kind: "setImageAlt", node: id, alt });\n }\n setImageUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setImageUrl", node: id, url });\n }\n setVideoUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setVideoUrl", node: id, url });\n }\n setVideoControls(id, controls) {\n this.requireId(id);\n return this.push({ kind: "setVideoControls", node: id, controls });\n }\n setDate(id, date, displayFormat) {\n this.requireId(id);\n return this.push({ kind: "setDate", node: id, date, displayFormat });\n }\n}\nfunction editorMethodNames(target) {\n const names = new Set;\n for (let proto = target;proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key === "constructor" || key.startsWith("_"))\n continue;\n if (typeof target[key] === "function") {\n names.add(key);\n }\n }\n }\n return [...names];\n}\nfunction suggestMethods(wanted, names) {\n const normalizedWanted = wanted.toLowerCase();\n const scored = names.map((name) => {\n const normalizedName = name.toLowerCase();\n let score = 0;\n if (normalizedName === normalizedWanted)\n score = 1000;\n else if (normalizedName.includes(normalizedWanted) || normalizedWanted.includes(normalizedName)) {\n score = 100 + Math.min(normalizedName.length, normalizedWanted.length);\n } else {\n while (score < normalizedName.length && score < normalizedWanted.length && normalizedName[score] === normalizedWanted[score]) {\n score++;\n }\n }\n return { name, score };\n });\n scored.sort((a, b) => b.score - a.score);\n return scored.filter(({ score }) => score >= 3).slice(0, 3).map(({ name }) => name);\n}\nfunction createDocumentEditor(options) {\n const target = new DocumentEditor(options);\n return new Proxy(target, {\n get(editor, property) {\n const value = editor[property];\n if (value !== undefined || typeof property !== "string") {\n return typeof value === "function" ? value.bind(editor) : value;\n }\n return () => {\n const suggestions = suggestMethods(property, editorMethodNames(editor));\n throw new Error(`editor.${property} does not exist` + (suggestions.length ? `. Did you mean: ${suggestions.join(", ")}?` : ".") + " The editor is write-only — to inspect the document use the readDocument tool, not a call inside the snippet.");\n };\n }\n });\n}';