Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calendar): add reviewed AI booking-link workflows (#7619)

Wolf Mermelstein9c1eaf44a83b
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 3a2122f727..b0631331c2 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -438,6 +438,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -466,6 +467,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -610,6 +612,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -632,6 +635,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1312,6 +1316,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1334,6 +1339,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1559,6 +1565,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1581,6 +1588,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2565,6 +2573,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_bots",
"crates/channel_sender",
@@ -2588,6 +2597,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4390,6 +4400,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4413,6 +4424,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/ensure_exists",
"crates/entity_access",
@@ -4561,6 +4573,7 @@
"crates/broadcast",
"crates/cal",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_bots",
"crates/channel_labels",
@@ -4589,6 +4602,7 @@
"crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8432,6 +8446,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -8454,6 +8469,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8601,6 +8617,7 @@
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -8623,6 +8640,7 @@
"crates/email",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
diff --git a/Cargo.lock b/Cargo.lock
index 8399eb2cd4..0696705863 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -925,6 +925,7 @@ dependencies = [
"bot_id",
"bots",
"calendar_events",
+ "calendar_scheduling",
"call",
"channels",
"chat",
@@ -958,6 +959,7 @@ dependencies = [
"lexical_client",
"lexical_mention_extractor",
"macro_auth",
+ "macro_authorization",
"macro_aws_config",
"macro_db_client",
"macro_env",
@@ -973,6 +975,7 @@ dependencies = [
"model-entity",
"model_notifications",
"model_owner",
+ "model_user",
"models_dcs",
"models_email",
"models_pagination",
@@ -3554,6 +3557,9 @@ dependencies = [
name = "calendar_scheduling"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
+ "anyhow",
+ "async-trait",
"axum",
"calendar_events",
"chrono",
@@ -3564,6 +3570,7 @@ dependencies = [
"model_user",
"reqwest 0.13.4",
"rootcause",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/docs/AI/mcp/tools/create-booking-link.mdx b/apps/docs/AI/mcp/tools/create-booking-link.mdx
new file mode 100644
index 0000000000..d9c8c41efc
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/create-booking-link.mdx
@@ -0,0 +1,16 @@
+---
+title: CreateBookingLink
+description: >-
+ Create a reusable booking page, not a calendar meeting.
+---
+
+# 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. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing Macro team ID, or null for a personal booking link. |
+| `draft` | BookingLinkDraft | Yes | Complete proposal reviewed and validated before saving. |
diff --git a/apps/docs/AI/mcp/tools/edit-booking-link.mdx b/apps/docs/AI/mcp/tools/edit-booking-link.mdx
new file mode 100644
index 0000000000..bcba3a15cc
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/edit-booking-link.mdx
@@ -0,0 +1,18 @@
+---
+title: EditBookingLink
+description: >-
+ Edit exactly one existing booking link.
+---
+
+# 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 present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing Macro team ID, or null for a personal booking link. |
+| `eventTypeId` | string | Yes | Existing link identity returned by ListBookingLinks. |
+| `expectedRevision` | integer | Yes | Revision returned by ListBookingLinks; guards against concurrent settings changes. |
+| `draft` | BookingLinkDraft | Yes | Complete proposal reviewed and validated before saving. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index d42fa32fed..04c32d04da 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -16,6 +16,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ConfigureAgent](/AI/mcp/tools/configure-agent)
- [ConfigureBot](/AI/mcp/tools/configure-bot)
- [ContentSearch](/AI/mcp/tools/content-search)
+- [CreateBookingLink](/AI/mcp/tools/create-booking-link)
- [CreateBot](/AI/mcp/tools/create-bot)
- [CreateCalendarEvent](/AI/mcp/tools/create-calendar-event)
- [CreateChannel](/AI/mcp/tools/create-channel)
@@ -35,6 +36,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [DescribeDatabase](/AI/mcp/tools/describe-database)
- [DispatchCodingAgent](/AI/mcp/tools/dispatch-coding-agent)
- [DisplayResults](/AI/mcp/tools/display-results)
+- [EditBookingLink](/AI/mcp/tools/edit-booking-link)
- [EditDocument](/AI/mcp/tools/edit-document)
- [EditPresentation](/AI/mcp/tools/edit-presentation)
- [EditSpreadsheet](/AI/mcp/tools/edit-spreadsheet)
@@ -48,6 +50,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ImportNotionPage](/AI/mcp/tools/import-notion-page)
- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)
- [ListAgents](/AI/mcp/tools/list-agents)
+- [ListBookingLinks](/AI/mcp/tools/list-booking-links)
- [ListBots](/AI/mcp/tools/list-bots)
- [ListCalendarEvents](/AI/mcp/tools/list-calendar-events)
- [ListCalendars](/AI/mcp/tools/list-calendars)
diff --git a/apps/docs/AI/mcp/tools/list-booking-links.mdx b/apps/docs/AI/mcp/tools/list-booking-links.mdx
new file mode 100644
index 0000000000..d961d61917
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/list-booking-links.mdx
@@ -0,0 +1,16 @@
+---
+title: ListBookingLinks
+description: >-
+ Discover and reuse the user's booking links before creating one.
+---
+
+# 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.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing Macro team ID, or null for personal links. |
+| `query` | string | No | Optional text to match in the link title, slug or description. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index e5f58362cd..4e7757f50a 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -7,6 +7,7 @@
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
+ "AI/mcp/tools/create-booking-link",
"AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-channel",
@@ -26,6 +27,7 @@
"AI/mcp/tools/describe-database",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
+ "AI/mcp/tools/edit-booking-link",
"AI/mcp/tools/edit-document",
"AI/mcp/tools/edit-presentation",
"AI/mcp/tools/edit-spreadsheet",
@@ -39,6 +41,7 @@
"AI/mcp/tools/import-notion-page",
"AI/mcp/tools/issue-bot-credential",
"AI/mcp/tools/list-agents",
+ "AI/mcp/tools/list-booking-links",
"AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 84fe2a242e..e0688650ab 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -78,6 +78,7 @@
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
+ "AI/mcp/tools/create-booking-link",
"AI/mcp/tools/create-bot",
"AI/mcp/tools/create-calendar-event",
"AI/mcp/tools/create-channel",
@@ -97,6 +98,7 @@
"AI/mcp/tools/describe-database",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
+ "AI/mcp/tools/edit-booking-link",
"AI/mcp/tools/edit-document",
"AI/mcp/tools/edit-presentation",
"AI/mcp/tools/edit-spreadsheet",
@@ -110,6 +112,7 @@
"AI/mcp/tools/import-notion-page",
"AI/mcp/tools/issue-bot-credential",
"AI/mcp/tools/list-agents",
+ "AI/mcp/tools/list-booking-links",
"AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
diff --git a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
index c5ad9fe124..11dd80328c 100644
--- a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
+++ b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
@@ -1,3 +1,5 @@
+import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
+import { BookingDraftComposer } from '@core/component/AI/component/tool/booking-link/DraftComposer';
/**
* The live controls for a question the agent is waiting on, shared by the
* session's card and the channel's Magic Chip: a form's fields and Submit,
@@ -354,6 +356,17 @@ export function UserToolComposer(props: {
const locked = () => !props.review.canAnswer();
return (
<Switch fallback={props.fallback}>
+ <Match
+ when={
+ props.tool.name === 'CreateBookingLink' ||
+ props.tool.name === 'EditBookingLink'
+ }
+ >
+ <BookingDraftComposer
+ initialData={props.tool.data as BookingLinkArgs}
+ sink={sink<BookingLinkArgs>()}
+ />
+ </Match>
<Match when={props.tool.name === 'CreateCalendarEvent'}>
<CalendarDraftComposer
initialData={props.tool.data as CreateCalendarEvent}
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index 512f10eb79..f15aea6f99 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -21,6 +21,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
ConfigureAgent: (whose) => `change ${whose} agents`,
ConfigureBot: (whose) => `change ${whose} bots`,
ContentSearch: (whose) => `search ${whose} workspace`,
+ CreateBookingLink: (whose) => `create a booking link for ${whose} calendar`,
CreateBot: (whose) => `create a bot in ${whose} workspace`,
CreateCalendarEvent: (whose) => `add an event to ${whose} calendar`,
CreateChannel: (whose) => `create a channel from ${whose} account`,
@@ -40,6 +41,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
DescribeDatabase: (whose) => `read ${whose} databases`,
DisplayResults: (whose) => `show results from ${whose} workspace`,
DispatchCodingAgent: (whose) => `start a coding agent with ${whose} access`,
+ EditBookingLink: (whose) => `edit ${whose} booking links`,
EditDocument: (whose) => `edit ${whose} documents`,
EditPresentation: (whose) => `edit ${whose} presentations`,
EditSpreadsheet: (whose) => `edit ${whose} spreadsheets`,
@@ -53,6 +55,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
ImportNotionPage: (whose) => `import a Notion page into ${whose} workspace`,
IssueBotCredential: (whose) => `issue credentials for ${whose} bots`,
ListAgents: (whose) => `list ${whose} agents`,
+ ListBookingLinks: (whose) => `read ${whose} booking links`,
ListBots: (whose) => `list ${whose} bots`,
ListCalendarEvents: (whose) => `read ${whose} calendar`,
ListCalendars: (whose) => `read ${whose} calendar`,
diff --git a/apps/web/src/features/scheduling/browser-test/booking-ai.html b/apps/web/src/features/scheduling/browser-test/booking-ai.html
new file mode 100644
index 0000000000..974d47dc5f
--- /dev/null
+++ b/apps/web/src/features/scheduling/browser-test/booking-ai.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Booking AI review QA</title></head><body><div id="root"></div><script type="module" src="./booking-ai.tsx"></script></body></html>
diff --git a/apps/web/src/features/scheduling/browser-test/booking-ai.tsx b/apps/web/src/features/scheduling/browser-test/booking-ai.tsx
new file mode 100644
index 0000000000..ad73f7c02d
--- /dev/null
+++ b/apps/web/src/features/scheduling/browser-test/booking-ai.tsx
@@ -0,0 +1,109 @@
+import '../../../index.css';
+import '@fontsource-variable/inter';
+import { createSignal, onMount, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { createElicitationReviewSink } from '../../block-agent/state/elicitation-review-sink';
+import { macroLightTheme } from '../../theme/themes/macro-light';
+import { themeCssVars } from '../../theme/utils/themeColorTokens';
+import { BookingLinkDraftComposer } from '../components/booking-link-draft-composer';
+import type { BookingLinkArgs } from '../core/booking-link';
+import { newEventType, newSchedule } from '../core/types';
+
+function Fixture() {
+ onMount(() => {
+ for (const [key, value] of Object.entries(themeCssVars(macroLightTheme)))
+ document.documentElement.style.setProperty(key, value);
+ document.documentElement.style.colorScheme = 'light';
+ });
+ const schedule = newSchedule('America/New_York');
+ const { id: _scheduleId, ...hours } = schedule;
+ const {
+ id: _eventId,
+ scheduleId: _sid,
+ ...details
+ } = newEventType(schedule.id, ['macro|[email protected]'], false);
+ const initial: BookingLinkArgs = {
+ teamId: null,
+ draft: {
+ event: { ...details, title: 'Intro call', slug: 'intro', enabled: true },
+ schedule: hours,
+ },
+ };
+ const [draft, setDraft] = createSignal<BookingLinkArgs>();
+ const [result, setResult] = createSignal('');
+ const [fail, setFail] = createSignal(false);
+ const [reviewCount, setReviewCount] = createSignal(0);
+ const sink = createElicitationReviewSink<BookingLinkArgs>({
+ canAnswer: () => true,
+ respond: async (answer) => {
+ if (fail())
+ throw new Error(
+ 'Configuration changed. Refresh and review the latest booking link.'
+ );
+ setReviewCount((count) => count + 1);
+ setResult(JSON.stringify(answer, null, 2));
+ setDraft(undefined);
+ return true;
+ },
+ });
+ return (
+ <main class="h-screen overflow-auto bg-panel p-2 text-ink sm:p-6">
+ <div class="mx-auto flex max-w-3xl flex-col gap-3">
+ <h1 class="text-xl font-semibold">Booking link review</h1>
+ <p>
+ Isolated QA fixture. Decisions use the agent elicitation sink; no
+ hosted data or invitations.
+ </p>
+ <div class="flex flex-wrap gap-4">
+ <button
+ onClick={() => {
+ setDraft(undefined);
+ queueMicrotask(() => setDraft(structuredClone(initial)));
+ }}
+ >
+ New booking link
+ </button>
+ <button
+ onClick={() => {
+ setDraft(undefined);
+ queueMicrotask(() =>
+ setDraft({
+ ...structuredClone(initial),
+ eventTypeId: crypto.randomUUID(),
+ expectedRevision: 7,
+ })
+ );
+ }}
+ >
+ Edit booking link
+ </button>
+ <label>
+ <input
+ type="checkbox"
+ checked={fail()}
+ onChange={(event) => setFail(event.currentTarget.checked)}
+ />
+ Simulate save error
+ </label>
+ </div>
+ <Show when={draft()} keyed>
+ {(value) => (
+ <BookingLinkDraftComposer
+ initialData={value}
+ sink={sink}
+ members={[]}
+ />
+ )}
+ </Show>
+ <output aria-label="Review count">{reviewCount()}</output>
+ <pre
+ class="overflow-auto whitespace-pre-wrap break-all"
+ aria-label="Review result"
+ >
+ {result()}
+ </pre>
+ </div>
+ </main>
+ );
+}
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx b/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx
new file mode 100644
index 0000000000..a8500c4cf8
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx
@@ -0,0 +1,137 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { BookingLinkArgs } from '../core/booking-link';
+import { newEventType, newSchedule } from '../core/types';
+import { BookingLinkDraftComposer } from './booking-link-draft-composer';
+
+afterEach(cleanup);
+function fixture(execute = vi.fn(async (_args: BookingLinkArgs) => true)) {
+ const schedule = newSchedule('America/New_York');
+ const event = {
+ ...newEventType(schedule.id, ['macro|[email protected]'], false),
+ title: 'Intro',
+ slug: 'intro',
+ };
+ const reject = vi.fn(async () => true);
+ render(() => (
+ <BookingLinkDraftComposer
+ initialData={{ draft: { event, schedule } }}
+ members={[]}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: execute,
+ onReject: reject,
+ }}
+ />
+ ));
+ return { execute, reject };
+}
+it('submits edited details and hours together exactly once', async () => {
+ const { execute } = fixture();
+ fireEvent.input(screen.getByLabelText('Title'), {
+ target: { value: 'Discovery' },
+ });
+ fireEvent.input(screen.getByLabelText('Monday start 1'), {
+ target: { value: '10:00' },
+ });
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Create booking link' })[0]
+ );
+ await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
+ expect(execute.mock.calls[0][0].draft.event.title).toBe('Discovery');
+ expect(
+ execute.mock.calls[0][0].draft.schedule.weekly[1].windows[0].start
+ ).toBe('10:00');
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Create booking link' })[0]
+ );
+ expect(execute).toHaveBeenCalledTimes(1);
+});
+it('cancels without executing the draft', async () => {
+ const { execute, reject } = fixture();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel review' }));
+ await waitFor(() => expect(reject).toHaveBeenCalledTimes(1));
+ expect(execute).not.toHaveBeenCalled();
+});
+it('keeps the edited draft usable after an execution failure', async () => {
+ const execute = vi.fn(async () => {
+ throw new Error('Configuration changed. Refresh and try again.');
+ });
+ fixture(execute);
+ fireEvent.input(screen.getByLabelText('Title'), {
+ target: { value: 'Retained edit' },
+ });
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Create booking link' })[0]
+ );
+ expect((await screen.findByRole('alert')).textContent).toContain(
+ 'Configuration changed'
+ );
+ expect((screen.getByLabelText('Title') as HTMLInputElement).value).toBe(
+ 'Retained edit'
+ );
+});
+
+it('allows an identical create retry even when the saved slug is already listed', async () => {
+ const schedule = newSchedule('UTC');
+ const event = {
+ ...newEventType(schedule.id, ['macro|[email protected]'], false),
+ title: 'Intro',
+ slug: 'intro',
+ };
+ const execute = vi.fn(async (_args: BookingLinkArgs) => true);
+ render(() => (
+ <BookingLinkDraftComposer
+ initialData={{ draft: { event, schedule } }}
+ members={[]}
+ events={[event]}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: execute,
+ onReject: async () => true,
+ }}
+ />
+ ));
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Create booking link' })[0]
+ );
+ await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
+});
+it('lets the user repair incomplete availability and its name in the review', async () => {
+ const schedule = { ...newSchedule('UTC'), name: '', weekly: [] };
+ const event = {
+ ...newEventType(schedule.id, ['macro|[email protected]'], false),
+ title: 'Intro',
+ slug: 'intro',
+ };
+ const execute = vi.fn(async (_args: BookingLinkArgs) => true);
+ render(() => (
+ <BookingLinkDraftComposer
+ initialData={{ draft: { event, schedule } }}
+ members={[]}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: execute,
+ onReject: async () => true,
+ }}
+ />
+ ));
+ fireEvent.input(screen.getByLabelText('Availability name'), {
+ target: { value: 'Repaired hours' },
+ });
+ fireEvent.click(
+ screen.getAllByRole('button', { name: 'Create booking link' })[0]
+ );
+ await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
+ expect(execute.mock.calls[0][0].draft.schedule.weekly).toHaveLength(7);
+ expect(execute.mock.calls[0][0].draft.schedule.name).toBe('Repaired hours');
+});
diff --git a/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx b/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx
new file mode 100644
index 0000000000..6f0bbd4caf
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx
@@ -0,0 +1,154 @@
+import type { UserToolReviewSink } from '@core/component/AI/component/tool/user-tool-review';
+import { createSignal, onCleanup, Show } from 'solid-js';
+import {
+ type BookingLinkArgs,
+ editableBookingWeek,
+} from '../core/booking-link';
+import {
+ type AvailabilitySchedule,
+ type EventType,
+ type SchedulingMember,
+ validateSchedule,
+} from '../core/types';
+import { EventEditor } from './event-editor';
+import { Field, TextInput } from './fields';
+import { ScheduleFields } from './schedule-editor';
+
+/** One review form shared by chat and agent elicitation, using the normal booking controls. */
+export function BookingLinkDraftComposer(props: {
+ initialData: BookingLinkArgs;
+ sink: UserToolReviewSink<BookingLinkArgs>;
+ members: SchedulingMember[];
+ events?: EventType[];
+}) {
+ // These identities only connect the local controls. The domain assigns persisted IDs.
+ const scheduleId = crypto.randomUUID();
+ const eventId =
+ 'eventTypeId' in props.initialData
+ ? props.initialData.eventTypeId
+ : crypto.randomUUID();
+ const [schedule, setSchedule] = createSignal<AvailabilitySchedule>({
+ ...props.initialData.draft.schedule,
+ weekly: editableBookingWeek(props.initialData.draft.schedule.weekly),
+ id: scheduleId,
+ });
+ const [event, setEvent] = createSignal<EventType>({
+ ...props.initialData.draft.event,
+ dailyLimit: props.initialData.draft.event.dailyLimit ?? null,
+ id: eventId,
+ scheduleId,
+ });
+ const [pending, setPending] = createSignal(false);
+ const [finished, setFinished] = createSignal(false);
+ const [error, setError] = createSignal('');
+ const locked = () => pending() || finished() || !props.sink.canAct();
+ const args = (nextEvent = event()): BookingLinkArgs => {
+ const { id: _eventId, scheduleId: _scheduleId, ...eventDraft } = nextEvent;
+ const { id: _id, ...scheduleDraft } = schedule();
+ return {
+ ...props.initialData,
+ draft: { event: eventDraft, schedule: scheduleDraft },
+ };
+ };
+ const changeSchedule = (
+ update: (current: AvailabilitySchedule) => AvailabilitySchedule
+ ) => {
+ if (locked()) return;
+ setSchedule(update);
+ props.sink.onEdit?.(args());
+ };
+ const decide = async (nextEvent?: EventType) => {
+ if (locked()) return;
+ setError('');
+ if (nextEvent) {
+ const message = validateSchedule(schedule());
+ if (message) {
+ setError(message);
+ return;
+ }
+ }
+ setPending(true);
+ try {
+ const done = nextEvent
+ ? await props.sink.onExecute(args(nextEvent))
+ : await props.sink.onReject();
+ setFinished(done);
+ if (!done)
+ setError(
+ 'Could not finish this review. Your edits are preserved; try again.'
+ );
+ } catch (cause) {
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : 'Could not save the booking link. Try again.'
+ );
+ } finally {
+ setPending(false);
+ }
+ };
+ onCleanup(() => props.sink.onDispose?.());
+ return (
+ <div
+ data-booking-link-composer
+ class="max-h-[min(80dvh,52rem)] min-w-0 overflow-y-auto overscroll-contain rounded-xl border border-edge-muted bg-panel p-3 text-ink sm:p-4"
+ >
+ <p class="mb-4 text-sm text-ink-muted">
+ Review your booking link. Changes to availability apply only to this
+ link. No invitations are sent until a guest books.
+ </p>
+ <Show when={props.sink.lockedNotice()}>
+ {(notice) => <p class="mb-3 text-sm text-ink-muted">{notice()}</p>}
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="mb-3 text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <fieldset
+ disabled={locked()}
+ inert={locked()}
+ class="min-w-0 disabled:opacity-60"
+ >
+ <EventEditor
+ event={event()}
+ events={
+ 'eventTypeId' in props.initialData ? (props.events ?? []) : []
+ }
+ schedules={[schedule()]}
+ members={props.members}
+ team={!!props.initialData.teamId}
+ saving={pending()}
+ cancelEditingLabel="Cancel review"
+ submitLabel={
+ 'eventTypeId' in props.initialData
+ ? 'Save booking link'
+ : 'Create booking link'
+ }
+ onChange={(value) => {
+ if (locked()) return;
+ setEvent(value);
+ props.sink.onEdit?.(args(value));
+ }}
+ onSave={(value) => decide(value)}
+ onCancel={() => void decide()}
+ availability={
+ <div class="flex min-w-0 flex-col gap-5">
+ <Field label="Availability name">
+ <TextInput
+ required
+ value={schedule().name}
+ onInput={(event) => {
+ const name = event.currentTarget.value;
+ changeSchedule((current) => ({ ...current, name }));
+ }}
+ />
+ </Field>
+ <ScheduleFields schedule={schedule()} onChange={changeSchedule} />
+ </div>
+ }
+ />
+ </fieldset>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/event-editor.tsx b/apps/web/src/features/scheduling/components/event-editor.tsx
index 7aa303fd8c..a378d61ea1 100644
--- a/apps/web/src/features/scheduling/components/event-editor.tsx
+++ b/apps/web/src/features/scheduling/components/event-editor.tsx
@@ -3,7 +3,7 @@ import {
SettingsSection,
} from '@app/features/settings/primitives';
import { Button } from '@ui';
-import { createSignal, For, Index, Show } from 'solid-js';
+import { createSignal, For, Index, type JSX, Show } from 'solid-js';
import { unwrap } from 'solid-js/store';
import {
type AvailabilitySchedule,
@@ -22,10 +22,22 @@ export function EventEditor(props: {
members: SchedulingMember[];
team: boolean;
saving: boolean;
+ /** Availability slot for an inline draft, otherwise show saved schedule selection. */
+ availability?: JSX.Element;
+ submitLabel?: string;
+ cancelEditingLabel?: string;
+ onChange?: (event: EventType) => void;
onSave: (event: EventType) => Promise<void>;
onCancel: () => void;
}) {
- const [draft, setDraft] = createSignal(structuredClone(unwrap(props.event)));
+ const [draft, setDraftValue] = createSignal(
+ structuredClone(unwrap(props.event))
+ );
+ const setDraft = (update: (current: EventType) => EventType) => {
+ const next = setDraftValue(update);
+ props.onChange?.(next);
+ return next;
+ };
const [error, setError] = createSignal('');
const update = <K extends keyof EventType>(key: K, value: EventType[K]) =>
setDraft((d) => ({ ...d, [key]: value }));
@@ -57,7 +69,7 @@ export function EventEditor(props: {
<form onSubmit={(e) => void save(e)} class="@container min-w-0">
<div class="flex min-w-0 flex-col gap-5">
<Button variant="ghost" class="self-start" onClick={props.onCancel}>
- Cancel editing
+ {props.cancelEditingLabel ?? 'Cancel editing'}
</Button>
<header class="mb-7 flex items-start justify-between gap-4">
<div class="min-w-0">
@@ -71,7 +83,7 @@ export function EventEditor(props: {
</p>
</div>
<Button type="submit" variant="strong" disabled={props.saving}>
- {props.saving ? 'Saving…' : 'Save changes'}
+ {props.saving ? 'Saving…' : (props.submitLabel ?? 'Save changes')}
</Button>
</header>
<div class="flex min-w-0 flex-col gap-7">
@@ -165,54 +177,63 @@ export function EventEditor(props: {
>
<SettingsCard>
<div class="flex flex-col gap-5 p-6">
- <Field label="Availability schedule">
- <SelectInput
- label="Availability schedule"
- value={draft().scheduleId}
- options={props.schedules.map((s) => ({
- value: s.id,
- label: s.name,
- }))}
- onChange={(value) => update('scheduleId', value)}
- />
- </Field>
<Show
- when={props.schedules.find(
- (s) => s.id === draft().scheduleId
- )}
- >
- {(schedule) => (
- <div class="overflow-hidden rounded-lg border border-edge-muted">
- <div class="border-b border-edge-muted bg-surface-2 px-4 py-3 text-sm font-medium">
- Weekly hours{' '}
- <span class="ml-2 font-normal text-ink-muted">
- {schedule().timeZone.replaceAll('_', ' ')}
- </span>
- </div>
- <dl class="divide-y divide-edge-muted">
- <For each={schedule().weekly}>
- {(day) => (
- <div class="flex flex-wrap justify-between gap-2 px-4 py-3 text-sm">
- <dt>{WEEKDAYS[day.day]}</dt>
- <dd class="text-ink-muted">
- {day.windows.length
- ? day.windows
- .map((w) => `${w.start} – ${w.end}`)
- .join(', ')
- : 'Unavailable'}
- </dd>
+ when={props.availability}
+ fallback={
+ <>
+ <Field label="Availability schedule">
+ <SelectInput
+ label="Availability schedule"
+ value={draft().scheduleId}
+ options={props.schedules.map((s) => ({
+ value: s.id,
+ label: s.name,
+ }))}
+ onChange={(value) => update('scheduleId', value)}
+ />
+ </Field>
+ <Show
+ when={props.schedules.find(
+ (s) => s.id === draft().scheduleId
+ )}
+ >
+ {(schedule) => (
+ <div class="overflow-hidden rounded-lg border border-edge-muted">
+ <div class="border-b border-edge-muted bg-surface-2 px-4 py-3 text-sm font-medium">
+ Weekly hours{' '}
+ <span class="ml-2 font-normal text-ink-muted">
+ {schedule().timeZone.replaceAll('_', ' ')}
+ </span>
</div>
- )}
- </For>
- </dl>
- </div>
- )}
+ <dl class="divide-y divide-edge-muted">
+ <For each={schedule().weekly}>
+ {(day) => (
+ <div class="flex flex-wrap justify-between gap-2 px-4 py-3 text-sm">
+ <dt>{WEEKDAYS[day.day]}</dt>
+ <dd class="text-ink-muted">
+ {day.windows.length
+ ? day.windows
+ .map((w) => `${w.start} – ${w.end}`)
+ .join(', ')
+ : 'Unavailable'}
+ </dd>
+ </div>
+ )}
+ </For>
+ </dl>
+ </div>
+ )}
+ </Show>
+ <p class="text-sm text-ink-muted">
+ Busy events on each host’s connected calendar are
+ excluded automatically. Manage weekly hours and date
+ overrides in Availability.
+ </p>
+ </>
+ }
+ >
+ {props.availability}
</Show>
- <p class="text-sm text-ink-muted">
- Busy events on each host’s connected calendar are excluded
- automatically. Manage weekly hours and date overrides in
- Availability.
- </p>
</div>
</SettingsCard>
</SettingsSection>
@@ -488,7 +509,7 @@ export function EventEditor(props: {
Cancel
</Button>
<Button type="submit" variant="strong" disabled={props.saving}>
- {props.saving ? 'Saving…' : 'Save changes'}
+ {props.saving ? 'Saving…' : (props.submitLabel ?? 'Save changes')}
</Button>
</div>
</div>
diff --git a/apps/web/src/features/scheduling/components/schedule-editor.tsx b/apps/web/src/features/scheduling/components/schedule-editor.tsx
index 6df3f3e544..4455805724 100644
--- a/apps/web/src/features/scheduling/components/schedule-editor.tsx
+++ b/apps/web/src/features/scheduling/components/schedule-editor.tsx
@@ -33,10 +33,10 @@ function Windows(props: {
<div class="flex min-w-0 flex-col gap-2">
<Index each={props.windows}>
{(window, i) => (
- <div class="flex min-w-0 items-center gap-2">
+ <div class="grid min-w-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2 @min-[560px]:grid-cols-[128px_auto_128px_auto]">
<TextInput
type="time"
- class="w-28 shrink-0 px-2 @min-[560px]:w-32"
+ class="min-w-0 px-2"
aria-label={`${props.label} start ${i + 1}`}
required
value={window().start}
@@ -51,7 +51,7 @@ function Windows(props: {
<span class="text-ink-muted">–</span>
<TextInput
type="time"
- class="w-28 shrink-0 px-2 @min-[560px]:w-32"
+ class="min-w-0 px-2"
aria-label={`${props.label} end ${i + 1}`}
required
value={window().end}
@@ -67,6 +67,7 @@ function Windows(props: {
variant="ghost"
size="icon-md"
label={`Remove ${props.label} range ${i + 1}`}
+ class="col-span-3 justify-self-end @min-[560px]:col-span-1"
onClick={() =>
props.onChange(props.windows.filter((_, j) => j !== i))
}
@@ -156,12 +157,6 @@ export function ScheduleEditor(props: {
structuredClone(unwrap(props.schedule))
);
const [error, setError] = createSignal('');
- const remembered = new Map<number, TimeWindow[]>();
- const setDay = (day: number, windows: TimeWindow[]) =>
- setDraft((d) => ({
- ...d,
- weekly: d.weekly.map((w) => (w.day === day ? { ...w, windows } : w)),
- }));
const save = async (e: SubmitEvent) => {
e.preventDefault();
const message = validateSchedule(draft());
@@ -203,6 +198,26 @@ export function ScheduleEditor(props: {
{error()}
</p>
</Show>
+ <ScheduleFields schedule={draft()} onChange={setDraft} />
+ </form>
+ );
+}
+
+/** Shared availability controls used by settings and AI review. */
+export function ScheduleFields(props: {
+ schedule: AvailabilitySchedule;
+ onChange: (
+ update: (current: AvailabilitySchedule) => AvailabilitySchedule
+ ) => void;
+}) {
+ const remembered = new Map<number, TimeWindow[]>();
+ const setDay = (day: number, windows: TimeWindow[]) =>
+ props.onChange((d) => ({
+ ...d,
+ weekly: d.weekly.map((w) => (w.day === day ? { ...w, windows } : w)),
+ }));
+ return (
+ <div class="@container flex min-w-0 flex-col gap-6">
<section class="overflow-hidden rounded-xl border border-edge-muted bg-surface-1">
<div class="border-b border-edge-muted bg-surface-2 px-5 py-5">
<h3 class="font-semibold">Weekly hours</h3>
@@ -211,7 +226,7 @@ export function ScheduleEditor(props: {
</p>
</div>
<div class="divide-y divide-edge-muted">
- <Index each={draft().weekly}>
+ <Index each={props.schedule.weekly}>
{(day) => (
<div class="grid grid-cols-[1fr_auto] items-start gap-x-3 gap-y-3 px-5 py-4 @min-[720px]:grid-cols-[160px_1fr_auto]">
<ToggleSwitch
@@ -272,7 +287,7 @@ export function ScheduleEditor(props: {
day={day().day}
disabled={!day().windows.length}
onCopy={(days) =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
weekly: d.weekly.map((w) =>
days.includes(w.day)
@@ -303,7 +318,7 @@ export function ScheduleEditor(props: {
variant="outline"
depth={2}
onClick={() =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
overrides: [...d.overrides, { date: '', windows: [] }],
}))
@@ -313,7 +328,7 @@ export function ScheduleEditor(props: {
Add date override
</Button>
</div>
- <Index each={draft().overrides}>
+ <Index each={props.schedule.overrides}>
{(override, index) => (
<div class="flex flex-col gap-4 border-t border-edge-muted px-5 py-4">
<div class="flex items-center justify-between gap-3">
@@ -324,7 +339,7 @@ export function ScheduleEditor(props: {
aria-label="Override date"
value={override().date}
onInput={(e) =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
overrides: d.overrides.map((o, i) =>
i === index ? { ...o, date: e.currentTarget.value } : o
@@ -337,7 +352,7 @@ export function ScheduleEditor(props: {
size="icon-md"
label="Remove date override"
onClick={() =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
overrides: d.overrides.filter((_, i) => i !== index),
}))
@@ -359,7 +374,7 @@ export function ScheduleEditor(props: {
label={override().date || 'Override'}
windows={override().windows}
onChange={(windows) =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
overrides: d.overrides.map((o, i) =>
i === index ? { ...o, windows } : o
@@ -376,7 +391,7 @@ export function ScheduleEditor(props: {
override().windows.at(-1)?.end === '23:59'
}
onClick={() =>
- setDraft((d) => ({
+ props.onChange((d) => ({
...d,
overrides: d.overrides.map((o, i) =>
i === index
@@ -403,10 +418,10 @@ export function ScheduleEditor(props: {
hint="Your weekly hours and date overrides use this time zone."
>
<TimeZoneInput
- value={draft().timeZone}
- onChange={(timeZone) => setDraft((d) => ({ ...d, timeZone }))}
+ value={props.schedule.timeZone}
+ onChange={(timeZone) => props.onChange((d) => ({ ...d, timeZone }))}
/>
</Field>
- </form>
+ </div>
);
}
diff --git a/apps/web/src/features/scheduling/core/booking-link.ts b/apps/web/src/features/scheduling/core/booking-link.ts
new file mode 100644
index 0000000000..9c9a7ebb19
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/booking-link.ts
@@ -0,0 +1,18 @@
+import type {
+ CreateBookingLink,
+ EditBookingLink,
+} from '@service-cognition/generated/tools/types';
+
+export type BookingLinkArgs = CreateBookingLink | EditBookingLink;
+
+/** Complete the editable week; retain duplicate-day windows so validation can flag overlaps. */
+export function editableBookingWeek(
+ weekly: BookingLinkArgs['draft']['schedule']['weekly']
+) {
+ return Array.from({ length: 7 }, (_, day) => ({
+ day,
+ windows: weekly
+ .filter((entry) => entry.day === day)
+ .flatMap((entry) => entry.windows),
+ }));
+}
diff --git a/apps/web/src/features/scheduling/queries/booking-link-review.ts b/apps/web/src/features/scheduling/queries/booking-link-review.ts
new file mode 100644
index 0000000000..de5406c394
--- /dev/null
+++ b/apps/web/src/features/scheduling/queries/booking-link-review.ts
@@ -0,0 +1,29 @@
+import { queryClient } from '@queries/client';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import type { BookingLinkArgs } from '../core/booking-link';
+import { schedulingKeys } from './keys';
+
+export type BookingReviewIdentity = {
+ chat_id: string;
+ messageId: string;
+ toolCallId: string;
+};
+export const executeBookingReview = (
+ identity: BookingReviewIdentity,
+ args: BookingLinkArgs
+) =>
+ cognitionApiServiceClient.callTool<'CreateBookingLink' | 'EditBookingLink'>({
+ ...identity,
+ args,
+ });
+export const persistBookingReview = (
+ identity: BookingReviewIdentity,
+ args: BookingLinkArgs
+) =>
+ cognitionApiServiceClient.updateToolCall<
+ 'CreateBookingLink' | 'EditBookingLink'
+ >({ ...identity, args });
+export const rejectBookingReview = (identity: BookingReviewIdentity) =>
+ cognitionApiServiceClient.rejectToolCall(identity);
+export const invalidateBookingLinks = () =>
+ queryClient.invalidateQueries({ queryKey: schedulingKeys._def });
diff --git a/apps/web/src/features/scheduling/vitest.config.ts b/apps/web/src/features/scheduling/vitest.config.ts
index 979759d7e2..51dbde7591 100644
--- a/apps/web/src/features/scheduling/vitest.config.ts
+++ b/apps/web/src/features/scheduling/vitest.config.ts
@@ -15,6 +15,10 @@ export default defineConfig({
test: {
name: 'scheduling',
environment: 'jsdom',
- include: ['src/features/scheduling/**/*.{test,spec}.{ts,tsx}'],
+ include: [
+ 'src/features/scheduling/**/*.{test,spec}.{ts,tsx}',
+ 'src/lib/core/component/AI/component/tool/BookingLinks.test.tsx',
+ 'src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx',
+ ],
},
});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx
new file mode 100644
index 0000000000..be60eaada7
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx
@@ -0,0 +1,66 @@
+import { newEventType, newSchedule } from '@app/features/scheduling/core/types';
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { createBookingLinkHandler } from './BookingLinks';
+import { ToolErrorContext } from './ToolRenderer';
+
+vi.mock('./booking-link/ChatCompose', () => ({
+ BookingChatCompose: () => <div>Editable booking review</div>,
+}));
+afterEach(cleanup);
+const schedule = newSchedule('UTC');
+const draft = {
+ event: {
+ ...newEventType(schedule.id, ['macro|[email protected]'], false),
+ title: 'Intro',
+ slug: 'intro',
+ },
+ schedule,
+};
+const context = {
+ tool: {
+ id: 'booking-call',
+ name: 'CreateBookingLink' as const,
+ data: { draft },
+ },
+ chat_id: 'chat',
+ message_id: 'message',
+ part_index: 0,
+ isComplete: true,
+ renderContext: { isStreaming: false, followedBy: () => false },
+};
+it('restores the editable review when a failed persisted response is remounted', () => {
+ const view = render(() => (
+ <ToolErrorContext.Provider value={() => 'failed'}>
+ <createBookingLinkHandler.render {...context} />
+ </ToolErrorContext.Provider>
+ ));
+ expect(view.getByText('Editable booking review')).toBeTruthy();
+ expect(
+ view.getByText('The previous save failed. Review your draft and try again.')
+ ).toBeTruthy();
+});
+it('shows the actual saved URL and paused state after execution', () => {
+ const view = render(() => (
+ <createBookingLinkHandler.render
+ {...context}
+ response={{
+ id: 'booking-call',
+ name: 'CreateBookingLink',
+ data: {
+ UserAction: {
+ profileId: crypto.randomUUID(),
+ eventTypeId: crypto.randomUUID(),
+ revision: 1,
+ draft,
+ url: 'https://macro.com/app/book/profile/intro',
+ },
+ },
+ }}
+ />
+ ));
+ expect(view.getByRole('link', { name: 'Intro' }).getAttribute('href')).toBe(
+ 'https://macro.com/app/book/profile/intro'
+ );
+ expect(view.getByText(/Paused/)).toBeTruthy();
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx
new file mode 100644
index 0000000000..f3ff5163e3
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx
@@ -0,0 +1,141 @@
+import Link from '@phosphor-icons/core/regular/link.svg';
+import type { BookingLinkResult } from '@service-cognition/generated/tools/types';
+import { createSignal, For, Match, Switch } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { BookingChatCompose } from './booking-link/ChatCompose';
+import { Tool } from './Tool';
+import {
+ createToolRenderer,
+ type RenderContext,
+ useToolError,
+} from './ToolRenderer';
+
+function LinkCard(props: {
+ label: string;
+ links?: BookingLinkResult[];
+ status?: string;
+ renderContext: RenderContext['renderContext'];
+}) {
+ const [expanded, setExpanded] = createSignal(true);
+ return (
+ <BaseTool
+ icon={Link}
+ type="call"
+ renderContext={props.renderContext}
+ response={
+ expanded() && props.links ? (
+ <Tool.List>
+ <For each={props.links}>
+ {(link) => (
+ <Tool.ListItem icon={<Link class="size-4" />}>
+ <div class="min-w-0 text-xs">
+ <a
+ href={link.url}
+ target="_blank"
+ rel="noreferrer"
+ class="break-words text-accent hover:underline"
+ >
+ {link.draft.event.title}
+ </a>
+ <p class="mt-1 text-ink-muted">
+ {link.draft.event.durationMinutes} minutes ·{' '}
+ {link.draft.event.enabled
+ ? 'Accepting bookings'
+ : 'Paused'}{' '}
+ · {link.draft.schedule.timeZone}
+ </p>
+ <p class="mt-1 break-all text-ink-muted">{link.url}</p>
+ </div>
+ </Tool.ListItem>
+ )}
+ </For>
+ </Tool.List>
+ ) : undefined
+ }
+ >
+ <span class="min-w-0 flex-1">{props.label}</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!props.links?.length}
+ status={
+ props.status ??
+ (props.links
+ ? `${props.links.length} ${props.links.length === 1 ? 'link' : 'links'}`
+ : undefined)
+ }
+ />
+ </BaseTool>
+ );
+}
+export const listBookingLinksHandler = createToolRenderer({
+ name: 'ListBookingLinks',
+ render: (ctx) => (
+ <LinkCard
+ label="Booking links"
+ links={ctx.response?.data.links}
+ renderContext={ctx.renderContext}
+ />
+ ),
+});
+
+function mutationHandler(name: 'CreateBookingLink' | 'EditBookingLink') {
+ return createToolRenderer({
+ name,
+ render: (ctx) => {
+ const response = () => ctx.response?.data;
+ const error = () => useToolError();
+ const saved = () => {
+ const result = response();
+ return typeof result === 'object' &&
+ result !== null &&
+ 'UserAction' in result
+ ? result.UserAction
+ : undefined;
+ };
+ const label =
+ name === 'CreateBookingLink'
+ ? 'Create booking link'
+ : 'Edit booking link';
+ return (
+ <Switch
+ fallback={
+ <LinkCard
+ label={label}
+ renderContext={ctx.renderContext}
+ status={response() === 'Rejected' ? 'Cancelled' : undefined}
+ />
+ }
+ >
+ <Match when={response() === 'PendingUserExecution' || error()}>
+ <p class="text-sm text-ink-muted">
+ {error()
+ ? 'The previous save failed. Review your draft and try again.'
+ : ''}
+ </p>
+ <BookingChatCompose
+ name={name}
+ chatId={ctx.chat_id}
+ messageId={ctx.message_id}
+ toolCallId={ctx.tool.id}
+ initialData={ctx.tool.data}
+ streamLocked={ctx.renderContext.isStreaming}
+ />
+ </Match>
+ <Match when={saved()}>
+ {(link) => (
+ <LinkCard
+ label={label}
+ links={[link()]}
+ status="Saved"
+ renderContext={ctx.renderContext}
+ />
+ )}
+ </Match>
+ </Switch>
+ );
+ },
+ });
+}
+export const createBookingLinkHandler = mutationHandler('CreateBookingLink');
+export const editBookingLinkHandler = mutationHandler('EditBookingLink');
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx
new file mode 100644
index 0000000000..aaab87e7e2
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx
@@ -0,0 +1,141 @@
+import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
+import {
+ executeBookingReview,
+ invalidateBookingLinks,
+ persistBookingReview,
+ rejectBookingReview,
+} from '@app/features/scheduling/queries/booking-link-review';
+import { useChatContext } from '@core/component/AI/context';
+import { toast } from '@core/component/Toast/Toast';
+import { useChatQuery } from '@queries/chat';
+import { deserializeToolResponse } from '@service-cognition/generated/tools/tool';
+import { debounce } from '@solid-primitives/scheduled';
+import type { UserToolReviewSink } from '../user-tool-review';
+import { BookingDraftComposer } from './DraftComposer';
+
+/** Chat persists drafts and finishes the existing deferred tool call. */
+export function BookingChatCompose(props: {
+ chatId: string;
+ messageId: string;
+ toolCallId: string;
+ name: 'CreateBookingLink' | 'EditBookingLink';
+ initialData: BookingLinkArgs;
+ streamLocked: boolean;
+}) {
+ const chat = useChatContext();
+ const query = useChatQuery(() => props.chatId);
+ const canAct = () =>
+ query.isSuccess &&
+ query.data.userAccessLevel === 'owner' &&
+ !props.streamLocked;
+ const identity = () => ({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ });
+ let latest: BookingLinkArgs | undefined;
+ let queue = Promise.resolve();
+ let finalized = false;
+ const persist = () => {
+ const args = latest;
+ if (!args || finalized) return;
+ const previous = queue;
+ queue = (async () => {
+ await previous;
+ if (finalized) return;
+ try {
+ const result = await persistBookingReview(identity(), args);
+ if (result.isErr()) toast.failure('Could not save booking draft');
+ } catch {
+ toast.failure('Could not save booking draft');
+ }
+ })();
+ };
+ const deferredPersist = debounce(persist, 200);
+ function updateResponse(response: unknown, args?: BookingLinkArgs) {
+ chat.setMessages((messages) =>
+ messages.map((message) => {
+ if (message.id !== props.messageId || !Array.isArray(message.content))
+ return message;
+ return {
+ ...message,
+ content: message.content.map((part) => {
+ if (
+ part.type === 'toolCallResponseJson' &&
+ part.id === props.toolCallId
+ )
+ return { ...part, json: response };
+ if (
+ args &&
+ part.type === 'toolCall' &&
+ part.id === props.toolCallId
+ )
+ return { ...part, json: args };
+ return part;
+ }),
+ };
+ })
+ );
+ }
+ const sink: UserToolReviewSink<BookingLinkArgs> = {
+ canAct,
+ lockedNotice: () =>
+ props.streamLocked
+ ? 'Waiting for the response to finish.'
+ : query.isSuccess && query.data.userAccessLevel !== 'owner'
+ ? 'Only the chat owner can finish this booking link.'
+ : undefined,
+ onEdit: (args) => {
+ latest = args;
+ deferredPersist();
+ },
+ onExecute: async (args) => {
+ deferredPersist.clear();
+ await queue;
+ const result = await executeBookingReview(identity(), args);
+ if (result.isErr())
+ throw new Error('Could not save the booking link. Please try again.');
+ const response = result.value;
+ // Validate the result with the generated contract before presenting a saved link.
+ const parsed = deserializeToolResponse({
+ id: props.toolCallId,
+ name: props.name,
+ json: response,
+ });
+ if (
+ parsed.isErr() ||
+ typeof response !== 'object' ||
+ response === null ||
+ !('UserAction' in response)
+ ) {
+ const message =
+ typeof response === 'object' &&
+ response !== null &&
+ 'error' in response &&
+ typeof response.error === 'string'
+ ? response.error
+ : 'The booking link was not saved. Please try again.';
+ throw new Error(message);
+ }
+ finalized = true;
+ updateResponse(response, args);
+ void invalidateBookingLinks();
+ return true;
+ },
+ onReject: async () => {
+ deferredPersist.clear();
+ await queue;
+ const result = await rejectBookingReview(identity());
+ if (result.isErr())
+ throw new Error('Could not cancel the review. Please try again.');
+ finalized = true;
+ updateResponse('Rejected');
+ return true;
+ },
+ onDispose: () => {
+ deferredPersist.clear();
+ if (!finalized) persist();
+ },
+ };
+ return <BookingDraftComposer initialData={props.initialData} sink={sink} />;
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx
new file mode 100644
index 0000000000..7740f1c39f
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx
@@ -0,0 +1,45 @@
+import { newEventType, newSchedule } from '@app/features/scheduling/core/types';
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { BookingDraftComposer } from './DraftComposer';
+
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@queries/team/teams', () => ({
+ useCurrentTeamQuery: () => ({ isSuccess: false, isError: false }),
+}));
+vi.mock('@app/features/scheduling/queries/source', () => ({
+ useSchedulingProfileQuery: () => ({ isSuccess: false, isError: false }),
+}));
+vi.mock('@core/user', () => ({
+ tryMacroId: (id: string) => id,
+ getDisplayName: (id: string) => id,
+ macroIdToEmail: (id: string) => id,
+}));
+afterEach(cleanup);
+it.each([undefined, '019a19f7-2a01-7c21-809e-fc6bfb9ef327'])(
+ 'renders without treating unknown team membership as removal: %s',
+ (teamId) => {
+ const schedule = newSchedule('UTC');
+ const event = {
+ ...newEventType(schedule.id, ['macro|[email protected]'], !!teamId),
+ title: 'Intro',
+ slug: 'intro',
+ };
+ const view = render(() => (
+ <BookingDraftComposer
+ initialData={{ teamId, draft: { event, schedule } }}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: async () => true,
+ onReject: async () => true,
+ }}
+ />
+ ));
+ expect(view.getByLabelText('Title')).toBeTruthy();
+ expect(view.queryByText('Former team member')).toBeNull();
+ expect(view.getByRole('button', { name: 'Cancel' })).toBeTruthy();
+ }
+);
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx
new file mode 100644
index 0000000000..1af0de9d1e
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx
@@ -0,0 +1,74 @@
+import { BookingLinkDraftComposer } from '@app/features/scheduling/components/booking-link-draft-composer';
+import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
+import { useSchedulingProfileQuery } from '@app/features/scheduling/queries/source';
+import { useUserId } from '@core/context/user';
+import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';
+import { useCurrentTeamQuery } from '@queries/team/teams';
+import { Button } from '@ui';
+import { Show, Suspense } from 'solid-js';
+import type { UserToolReviewSink } from '../user-tool-review';
+
+type Props = {
+ initialData: BookingLinkArgs;
+ sink: UserToolReviewSink<BookingLinkArgs>;
+};
+function Content(props: Props) {
+ const user = useUserId();
+ const profile = useSchedulingProfileQuery(() => ({
+ id: props.initialData.teamId ?? user() ?? 'me',
+ teamId: props.initialData.teamId ?? undefined,
+ name: '',
+ canEdit: true,
+ }));
+ const team = useCurrentTeamQuery(() => !!props.initialData.teamId);
+ const members = () => {
+ const data = team.isSuccess ? team.data : undefined;
+ const roster =
+ data && data.team.id === props.initialData.teamId
+ ? data.members
+ : props.initialData.draft.event.hosts.map((user_id) => ({ user_id }));
+ return roster.map((member) => {
+ const id = tryMacroId(member.user_id);
+ return {
+ id: member.user_id,
+ name: id ? getDisplayName(id) : member.user_id,
+ email: id ? macroIdToEmail(id) : member.user_id,
+ };
+ });
+ };
+ return (
+ <>
+ <Show
+ when={profile.isError || (!!props.initialData.teamId && team.isError)}
+ >
+ <div role="status" class="mb-3 text-sm text-ink-muted">
+ Could not load current booking settings. Your draft is preserved.
+ <Button
+ variant="ghost"
+ onClick={() => {
+ void profile.refetch();
+ if (props.initialData.teamId) void team.refetch();
+ }}
+ >
+ Retry loading
+ </Button>
+ </div>
+ </Show>
+ <BookingLinkDraftComposer
+ {...props}
+ members={members()}
+ events={profile.isSuccess ? profile.data.eventTypes : []}
+ />
+ </>
+ );
+}
+/** Local boundary prevents settings queries from suspending the transcript. */
+export function BookingDraftComposer(props: Props) {
+ return (
+ <Suspense
+ fallback={<p class="p-4 text-ink-muted">Loading booking editor…</p>}
+ >
+ <Content {...props} />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 7a7fd40645..b08d4f3f14 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -13,6 +13,11 @@ import { createMemo, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { configureAgentHandler, listAgentsHandler } from './Agents';
import { bashCodeExecutionHandler } from './BashCodeExecution';
+import {
+ createBookingLinkHandler,
+ editBookingLinkHandler,
+ listBookingLinksHandler,
+} from './BookingLinks';
import {
configureBotHandler,
createBotHandler,
@@ -166,6 +171,9 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
IssueBotCredential: issueBotCredentialHandler,
ListBots: listBotsHandler,
ManageBotChannelAccess: manageBotChannelAccessHandler,
+ ListBookingLinks: listBookingLinksHandler,
+ CreateBookingLink: createBookingLinkHandler,
+ EditBookingLink: editBookingLinkHandler,
CreateCalendarEvent: createCalendarEventHandler,
CreateConfirmedCalendarEvent: createConfirmedCalendarEventHandler,
UpdateCalendarEvent: updateCalendarEventHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 8214e8af89..9a6dbaeba1 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -1555,6 +1555,200 @@ export const SearchToolResponse = z.object({
),
});
+export const CreateBookingLink = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ draft: z
+ .object({
+ event: z
+ .object({
+ title: z.string(),
+ slug: z.string(),
+ description: z.string(),
+ durationMinutes: z.number().int().gte(0).lte(65535),
+ location: z.string(),
+ googleMeet: z.boolean(),
+ enabled: z.boolean(),
+ mode: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('individual'),
+ z.literal('collective'),
+ z.literal('roundRobin'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ hosts: z.array(z.string()),
+ beforeMinutes: z.number().int().gte(0).lte(65535),
+ afterMinutes: z.number().int().gte(0).lte(65535),
+ noticeMinutes: z.number().int().gte(0).lte(65535),
+ horizonDays: z.number().int().gte(0).lte(65535),
+ intervalMinutes: z.number().int().gte(0).lte(65535),
+ dailyLimit: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .optional(),
+ requiresConfirmation: z.boolean(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ label: z.string(),
+ required: z.boolean(),
+ })
+ ),
+ })
+ .strict(),
+ schedule: z
+ .object({
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export const UserToolResponseForBookingLinkResult = z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('PendingUserExecution'),
+ z.literal('Rejected'),
+ z
+ .object({
+ UserAction: z.object({
+ profileId: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ revision: z.number().int(),
+ draft: z
+ .object({
+ event: z
+ .object({
+ title: z.string(),
+ slug: z.string(),
+ description: z.string(),
+ durationMinutes: z.number().int().gte(0).lte(65535),
+ location: z.string(),
+ googleMeet: z.boolean(),
+ enabled: z.boolean(),
+ mode: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('individual'),
+ z.literal('collective'),
+ z.literal('roundRobin'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ hosts: z.array(z.string()),
+ beforeMinutes: z.number().int().gte(0).lte(65535),
+ afterMinutes: z.number().int().gte(0).lte(65535),
+ noticeMinutes: z.number().int().gte(0).lte(65535),
+ horizonDays: z.number().int().gte(0).lte(65535),
+ intervalMinutes: z.number().int().gte(0).lte(65535),
+ dailyLimit: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .optional(),
+ requiresConfirmation: z.boolean(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ label: z.string(),
+ required: z.boolean(),
+ })
+ ),
+ })
+ .strict(),
+ schedule: z
+ .object({
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ url: z.string(),
+ }),
+ })
+ .strict(),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ });
+
export const CreateBot = z.object({
teamId: z.union([z.string().uuid(), z.null()]).optional(),
name: z.string(),
@@ -2464,6 +2658,91 @@ export const DisplayResults = z.object({ view: z.any() });
export const DisplayResultsResponse = z.object({ message: z.string() });
+export const EditBookingLink = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ eventTypeId: z.string().uuid(),
+ expectedRevision: z.number().int(),
+ draft: z
+ .object({
+ event: z
+ .object({
+ title: z.string(),
+ slug: z.string(),
+ description: z.string(),
+ durationMinutes: z.number().int().gte(0).lte(65535),
+ location: z.string(),
+ googleMeet: z.boolean(),
+ enabled: z.boolean(),
+ mode: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('individual'),
+ z.literal('collective'),
+ z.literal('roundRobin'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ hosts: z.array(z.string()),
+ beforeMinutes: z.number().int().gte(0).lte(65535),
+ afterMinutes: z.number().int().gte(0).lte(65535),
+ noticeMinutes: z.number().int().gte(0).lte(65535),
+ horizonDays: z.number().int().gte(0).lte(65535),
+ intervalMinutes: z.number().int().gte(0).lte(65535),
+ dailyLimit: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .optional(),
+ requiresConfirmation: z.boolean(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ label: z.string(),
+ required: z.boolean(),
+ })
+ ),
+ })
+ .strict(),
+ schedule: z
+ .object({
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ })
+ .strict();
+
export const EditDocument = z.object({
document_id: z.string(),
instructions: z.string(),
@@ -5415,6 +5694,124 @@ export const ListAgentsResponse = z.object({
summary: z.string(),
});
+export const ListBookingLinks = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ query: z.union([z.string(), z.null()]).optional(),
+ })
+ .strict();
+
+export const ListBookingLinksResult = z.object({
+ teamIds: z.array(z.string().uuid()),
+ userId: z.string(),
+ profileId: z.string().uuid(),
+ revision: z.number().int(),
+ schedules: z.array(
+ z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(z.object({ start: z.string(), end: z.string() })),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(z.object({ start: z.string(), end: z.string() })),
+ })
+ ),
+ })
+ ),
+ links: z.array(
+ z.object({
+ profileId: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ revision: z.number().int(),
+ draft: z
+ .object({
+ event: z
+ .object({
+ title: z.string(),
+ slug: z.string(),
+ description: z.string(),
+ durationMinutes: z.number().int().gte(0).lte(65535),
+ location: z.string(),
+ googleMeet: z.boolean(),
+ enabled: z.boolean(),
+ mode: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('individual'),
+ z.literal('collective'),
+ z.literal('roundRobin'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ hosts: z.array(z.string()),
+ beforeMinutes: z.number().int().gte(0).lte(65535),
+ afterMinutes: z.number().int().gte(0).lte(65535),
+ noticeMinutes: z.number().int().gte(0).lte(65535),
+ horizonDays: z.number().int().gte(0).lte(65535),
+ intervalMinutes: z.number().int().gte(0).lte(65535),
+ dailyLimit: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .optional(),
+ requiresConfirmation: z.boolean(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ label: z.string(),
+ required: z.boolean(),
+ })
+ ),
+ })
+ .strict(),
+ schedule: z
+ .object({
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ url: z.string(),
+ })
+ ),
+});
+
export const ListBots = z.record(z.any());
export const ListBotsResponse = z.object({
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 0bccbd0876..96ca4e12a2 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -36,6 +36,10 @@ type ToolParserMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateBookingLink: {
+ call: types.CreateBookingLink;
+ response: types.UserToolResponseForBookingLinkResult;
+ };
CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
@@ -97,6 +101,10 @@ type ToolParserMap = {
call: types.DisplayResults;
response: types.DisplayResultsResponse;
};
+ EditBookingLink: {
+ call: types.EditBookingLink;
+ response: types.UserToolResponseForBookingLinkResult;
+ };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
@@ -137,6 +145,10 @@ type ToolParserMap = {
response: types.IssueBotCredentialResponse;
};
ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };
+ ListBookingLinks: {
+ call: types.ListBookingLinks;
+ response: types.ListBookingLinksResult;
+ };
ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
@@ -373,6 +385,10 @@ const toolParserMap = {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
},
+ CreateBookingLink: {
+ call: schemas.CreateBookingLink,
+ response: schemas.UserToolResponseForBookingLinkResult,
+ },
CreateBot: { call: schemas.CreateBot, response: schemas.CreateBotResponse },
CreateCalendarEvent: {
call: schemas.CreateCalendarEvent,
@@ -434,6 +450,10 @@ const toolParserMap = {
call: schemas.DisplayResults,
response: schemas.DisplayResultsResponse,
},
+ EditBookingLink: {
+ call: schemas.EditBookingLink,
+ response: schemas.UserToolResponseForBookingLinkResult,
+ },
EditDocument: {
call: schemas.EditDocument,
response: schemas.EditDocumentResponse,
@@ -480,6 +500,10 @@ const toolParserMap = {
call: schemas.ListAgents,
response: schemas.ListAgentsResponse,
},
+ ListBookingLinks: {
+ call: schemas.ListBookingLinks,
+ response: schemas.ListBookingLinksResult,
+ },
ListBots: { call: schemas.ListBots, response: schemas.ListBotsResponse },
ListCalendarEvents: {
call: schemas.ListCalendarEvents,
@@ -751,6 +775,10 @@ type ToolDataMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateBookingLink: {
+ call: types.CreateBookingLink;
+ response: types.UserToolResponseForBookingLinkResult;
+ };
CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
@@ -812,6 +840,10 @@ type ToolDataMap = {
call: types.DisplayResults;
response: types.DisplayResultsResponse;
};
+ EditBookingLink: {
+ call: types.EditBookingLink;
+ response: types.UserToolResponseForBookingLinkResult;
+ };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
@@ -852,6 +884,10 @@ type ToolDataMap = {
response: types.IssueBotCredentialResponse;
};
ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };
+ ListBookingLinks: {
+ call: types.ListBookingLinks;
+ response: types.ListBookingLinksResult;
+ };
ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 6028f2c658..d04f08f659 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
@@ -313,6 +313,19 @@ export type CalendarEventSearchTime =
* Side of a folded conversation.
*/
export type AgentSessionAuthor = 'user' | 'agent';
+/**
+ * Team host assignment policy.
+ */
+export type SchedulingMode = 'individual' | 'collective' | 'roundRobin';
+/**
+ * User tools are pending until a user executes them
+ */
+export type UserToolResponseForBookingLinkResult =
+ | 'PendingUserExecution'
+ | 'Rejected'
+ | {
+ UserAction: BookingLinkResult;
+ };
/**
* The mutually exclusive time shape supplied to calendar tools.
*/
@@ -5137,6 +5150,192 @@ export interface SearchGotoAgentSession {
message_turn: number;
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. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+ */
+export interface CreateBookingLink {
+ /**
+ * Existing Macro team ID, or null for a personal booking link.
+ */
+ teamId?: string | null;
+ draft: BookingLinkDraft;
+}
+/**
+ * Complete proposal reviewed and validated before saving.
+ */
+export interface BookingLinkDraft {
+ event: BookingLinkEvent;
+ schedule: BookingLinkSchedule;
+}
+/**
+ * All editable rules for one link. Personal links must use the authenticated user as host.
+ */
+export interface BookingLinkEvent {
+ /**
+ * Public title.
+ */
+ title: string;
+ /**
+ * Unique link segment within a profile.
+ */
+ slug: string;
+ /**
+ * Public description.
+ */
+ description: string;
+ /**
+ * Meeting duration.
+ */
+ durationMinutes: number;
+ /**
+ * Meeting location.
+ */
+ location: string;
+ /**
+ * Generate a Google Meet conference.
+ */
+ googleMeet: boolean;
+ /**
+ * Whether new bookings are accepted.
+ */
+ enabled: boolean;
+ mode: SchedulingMode;
+ /**
+ * Current Macro user identities selected as hosts.
+ */
+ hosts: string[];
+ /**
+ * Protected time before a meeting.
+ */
+ beforeMinutes: number;
+ /**
+ * Protected time after a meeting.
+ */
+ afterMinutes: number;
+ /**
+ * Minimum notice in minutes.
+ */
+ noticeMinutes: number;
+ /**
+ * Maximum days ahead.
+ */
+ horizonDays: number;
+ /**
+ * Spacing of offered start times.
+ */
+ intervalMinutes: number;
+ /**
+ * Maximum bookings for this event on one schedule-local day.
+ */
+ dailyLimit?: number | null;
+ /**
+ * Hold bookings for host approval.
+ */
+ requiresConfirmation: boolean;
+ /**
+ * Additional form fields.
+ */
+ questions: Question[];
+}
+/**
+ * A question on the booking form.
+ */
+export interface Question {
+ /**
+ * Stable identity.
+ */
+ id: string;
+ /**
+ * Public question label.
+ */
+ label: string;
+ /**
+ * Whether an answer is mandatory.
+ */
+ required: boolean;
+}
+/**
+ * Availability copied into a dedicated schedule when it changes; other links retain their hours.
+ */
+export interface BookingLinkSchedule {
+ /**
+ * Display name.
+ */
+ name: string;
+ /**
+ * IANA time zone.
+ */
+ timeZone: string;
+ /**
+ * Weekly windows.
+ */
+ weekly: WeeklyDay[];
+ /**
+ * Date-specific replacements.
+ */
+ overrides: DateOverride[];
+}
+/**
+ * Availability for one weekday.
+ */
+export interface WeeklyDay {
+ /**
+ * Sunday is zero.
+ */
+ day: number;
+ /**
+ * Non-overlapping local windows.
+ */
+ windows: TimeWindow[];
+}
+/**
+ * A wall-clock window in an availability schedule.
+ */
+export interface TimeWindow {
+ /**
+ * Inclusive HH:MM start.
+ */
+ start: string;
+ /**
+ * Exclusive HH:MM end.
+ */
+ end: string;
+}
+/**
+ * Replacement availability for one date.
+ */
+export interface DateOverride {
+ /**
+ * Local date in the schedule zone.
+ */
+ date: string;
+ /**
+ * Empty means unavailable all day.
+ */
+ windows: TimeWindow[];
+}
+/**
+ * Saved link and shareable URL. Paused links remain discoverable but do not accept bookings.
+ */
+export interface BookingLinkResult {
+ /**
+ * Owning profile.
+ */
+ profileId: string;
+ /**
+ * Stable link identity.
+ */
+ eventTypeId: string;
+ /**
+ * Profile revision to supply when editing.
+ */
+ revision: number;
+ draft: BookingLinkDraft;
+ /**
+ * Link to share; enabled in the draft determines whether guests can book.
+ */
+ url: string;
+}
/**
* Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
*/
@@ -6172,6 +6371,24 @@ export interface DisplayResults {
export interface DisplayResultsResponse {
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 present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+ */
+export interface EditBookingLink {
+ /**
+ * Existing Macro team ID, or null for a personal booking link.
+ */
+ teamId?: string | null;
+ /**
+ * Existing link identity returned by ListBookingLinks.
+ */
+ eventTypeId: string;
+ /**
+ * Revision returned by ListBookingLinks; guards against concurrent settings changes.
+ */
+ expectedRevision: number;
+ draft: BookingLinkDraft;
+}
/**
* 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.
*/
@@ -7378,6 +7595,73 @@ 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.
+ */
+export interface ListBookingLinks {
+ /**
+ * Existing Macro team ID, or null for personal links.
+ */
+ teamId?: string | null;
+ /**
+ * Optional text to match in the link title, slug or description.
+ */
+ query?: string | null;
+}
+/**
+ * Authorized discovery results with shareable links.
+ */
+export interface ListBookingLinksResult {
+ /**
+ * Current team IDs; call ListBookingLinks again with one as teamId to read team links.
+ */
+ teamIds: string[];
+ /**
+ * Authenticated user's ID; use this host for a personal draft.
+ */
+ userId: string;
+ /**
+ * Personal or team profile identity.
+ */
+ profileId: string;
+ /**
+ * Current profile revision for editing.
+ */
+ revision: number;
+ /**
+ * Reusable availability to copy into a new draft.
+ */
+ schedules: Schedule[];
+ /**
+ * Matching links including their complete drafts.
+ */
+ links: BookingLinkResult[];
+}
+/**
+ * Reusable hours, with DST interpreted in an IANA zone.
+ */
+export interface Schedule {
+ /**
+ * Stable schedule identity.
+ */
+ id: string;
+ /**
+ * Display name.
+ */
+ name: string;
+ /**
+ * IANA time zone.
+ */
+ timeZone: string;
+ /**
+ * Weekly windows.
+ */
+ weekly: WeeklyDay[];
+ /**
+ * Date-specific replacements.
+ */
+ overrides: DateOverride[];
+}
/**
* List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot.
*/
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 96fbb2d613..345f9d7600 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -29,6 +29,7 @@ async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
bots = { path = "../bots", default-features = false, features = ["ai_tools", "outbound"] }
+calendar_scheduling = { path = "../calendar_scheduling", features = ["ai_tools", "postgres", "calendar"] }
calendar_events = { path = "../calendar_events", features = ["ai_tools", "mutation-client", "postgres"] }
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
@@ -119,4 +120,7 @@ macro_service_urls = { path = "../macro_service_urls" }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+calendar_scheduling = { path = "../calendar_scheduling", features = ["inbound"] }
+macro_authorization = { path = "../macro_authorization", features = ["axum"] }
+model_user = { path = "../model_user" }
cool_asserts = "2"
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index a29de8551c..e7179ed468 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -502,6 +502,10 @@ pub async fn build_tool_service_context_from_env(
email_tool_context,
call_tool_context,
calendar_tool_context,
+ booking_link_tool_context: crate::tool_context::build_booking_link_tool_context(
+ pool.clone(),
+ environment,
+ ),
notification_tool_context,
databases_tool_context,
databases_sql_tool_context,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index d5cba1cf94..8c56ae37d7 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -27,6 +27,9 @@ pub use anthropic::toolset::AnthropicToolContext;
use anthropic::toolset::anthropic_toolset;
use bots::inbound::toolset::bot_toolset;
use calendar_events::inbound::toolset::{calendar_toolset, mcp_toolset as calendar_mcp_toolset};
+use calendar_scheduling::inbound::toolset::{
+ booking_link_toolset, mcp_toolset as booking_link_mcp_toolset,
+};
use call::inbound::toolset::call_toolset;
use channels::inbound::toolset::channel_toolset;
use chat::inbound::toolset::chat_toolset;
@@ -63,30 +66,31 @@ pub use tool_context::{
ChannelSideEffectClients, MaybeToolEventBroker, NoOpCallRtcClient, NoOpConnectionService,
NoOpNotificationIngress, NoOpNotificationService, NoOpSnsEndpointManager, NoOpTaskProperties,
RequestContext, RoutineToolContext, TaskPropertiesAdapter, ToolActivityToolContext,
- ToolBotService, ToolBotToolContext, ToolCalendarMutationService, ToolCalendarReadService,
- ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,
- ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,
- ToolChatService, ToolChatToolContext, ToolCodingAgentToolContext, ToolCommsService,
- ToolCrmService, ToolCrmToolContext, ToolDatabasesService, ToolDatabasesSqlToolContext,
- ToolDatabasesToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,
- ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
- ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolGithubPullRequestService,
+ ToolBookingLinkService, ToolBookingLinkToolContext, ToolBotService, ToolBotToolContext,
+ ToolCalendarMutationService, ToolCalendarReadService, ToolCalendarToolContext,
+ ToolCallRecordQueryService, ToolCallService, ToolCallToolContext, ToolChannelEventDispatcher,
+ ToolChannelMessagesService, ToolChannelToolContext, ToolChatService, ToolChatToolContext,
+ ToolCodingAgentToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,
+ ToolDatabasesService, ToolDatabasesSqlToolContext, ToolDatabasesToolContext,
+ ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,
+ ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,
+ ToolForeignEntityService, ToolFrecencyService, ToolGithubPullRequestService,
ToolImageGenerationToolContext, ToolImportService, ToolImportToolContext,
ToolInitiativeToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,
ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,
ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolServiceContext,
ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,
ToolTableEventPublisher, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
- ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context, build_bot_tool_context,
- build_calendar_tool_context, build_channel_tool_context_with_dispatcher,
- build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
- build_coding_agent_tool_context, build_crm_tool_context, build_databases_sql_tool_context,
- build_databases_tool_context, build_image_generation_tool_context,
- build_initiative_tool_context, build_message_service_with_side_effects,
- build_message_service_without_side_effects, build_project_tool_context,
- build_properties_service, build_properties_service_with_broker, build_properties_tool_context,
- build_routine_tool_context, build_skill_tool_context, build_task_properties_adapter,
- build_team_repository, build_team_tool_context,
+ ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context,
+ build_booking_link_tool_context, build_bot_tool_context, build_calendar_tool_context,
+ build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,
+ build_channel_tool_context_without_side_effects, build_coding_agent_tool_context,
+ build_crm_tool_context, build_databases_sql_tool_context, build_databases_tool_context,
+ build_image_generation_tool_context, build_initiative_tool_context,
+ build_message_service_with_side_effects, build_message_service_without_side_effects,
+ build_project_tool_context, build_properties_service, build_properties_service_with_broker,
+ build_properties_tool_context, build_routine_tool_context, build_skill_tool_context,
+ build_task_properties_adapter, build_team_repository, build_team_tool_context,
};
#[cfg(any(test, feature = "test-support"))]
pub use tool_context::{build_image_generation_tool_context_test, no_op_schedule_context};
@@ -226,10 +230,12 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
let toolset = match host {
AiHost::Chat | AiHost::AgentSession => toolset
.add_subtoolset::<ToolEmailToolContext>(email_toolset())
- .add_subtoolset::<ToolCalendarToolContext>(calendar_toolset()),
+ .add_subtoolset::<ToolCalendarToolContext>(calendar_toolset())
+ .add_subtoolset::<ToolBookingLinkToolContext>(booking_link_toolset()),
AiHost::ChannelBot | AiHost::Mcp => toolset
.add_subtoolset::<ToolEmailToolContext>(email_mcp_toolset())
- .add_subtoolset::<ToolCalendarToolContext>(calendar_mcp_toolset()),
+ .add_subtoolset::<ToolCalendarToolContext>(calendar_mcp_toolset())
+ .add_subtoolset::<ToolBookingLinkToolContext>(booking_link_mcp_toolset()),
};
let toolset = toolset
.add_subtoolset::<ToolImportToolContext>(import_toolset())
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index f0708ea685..4240faa287 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -427,3 +427,23 @@ fn every_eager_tool_exists() {
);
}
}
+
+#[test]
+fn booking_link_mutations_only_defer_on_hosts_that_finish_reviews() {
+ for host in [
+ AiHost::Chat,
+ AiHost::AgentSession,
+ AiHost::ChannelBot,
+ AiHost::Mcp,
+ ] {
+ let tools = tools_for(host).toolset;
+ assert!(tools.tools.contains_key("ListBookingLinks"));
+ for name in ["CreateBookingLink", "EditBookingLink"] {
+ assert!(tools.tools.contains_key(name));
+ assert_eq!(
+ tools.user_tools.contains_key(name),
+ matches!(host, AiHost::Chat | AiHost::AgentSession)
+ );
+ }
+ }
+}
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 4475276c88..aea9e787df 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -467,6 +467,37 @@ pub fn build_calendar_tool_context(
)
}
+/// Settings-only scheduling service; no provider/calendar writes are exposed here.
+pub type ToolBookingLinkService = calendar_scheduling::domain::service::Service<
+ calendar_scheduling::outbound::postgres::PostgresRepository,
+ (),
+ calendar_scheduling::outbound::macro_services::MacroDirectory<ToolTeamService>,
+>;
+/// Booking-link tool dependencies.
+pub type ToolBookingLinkToolContext =
+ calendar_scheduling::inbound::toolset::BookingLinkToolContext<ToolBookingLinkService>;
+/// Construct scheduling adapters at the AI composition root.
+pub fn build_booking_link_tool_context(
+ pool: sqlx::PgPool,
+ environment: macro_env::Environment,
+) -> ToolBookingLinkToolContext {
+ calendar_scheduling::inbound::toolset::BookingLinkToolContext {
+ service: Arc::new(calendar_scheduling::domain::service::Service::new(
+ calendar_scheduling::outbound::postgres::PostgresRepository::new(pool.clone()),
+ (),
+ calendar_scheduling::outbound::macro_services::MacroDirectory(TeamRepositoryImpl::new(
+ pool,
+ )),
+ )),
+ public_origin: match environment {
+ macro_env::Environment::Production => "https://macro.com",
+ macro_env::Environment::Develop => "https://dev.macro.com",
+ macro_env::Environment::Local => "",
+ }
+ .into(),
+ }
+}
+
/// Type alias for the CRM AI tool context.
pub type ToolCrmToolContext =
CrmToolContext<ToolCrmService, ToolEntityAccessService, ToolPropertiesService>;
@@ -1558,6 +1589,7 @@ pub struct ToolServiceContext {
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
pub calendar_tool_context: ToolCalendarToolContext,
+ pub booking_link_tool_context: ToolBookingLinkToolContext,
pub notification_tool_context: ToolNotificationToolContext,
pub databases_tool_context: ToolDatabasesToolContext,
pub databases_sql_tool_context: ToolDatabasesSqlToolContext,
diff --git a/crates/ai_tools/src/user_tool_review/test.rs b/crates/ai_tools/src/user_tool_review/test.rs
index 01a40fa4f5..0878ca9f61 100644
--- a/crates/ai_tools/src/user_tool_review/test.rs
+++ b/crates/ai_tools/src/user_tool_review/test.rs
@@ -336,3 +336,5 @@ async fn a_tool_the_toolset_does_not_know_as_a_user_tool_is_left_alone() {
assert_eq!(finished, None);
assert!(reviewer.asked.lock().unwrap().is_empty());
}
+
+mod booking_links;
diff --git a/crates/ai_tools/src/user_tool_review/test/booking_links.rs b/crates/ai_tools/src/user_tool_review/test/booking_links.rs
new file mode 100644
index 0000000000..1cc1f0e2ba
--- /dev/null
+++ b/crates/ai_tools/src/user_tool_review/test/booking_links.rs
@@ -0,0 +1,274 @@
+//! Actual review -> edited tool execution -> PostgreSQL -> public booking HTTP API.
+use super::*;
+use ai_toolset::ToolSet;
+use calendar_scheduling::{
+ domain::{models::*, ports::*, service::Service},
+ inbound::{
+ router::{RouterState, router},
+ toolset::{BookingLinkToolContext, booking_link_toolset},
+ },
+ outbound::postgres::PostgresRepository,
+};
+use chrono::{DateTime, Duration, Utc};
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
+use model_user::UserContext;
+use rootcause::Report;
+use uuid::Uuid;
+
+#[derive(Clone)]
+struct NoAuth;
+impl MacroAuthorizationService for NoAuth {
+ async fn authorize(&self, _: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+ async fn authorize_internal(
+ &self,
+ _: &str,
+ _: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+struct Members;
+impl Directory for Members {
+ async fn user_teams(&self, _: &str) -> Result<Vec<Uuid>, Error> {
+ Ok(vec![])
+ }
+ async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
+ Ok(vec![])
+ }
+}
+struct FakeCalendar;
+impl Calendars for FakeCalendar {
+ async fn creation_calendar(&self, _: &str) -> Result<Uuid, Error> {
+ Ok(Uuid::now_v7())
+ }
+ async fn busy(
+ &self,
+ _: &[String],
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ _: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ Ok(vec![])
+ }
+ async fn create(&self, record: &BookingRecord, _: &EventType) -> Result<(Uuid, String), Error> {
+ Ok((record.booking.id, "Test room".into()))
+ }
+ async fn cancel(&self, _: &BookingRecord) -> Result<(), Error> {
+ Ok(())
+ }
+ async fn reschedule(&self, _: &BookingRecord) -> Result<(), Error> {
+ Ok(())
+ }
+}
+type Context = BookingLinkToolContext<Service<PostgresRepository, FakeCalendar, Members>>;
+
+fn args() -> Value {
+ json!({"teamId": null, "draft": {
+ "event": {"title":"Original", "slug":"intro", "description":"", "durationMinutes":30, "location":"Test room", "googleMeet":false, "enabled":true, "mode":"individual", "hosts":[owner().as_ref()], "beforeMinutes":0, "afterMinutes":0, "noticeMinutes":0, "horizonDays":30, "intervalMinutes":30, "dailyLimit":null, "requiresConfirmation":false, "questions":[]},
+ "schedule":{"name":"Working hours", "timeZone":"UTC", "weekly":(0..7).map(|day| json!({"day":day, "windows":[{"start":"09:00", "end":"17:00"}]})).collect::<Vec<_>>(), "overrides":[]}
+ }})
+}
+async fn review(
+ context: Context,
+ tool: &str,
+ args: Value,
+ outcome: ReviewOutcome,
+) -> FinishedUserTool {
+ let tools = Arc::new(booking_link_toolset());
+ let deferred = tools
+ .try_tool_call(context.clone(), RequestContext::new(owner()), tool, &args)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(deferred, json!("PendingUserExecution"));
+ let reviewer = Arc::new(Scripted {
+ asked: Mutex::new(vec![]),
+ answer: Ok(outcome),
+ });
+ user_tool_finisher(tools, context, owner(), reviewer, CancellationToken::new())(
+ PendingUserTool {
+ tool_name: tool.into(),
+ tool_call_id: "booking-link-call".into(),
+ args,
+ },
+ )
+ .await
+ .unwrap()
+}
+fn accept(args: Value) -> ReviewOutcome {
+ ReviewOutcome::Accepted(BTreeMap::from([(
+ DRAFT_FIELD.into(),
+ Value::String(args.to_string()),
+ )]))
+}
+fn saved(result: FinishedUserTool) -> Value {
+ let FinishedUserTool::Result(value) = result else {
+ panic!("expected saved link: {result:?}")
+ };
+ value["UserAction"].clone()
+}
+
+#[sqlx::test(migrations = false)]
+async fn edited_review_is_saved_and_bookable_without_touching_other_links(pool: sqlx::PgPool) {
+ sqlx::raw_sql("CREATE TABLE \"User\" (id text PRIMARY KEY); CREATE TABLE team (id uuid PRIMARY KEY); INSERT INTO \"User\" VALUES ('macro|[email protected]');").execute(&pool).await.unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918164303_calendar_scheduling.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918175703_scheduling_recovery.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ let service = Arc::new(Service::new(
+ PostgresRepository::new(pool),
+ FakeCalendar,
+ Members,
+ ));
+ let context = Context {
+ service: service.clone(),
+ public_origin: "https://booking.example.test".into(),
+ };
+ for outcome in [ReviewOutcome::Declined, ReviewOutcome::Cancelled] {
+ review(context.clone(), "CreateBookingLink", args(), outcome).await;
+ assert!(
+ service
+ .settings(owner().as_ref(), None)
+ .await
+ .unwrap()
+ .event_types
+ .is_empty()
+ );
+ }
+ let mut invalid = args();
+ invalid["draft"]["event"]["durationMinutes"] = json!(0);
+ assert!(matches!(
+ review(
+ context.clone(),
+ "CreateBookingLink",
+ args(),
+ accept(invalid)
+ )
+ .await,
+ FinishedUserTool::Error(_)
+ ));
+ assert!(
+ service
+ .settings(owner().as_ref(), None)
+ .await
+ .unwrap()
+ .event_types
+ .is_empty()
+ );
+ let mut edited = args();
+ edited["draft"]["event"]["title"] = json!("Reviewed title");
+ let first = saved(
+ review(
+ context.clone(),
+ "CreateBookingLink",
+ args(),
+ accept(edited.clone()),
+ )
+ .await,
+ );
+ assert_eq!(first["draft"]["event"]["title"], "Reviewed title");
+ let retry = saved(
+ review(
+ context.clone(),
+ "CreateBookingLink",
+ edited.clone(),
+ accept(edited.clone()),
+ )
+ .await,
+ );
+ assert_eq!(first, retry);
+ let mut other = args();
+ other["draft"]["event"]["slug"] = json!("other");
+ let second = saved(
+ review(
+ context.clone(),
+ "CreateBookingLink",
+ other.clone(),
+ accept(other),
+ )
+ .await,
+ );
+ let before = service.settings(owner().as_ref(), None).await.unwrap();
+ let edit = json!({"teamId":null, "eventTypeId":first["eventTypeId"], "expectedRevision":second["revision"], "draft":edited["draft"]});
+ let mut accepted = edit.clone();
+ accepted["draft"]["event"]["durationMinutes"] = json!(45);
+ let updated = saved(
+ review(
+ context.clone(),
+ "EditBookingLink",
+ edit.clone(),
+ accept(accepted),
+ )
+ .await,
+ );
+ assert_eq!(updated["eventTypeId"], first["eventTypeId"]);
+ let after = service.settings(owner().as_ref(), None).await.unwrap();
+ assert_eq!(before.event_types[1], after.event_types[1]);
+ assert!(matches!(
+ review(
+ context.clone(),
+ "EditBookingLink",
+ edit.clone(),
+ accept(edit)
+ )
+ .await,
+ FinishedUserTool::Error(_)
+ ));
+ let app: axum::Router = router(RouterState::new(
+ service.clone(),
+ MacroAuthorizationState::new(Arc::new(NoAuth)),
+ ));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let client = reqwest::Client::new();
+ let profile_id = first["profileId"].as_str().unwrap();
+ let event_id = first["eventTypeId"].as_str().unwrap();
+ assert_eq!(
+ first["url"],
+ format!("https://booking.example.test/app/book/{profile_id}/intro")
+ );
+ let public: Value = client
+ .get(format!("{base}/public/{profile_id}"))
+ .send()
+ .await
+ .unwrap()
+ .error_for_status()
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(public["profile"]["eventTypes"].as_array().unwrap().len(), 2);
+ let date = Utc::now().date_naive() + Duration::days(2);
+ let slots: Value = client
+ .get(format!(
+ "{base}/public/{profile_id}/{event_id}/slots?date={date}&time_zone=UTC"
+ ))
+ .send()
+ .await
+ .unwrap()
+ .error_for_status()
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ let start = &slots["slots"][0]["startsAt"];
+ assert!(start.is_string(), "{slots}");
+ let booking: Value = client.post(format!("{base}/public/{profile_id}/{event_id}/book")).json(&json!({"startsAt":start, "name":"QA guest", "email":"[email protected]", "timeZone":"UTC", "answers":{}, "requestId":Uuid::now_v7()})).send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
+ assert_eq!(booking["booking"]["title"], "Reviewed title");
+ assert_eq!(booking["booking"]["status"], "confirmed");
+ task.abort();
+}
diff --git a/crates/calendar_scheduling/Cargo.toml b/crates/calendar_scheduling/Cargo.toml
index e703069f76..ce8e36c322 100644
--- a/crates/calendar_scheduling/Cargo.toml
+++ b/crates/calendar_scheduling/Cargo.toml
@@ -6,11 +6,16 @@ publish = false
[features]
default = []
+ai_tools = ["dep:ai_toolset", "dep:async-trait", "dep:schemars", "dep:anyhow"]
postgres = ["dep:sqlx"]
inbound = ["dep:axum", "dep:macro_authorization"]
calendar = ["dep:calendar_events", "dep:teams", "dep:macro_user_id"]
[dependencies]
+ai_toolset = { path = "../ai_toolset", optional = true }
+async-trait = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
+anyhow = { workspace = true, optional = true }
email_validator = { path = "../email_validator" }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
chrono = { workspace = true }
diff --git a/crates/calendar_scheduling/README.md b/crates/calendar_scheduling/README.md
index bd2f0b98ed..70e6ef8e64 100644
--- a/crates/calendar_scheduling/README.md
+++ b/crates/calendar_scheduling/README.md
@@ -74,3 +74,23 @@ provider calendar invitations. Shared PostgreSQL budgets cap public availability
requests per profile; all booking changes use a monotonic revision to prevent stale edits.
See `docs/CALENDAR_SCHEDULING_V1.md` for rollout, rollback and monitoring queries.
It does not deploy the backend or apply migrations to shared databases.
+
+## AI booking-link workflows
+
+`ListBookingLinks` discovers personal links, current team IDs, reusable schedules and
+full editable drafts. Pass a returned team ID to discover that team's links. Both
+active and paused links include their shareable URL and profile revision.
+`CreateBookingLink` and `EditBookingLink` present one editable review in chat and
+agent sessions. The review reuses the normal booking options and availability
+controls; accepting executes the edited draft, while declining/cancelling does not
+write anything. Headless hosts register executable tools, not deferred user tools.
+
+The scheduling service owns authorization and validates the complete draft. Edits
+replace only the chosen event type; changed hours use a separate schedule to
+preserve other links and personal default availability. All writes retain the
+profile's compare-and-swap fence. An identical create at an existing slug or an
+identical edit is a no-op; a conflicting slug or stale edited revision fails and
+requires reading and reviewing the current state. Creation returns actual saved
+identities and URLs. Paused links cannot accept bookings, and creating a link never
+sends invitations. Guest booking still uses the normal calendar-readiness and
+availability checks. This workflow has no Forms dependencies.
diff --git a/crates/calendar_scheduling/src/domain.rs b/crates/calendar_scheduling/src/domain.rs
index 8a5c37bfc8..f242969a4b 100644
--- a/crates/calendar_scheduling/src/domain.rs
+++ b/crates/calendar_scheduling/src/domain.rs
@@ -5,3 +5,6 @@ pub mod ports;
pub mod service;
mod recovery;
+
+pub mod booking_link_models;
+pub mod booking_links;
diff --git a/crates/calendar_scheduling/src/domain/booking_link_models.rs b/crates/calendar_scheduling/src/domain/booking_link_models.rs
new file mode 100644
index 0000000000..374c974422
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/booking_link_models.rs
@@ -0,0 +1,171 @@
+//! Complete booking-link drafts, independent of transport and persisted identities.
+use super::models::*;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// All editable rules for one link. Personal links must use the authenticated user as host.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BookingLinkEvent {
+ /// Public title.
+ pub title: String,
+ /// Unique link segment within a profile.
+ pub slug: String,
+ /// Public description.
+ pub description: String,
+ /// Meeting duration.
+ pub duration_minutes: u16,
+ /// Meeting location.
+ pub location: String,
+ /// Generate a Google Meet conference.
+ pub google_meet: bool,
+ /// Whether new bookings are accepted.
+ pub enabled: bool,
+ /// Host assignment policy.
+ pub mode: SchedulingMode,
+ /// Current Macro user identities selected as hosts.
+ pub hosts: Vec<String>,
+ /// Protected time before a meeting.
+ pub before_minutes: u16,
+ /// Protected time after a meeting.
+ pub after_minutes: u16,
+ /// Minimum notice in minutes.
+ pub notice_minutes: u16,
+ /// Maximum days ahead.
+ pub horizon_days: u16,
+ /// Spacing of offered start times.
+ pub interval_minutes: u16,
+ /// Maximum bookings for this event on one schedule-local day.
+ pub daily_limit: Option<u16>,
+ /// Hold bookings for host approval.
+ pub requires_confirmation: bool,
+ /// Additional form fields.
+ pub questions: Vec<Question>,
+}
+
+/// Availability copied into a dedicated schedule when it changes; other links retain their hours.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BookingLinkSchedule {
+ /// Display name.
+ pub name: String,
+ /// IANA time zone.
+ #[cfg_attr(feature = "ai_tools", schemars(with = "String"))]
+ pub time_zone: chrono_tz::Tz,
+ /// Weekly windows.
+ pub weekly: Vec<WeeklyDay>,
+ /// Date-specific replacements.
+ pub overrides: Vec<DateOverride>,
+}
+
+/// Complete proposal reviewed and validated before saving.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BookingLinkDraft {
+ /// Public details, hosts, booking rules and questions.
+ pub event: BookingLinkEvent,
+ /// Weekly hours, IANA time zone, and date overrides for this link.
+ pub schedule: BookingLinkSchedule,
+}
+
+/// Saved link with actual identities and revision for subsequent edits.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BookingLink {
+ /// Owning profile.
+ pub profile_id: Uuid,
+ /// Stable link identity.
+ pub event_type_id: Uuid,
+ /// Profile revision to supply when editing.
+ pub revision: i64,
+ /// Full editable configuration.
+ pub draft: BookingLinkDraft,
+}
+
+/// Authorized discovery results including reusable availability.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BookingLinkListing {
+ /// Current team identities that can be used to discover team links.
+ pub team_ids: Vec<Uuid>,
+ /// Current authenticated host identity for personal drafts.
+ pub user_id: String,
+ /// Owning profile identity, including unsaved new profiles.
+ pub profile_id: Uuid,
+ /// Current revision.
+ pub revision: i64,
+ /// Reusable schedules, even when no links match.
+ pub schedules: Vec<Schedule>,
+ /// Links whose title, slug or description matches the search, including paused links.
+ pub links: Vec<BookingLink>,
+}
+
+impl BookingLinkDraft {
+ /// Extract a draft without persisted event or schedule identities.
+ pub fn from_parts(event: &EventType, schedule: &Schedule) -> Self {
+ Self {
+ event: BookingLinkEvent {
+ title: event.title.clone(),
+ slug: event.slug.clone(),
+ description: event.description.clone(),
+ duration_minutes: event.duration_minutes,
+ location: event.location.clone(),
+ google_meet: event.google_meet,
+ enabled: event.enabled,
+ mode: event.mode,
+ hosts: event.hosts.clone(),
+ before_minutes: event.before_minutes,
+ after_minutes: event.after_minutes,
+ notice_minutes: event.notice_minutes,
+ horizon_days: event.horizon_days,
+ interval_minutes: event.interval_minutes,
+ daily_limit: event.daily_limit,
+ requires_confirmation: event.requires_confirmation,
+ questions: event.questions.clone(),
+ },
+ schedule: BookingLinkSchedule {
+ name: schedule.name.clone(),
+ time_zone: schedule.time_zone,
+ weekly: schedule.weekly.clone(),
+ overrides: schedule.overrides.clone(),
+ },
+ }
+ }
+ pub(super) fn into_parts(self, event_id: Uuid, schedule_id: Uuid) -> (EventType, Schedule) {
+ (
+ EventType {
+ id: event_id,
+ schedule_id,
+ title: self.event.title,
+ slug: self.event.slug,
+ description: self.event.description,
+ duration_minutes: self.event.duration_minutes,
+ location: self.event.location,
+ google_meet: self.event.google_meet,
+ enabled: self.event.enabled,
+ mode: self.event.mode,
+ hosts: self.event.hosts,
+ before_minutes: self.event.before_minutes,
+ after_minutes: self.event.after_minutes,
+ notice_minutes: self.event.notice_minutes,
+ horizon_days: self.event.horizon_days,
+ interval_minutes: self.event.interval_minutes,
+ daily_limit: self.event.daily_limit,
+ requires_confirmation: self.event.requires_confirmation,
+ questions: self.event.questions,
+ },
+ Schedule {
+ id: schedule_id,
+ name: self.schedule.name,
+ time_zone: self.schedule.time_zone,
+ weekly: self.schedule.weekly,
+ overrides: self.schedule.overrides,
+ },
+ )
+ }
+}
diff --git a/crates/calendar_scheduling/src/domain/booking_links.rs b/crates/calendar_scheduling/src/domain/booking_links.rs
new file mode 100644
index 0000000000..14896e3278
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/booking_links.rs
@@ -0,0 +1,191 @@
+//! Single-link workflows. Authorization and validation stay in the scheduling service.
+pub use super::booking_link_models::*;
+use super::{
+ models::*,
+ ports::{Directory, Repository},
+ service::Service,
+};
+use std::future::Future;
+use uuid::Uuid;
+
+/// Workflows exposed to booking-link clients. Reads never create a profile.
+pub trait BookingLinks: Send + Sync + 'static {
+ /// Discover owned links and full editable drafts, optionally searching their public text.
+ fn list_links(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: Option<&str>,
+ ) -> impl Future<Output = Result<BookingLinkListing, Error>> + Send;
+ /// Create a link; replaying an identical slug and draft returns the existing link.
+ fn create_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ draft: BookingLinkDraft,
+ ) -> impl Future<Output = Result<BookingLink, Error>> + Send;
+ /// Edit exactly one link at the revision reviewed by the user. Identical retries are no-ops.
+ fn edit_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ event: Uuid,
+ revision: i64,
+ draft: BookingLinkDraft,
+ ) -> impl Future<Output = Result<BookingLink, Error>> + Send;
+}
+
+fn saved_link(profile: &Profile, event: &EventType) -> Result<BookingLink, Error> {
+ let schedule = profile
+ .schedules
+ .iter()
+ .find(|s| s.id == event.schedule_id)
+ .ok_or(Error::NotFound)?;
+ Ok(BookingLink {
+ profile_id: profile.id,
+ event_type_id: event.id,
+ revision: profile.revision,
+ draft: BookingLinkDraft::from_parts(event, schedule),
+ })
+}
+
+impl<Store: Repository, Calendar: Send + Sync + 'static, Members: Directory> BookingLinks
+ for Service<Store, Calendar, Members>
+{
+ async fn list_links(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: Option<&str>,
+ ) -> Result<BookingLinkListing, Error> {
+ let profile = self.settings(user, team).await?;
+ let query = query.unwrap_or_default().trim().to_lowercase();
+ let links = profile
+ .event_types
+ .iter()
+ .filter(|e| {
+ [&e.title, &e.slug, &e.description]
+ .iter()
+ .any(|text| text.to_lowercase().contains(&query))
+ })
+ .map(|event| saved_link(&profile, event))
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(BookingLinkListing {
+ team_ids: self.directory.user_teams(user).await?,
+ user_id: user.into(),
+ profile_id: profile.id,
+ revision: profile.revision,
+ schedules: profile.schedules,
+ links,
+ })
+ }
+
+ async fn create_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ draft: BookingLinkDraft,
+ ) -> Result<BookingLink, Error> {
+ let mut profile = self.settings(user, team).await?;
+ self.authorize_link_write(user, team, &profile).await?;
+ if let Some(event) = profile
+ .event_types
+ .iter()
+ .find(|e| e.slug == draft.event.slug)
+ {
+ let existing = saved_link(&profile, event)?;
+ return if existing.draft == draft {
+ Ok(existing)
+ } else {
+ Err(Error::Conflict)
+ };
+ }
+ let shared_schedule = profile
+ .schedules
+ .iter()
+ .find(|schedule| {
+ let (_, wanted) = draft.clone().into_parts(Uuid::nil(), schedule.id);
+ **schedule == wanted
+ })
+ .map(|schedule| schedule.id);
+ let (event, schedule) =
+ draft.into_parts(Uuid::now_v7(), shared_schedule.unwrap_or_else(Uuid::now_v7));
+ if shared_schedule.is_none() {
+ profile.schedules.push(schedule);
+ }
+ profile.event_types.push(event.clone());
+ let profile = self.save(user, team, profile).await?;
+ saved_link(&profile, &event)
+ }
+
+ async fn edit_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ event_id: Uuid,
+ revision: i64,
+ draft: BookingLinkDraft,
+ ) -> Result<BookingLink, Error> {
+ let mut profile = self.settings(user, team).await?;
+ self.authorize_link_write(user, team, &profile).await?;
+ let index = profile
+ .event_types
+ .iter()
+ .position(|e| e.id == event_id)
+ .ok_or(Error::NotFound)?;
+ let existing = saved_link(&profile, &profile.event_types[index])?;
+ if existing.draft == draft {
+ return Ok(existing);
+ }
+ if profile.revision != revision {
+ return Err(Error::Conflict);
+ }
+ let old_schedule_id = profile.event_types[index].schedule_id;
+ let schedule_changed = existing.draft.schedule != draft.schedule;
+ // Never mutate an existing schedule: it may be another link's availability or personal default.
+ let schedule_id = if schedule_changed {
+ Uuid::now_v7()
+ } else {
+ old_schedule_id
+ };
+ let (event, schedule) = draft.into_parts(event_id, schedule_id);
+ profile.event_types[index] = event.clone();
+ if schedule_changed {
+ profile.schedules.push(schedule);
+ // Remove only this link's now-unused schedule, preserving explicit and legacy personal defaults.
+ let default_id = profile
+ .default_schedule_id
+ .or_else(|| profile.schedules.first().map(|s| s.id));
+ if default_id != Some(old_schedule_id)
+ && !profile
+ .event_types
+ .iter()
+ .any(|e| e.schedule_id == old_schedule_id)
+ {
+ profile.schedules.retain(|s| s.id != old_schedule_id);
+ }
+ }
+ let profile = self.save(user, team, profile).await?;
+ saved_link(&profile, &event)
+ }
+}
+
+impl<Store: Repository, Calendar, Members: Directory> Service<Store, Calendar, Members> {
+ async fn authorize_link_write(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ profile: &Profile,
+ ) -> Result<(), Error> {
+ self.authorize(
+ user,
+ &OwnedProfile {
+ user_id: team.is_none().then(|| user.into()),
+ team_id: team,
+ profile: profile.clone(),
+ },
+ true,
+ )
+ .await
+ }
+}
diff --git a/crates/calendar_scheduling/src/domain/models.rs b/crates/calendar_scheduling/src/domain/models.rs
index 255380bb03..c5f049cb18 100644
--- a/crates/calendar_scheduling/src/domain/models.rs
+++ b/crates/calendar_scheduling/src/domain/models.rs
@@ -5,7 +5,8 @@ use std::collections::BTreeMap;
use uuid::Uuid;
/// A wall-clock window in an availability schedule.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TimeWindow {
/// Inclusive HH:MM start.
@@ -14,7 +15,8 @@ pub struct TimeWindow {
pub end: String,
}
/// Availability for one weekday.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct WeeklyDay {
/// Sunday is zero.
pub day: u8,
@@ -22,7 +24,8 @@ pub struct WeeklyDay {
pub windows: Vec<TimeWindow>,
}
/// Replacement availability for one date.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DateOverride {
/// Local date in the schedule zone.
pub date: NaiveDate,
@@ -30,7 +33,8 @@ pub struct DateOverride {
pub windows: Vec<TimeWindow>,
}
/// Reusable hours, with DST interpreted in an IANA zone.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Schedule {
/// Stable schedule identity.
@@ -38,6 +42,7 @@ pub struct Schedule {
/// Display name.
pub name: String,
/// IANA time zone.
+ #[cfg_attr(feature = "ai_tools", schemars(with = "String"))]
pub time_zone: chrono_tz::Tz,
/// Weekly windows.
pub weekly: Vec<WeeklyDay>,
@@ -45,6 +50,7 @@ pub struct Schedule {
pub overrides: Vec<DateOverride>,
}
/// Team host assignment policy.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SchedulingMode {
@@ -56,7 +62,8 @@ pub enum SchedulingMode {
RoundRobin,
}
/// A question on the booking form.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Question {
/// Stable identity.
pub id: Uuid,
@@ -66,7 +73,7 @@ pub struct Question {
pub required: bool,
}
/// A reusable booking link.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventType {
/// Stable identity.
@@ -109,7 +116,7 @@ pub struct EventType {
pub questions: Vec<Question>,
}
/// Editable configuration for a person or team.
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
/// Public, opaque profile identity.
diff --git a/crates/calendar_scheduling/src/domain/ports.rs b/crates/calendar_scheduling/src/domain/ports.rs
index bc2a13fd3b..6221b01737 100644
--- a/crates/calendar_scheduling/src/domain/ports.rs
+++ b/crates/calendar_scheduling/src/domain/ports.rs
@@ -103,6 +103,8 @@ pub trait Calendars: Send + Sync + 'static {
}
/// Membership facts supplied by Macro's teams domain.
pub trait Directory: Send + Sync + 'static {
+ /// Teams the authenticated user currently belongs to, for booking-link discovery.
+ fn user_teams(&self, user: &str) -> impl Future<Output = Result<Vec<Uuid>, Error>> + Send;
/// All current members, including the owner.
fn members(&self, team: Uuid) -> impl Future<Output = Result<Vec<TeamMember>, Error>> + Send;
}
diff --git a/crates/calendar_scheduling/src/domain/service.rs b/crates/calendar_scheduling/src/domain/service.rs
index 85c00d95e7..f35f718446 100644
--- a/crates/calendar_scheduling/src/domain/service.rs
+++ b/crates/calendar_scheduling/src/domain/service.rs
@@ -11,9 +11,9 @@ use uuid::Uuid;
pub struct Service<R, C, D> {
pub(super) repository: R,
pub(super) calendars: C,
- directory: D,
+ pub(super) directory: D,
}
-impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
+impl<R: Repository, C, D: Directory> Service<R, C, D> {
/// Construct the scheduling use-case service.
pub fn new(repository: R, calendars: C, directory: D) -> Self {
Self {
@@ -30,7 +30,12 @@ impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
);
Uuid::new_v5(&Uuid::NAMESPACE_URL, scope.as_bytes())
}
- async fn authorize(&self, user: &str, owner: &OwnedProfile, write: bool) -> Result<(), Error> {
+ pub(super) async fn authorize(
+ &self,
+ user: &str,
+ owner: &OwnedProfile,
+ write: bool,
+ ) -> Result<(), Error> {
if let Some(team) = owner.team_id {
if self
.directory
@@ -124,6 +129,8 @@ impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
}
Ok(())
}
+}
+impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
async fn validate_booking_hosts(
&self,
owner: &OwnedProfile,
diff --git a/crates/calendar_scheduling/src/domain/service/test.rs b/crates/calendar_scheduling/src/domain/service/test.rs
index fd3dfaaba5..aecc0c2a8c 100644
--- a/crates/calendar_scheduling/src/domain/service/test.rs
+++ b/crates/calendar_scheduling/src/domain/service/test.rs
@@ -247,6 +247,9 @@ impl Calendars for Arc<Calendar> {
}
struct Members;
impl Directory for Members {
+ async fn user_teams(&self, _: &str) -> Result<Vec<Uuid>, Error> {
+ Ok(vec![])
+ }
async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
Ok(vec![
TeamMember {
@@ -555,6 +558,9 @@ async fn visitor_time_zone_uses_the_visitors_local_date() {
async fn approval_rechecks_assigned_hosts_even_after_link_removal() {
struct ChangingMembers(Arc<Mutex<Vec<TeamMember>>>);
impl Directory for ChangingMembers {
+ async fn user_teams(&self, _: &str) -> Result<Vec<Uuid>, Error> {
+ Ok(vec![])
+ }
async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
Ok(self.0.lock().unwrap().clone())
}
@@ -1135,3 +1141,5 @@ async fn stale_team_events_can_be_repaired_one_at_a_time() {
Err(Error::Invalid(_))
));
}
+
+mod booking_links;
diff --git a/crates/calendar_scheduling/src/domain/service/test/booking_links.rs b/crates/calendar_scheduling/src/domain/service/test/booking_links.rs
new file mode 100644
index 0000000000..097c5b59af
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/service/test/booking_links.rs
@@ -0,0 +1,166 @@
+use super::*;
+use crate::domain::booking_links::{BookingLinkDraft, BookingLinks};
+
+const USER: &str = "macro|[email protected]";
+
+#[tokio::test]
+async fn discovery_is_read_only_and_finds_paused_links_by_public_text() {
+ let memory = Arc::new(Memory::default());
+ let service = TestService::new(memory.clone(), Arc::new(Calendar::default()), Members);
+ assert!(
+ service
+ .list_links(USER, None, None)
+ .await
+ .unwrap()
+ .links
+ .is_empty()
+ );
+ assert!(memory.profiles.lock().unwrap().is_empty());
+ let mut paused = draft();
+ paused.event.enabled = false;
+ paused.event.description = "Qualification conversation".into();
+ service.create_link(USER, None, paused).await.unwrap();
+ let matches = service
+ .list_links(USER, None, Some("QUALIFICATION"))
+ .await
+ .unwrap();
+ assert_eq!(matches.links.len(), 1);
+ assert!(!matches.links[0].draft.event.enabled);
+ assert!(
+ service
+ .public_profile(matches.profile_id)
+ .await
+ .unwrap()
+ .event_types
+ .is_empty()
+ );
+ assert!(
+ service
+ .list_links(USER, None, Some("no match"))
+ .await
+ .unwrap()
+ .links
+ .is_empty()
+ );
+ assert!(matches!(
+ service.list_links(USER, Some(Uuid::now_v7()), None).await,
+ Err(Error::Forbidden)
+ ));
+}
+
+fn draft() -> BookingLinkDraft {
+ let profile = profile(None);
+ let mut draft = BookingLinkDraft::from_parts(&profile.event_types[0], &profile.schedules[0]);
+ draft.event.hosts = vec![USER.into()];
+ draft
+}
+
+#[tokio::test]
+async fn link_is_retry_safe_and_usable_by_normal_booking_workflow() {
+ let memory = Arc::new(Memory::default());
+ let calendar = Arc::new(Calendar::default());
+ let service = TestService::new(memory, calendar.clone(), Members);
+ let link = service.create_link(USER, None, draft()).await.unwrap();
+ let retry = service.create_link(USER, None, draft()).await.unwrap();
+ assert_eq!(link.event_type_id, retry.event_type_id);
+ assert_eq!(link.revision, retry.revision);
+ assert_eq!(calendar.creates.load(Ordering::SeqCst), 0);
+ let public = service.public_profile(link.profile_id).await.unwrap();
+ assert_eq!(public.event_types[0].id, link.event_type_id);
+ let booking = service
+ .book(link.profile_id, link.event_type_id, request())
+ .await
+ .unwrap();
+ assert_eq!(booking.booking.status, BookingStatus::Confirmed);
+}
+
+#[tokio::test]
+async fn edit_preserves_other_links_hours_and_profile_and_rejects_stale_changes() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let first = service.create_link(USER, None, draft()).await.unwrap();
+ let mut second_draft = draft();
+ second_draft.event.slug = "second".into();
+ let second = service.create_link(USER, None, second_draft).await.unwrap();
+ let before = service.settings(USER, None).await.unwrap();
+ let mut edited = first.draft.clone();
+ edited.event.title = "Edited meeting".into();
+ edited.schedule.weekly[1].windows.clear();
+ let saved = service
+ .edit_link(
+ USER,
+ None,
+ first.event_type_id,
+ second.revision,
+ edited.clone(),
+ )
+ .await
+ .unwrap();
+ let after = service.settings(USER, None).await.unwrap();
+ assert_eq!(before.name, after.name);
+ assert_eq!(before.default_schedule_id, after.default_schedule_id);
+ assert_eq!(before.schedules[0], after.schedules[0]);
+ assert_eq!(before.event_types[1], after.event_types[1]);
+ assert_eq!(saved.draft, edited);
+ assert_eq!(
+ service
+ .edit_link(
+ USER,
+ None,
+ first.event_type_id,
+ second.revision,
+ edited.clone()
+ )
+ .await
+ .unwrap()
+ .revision,
+ saved.revision
+ );
+ edited.event.title = "Stale".into();
+ assert!(matches!(
+ service
+ .edit_link(USER, None, first.event_type_id, second.revision, edited)
+ .await,
+ Err(Error::Conflict)
+ ));
+ assert!(matches!(
+ service
+ .edit_link(
+ None,
+ first.event_type_id,
+ saved.revision,
+ draft()
+ )
+ .await,
+ Err(Error::NotFound)
+ ));
+}
+
+#[tokio::test]
+async fn invalid_drafts_and_team_non_admins_do_not_write() {
+ let memory = Arc::new(Memory::default());
+ let service = TestService::new(memory.clone(), Arc::new(Calendar::default()), Members);
+ let mut invalid = draft();
+ invalid.event.duration_minutes = 0;
+ assert!(matches!(
+ service.create_link(USER, None, invalid).await,
+ Err(Error::Invalid(_))
+ ));
+ let mut forged = draft();
+ forged.event.hosts = vec!["macro|[email protected]".into()];
+ assert!(matches!(
+ service.create_link(USER, None, forged).await,
+ Err(Error::Invalid(_))
+ ));
+ assert!(matches!(
+ service
+ .create_link("member", Some(Uuid::now_v7()), draft())
+ .await,
+ Err(Error::Forbidden)
+ ));
+ assert!(memory.profiles.lock().unwrap().is_empty());
+}
diff --git a/crates/calendar_scheduling/src/inbound.rs b/crates/calendar_scheduling/src/inbound.rs
index f1de119bd9..01fc5fa2b0 100644
--- a/crates/calendar_scheduling/src/inbound.rs
+++ b/crates/calendar_scheduling/src/inbound.rs
@@ -1,2 +1,5 @@
-//! HTTP adapters for scheduling use cases.
+//! Inbound scheduling adapters.
+#[cfg(feature = "inbound")]
pub mod router;
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/crates/calendar_scheduling/src/inbound/router/test.rs b/crates/calendar_scheduling/src/inbound/router/test.rs
index 817b8a12a4..c161ce3e6b 100644
--- a/crates/calendar_scheduling/src/inbound/router/test.rs
+++ b/crates/calendar_scheduling/src/inbound/router/test.rs
@@ -30,6 +30,9 @@ impl MacroAuthorizationService for Identity {
}
struct People;
impl Directory for People {
+ async fn user_teams(&self, _: &str) -> Result<Vec<Uuid>, Error> {
+ Ok(vec![])
+ }
async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
Ok(vec![
TeamMember {
diff --git a/crates/calendar_scheduling/src/inbound/toolset.rs b/crates/calendar_scheduling/src/inbound/toolset.rs
new file mode 100644
index 0000000000..9ced9bfb1f
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset.rs
@@ -0,0 +1,74 @@
+//! Workflow-oriented booking links, with deferred review only on hosts that can finish it.
+use crate::domain::{
+ booking_links::{BookingLink, BookingLinks},
+ models::Error,
+};
+use ai_toolset::{AsyncToolCollection, ToolCallError};
+use schemars::JsonSchema;
+use serde::Serialize;
+use std::sync::Arc;
+mod create_booking_link;
+mod edit_booking_link;
+mod list_booking_links;
+pub use create_booking_link::CreateBookingLink;
+pub use edit_booking_link::EditBookingLink;
+pub use list_booking_links::ListBookingLinks;
+
+/// Scheduling port and the application's public origin, supplied by the host.
+pub struct BookingLinkToolContext<Scheduling> {
+ /// Authorized domain workflow implementation.
+ pub service: Arc<Scheduling>,
+ /// Public application origin; empty for local relative URLs.
+ pub public_origin: String,
+}
+impl<Scheduling> Clone for BookingLinkToolContext<Scheduling> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ public_origin: self.public_origin.clone(),
+ }
+ }
+}
+/// Saved link and shareable URL. Paused links remain discoverable but do not accept bookings.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BookingLinkResult {
+ /// Actual saved identities, revision, and full configuration.
+ #[serde(flatten)]
+ pub link: BookingLink,
+ /// Link to share; enabled in the draft determines whether guests can book.
+ pub url: String,
+}
+impl<Scheduling> BookingLinkToolContext<Scheduling> {
+ fn result(&self, link: BookingLink) -> BookingLinkResult {
+ let url = format!(
+ "{}/app/book/{}/{}",
+ self.public_origin.trim_end_matches('/'),
+ link.profile_id,
+ link.draft.event.slug
+ );
+ BookingLinkResult { link, url }
+ }
+}
+fn tool_error(error: Error) -> ToolCallError {
+ ToolCallError {
+ description: error.to_string(),
+ internal_error: anyhow::Error::new(error),
+ }
+}
+/// Chat and agent-session tools: mutations await the user's actual review card.
+pub fn booking_link_toolset<Scheduling: BookingLinks>()
+-> AsyncToolCollection<BookingLinkToolContext<Scheduling>> {
+ AsyncToolCollection::new()
+ .add_tool::<ListBookingLinks, BookingLinkToolContext<Scheduling>>()
+ .add_user_tool::<CreateBookingLink, BookingLinkToolContext<Scheduling>>()
+ .add_user_tool::<EditBookingLink, BookingLinkToolContext<Scheduling>>()
+}
+/// Headless hosts execute real tools using their own confirmation policy, never a pending placeholder.
+pub fn mcp_toolset<Scheduling: BookingLinks>()
+-> AsyncToolCollection<BookingLinkToolContext<Scheduling>> {
+ AsyncToolCollection::new()
+ .add_tool::<ListBookingLinks, BookingLinkToolContext<Scheduling>>()
+ .add_tool::<CreateBookingLink, BookingLinkToolContext<Scheduling>>()
+ .add_tool::<EditBookingLink, BookingLinkToolContext<Scheduling>>()
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs
new file mode 100644
index 0000000000..cb64f8daf9
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs
@@ -0,0 +1,43 @@
+use super::*;
+use crate::domain::booking_links::BookingLinkDraft;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Create one booking link after user review.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[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. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
+)]
+pub struct CreateBookingLink {
+ /// Existing Macro team ID, or null for a personal booking link.
+ pub team_id: Option<Uuid>,
+ /// Full booking rules and availability for review. No other links are modified.
+ pub draft: BookingLinkDraft,
+}
+impl ToolAnnotated for CreateBookingLink {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::additive("Create booking link").with_idempotent();
+}
+#[async_trait]
+impl<Scheduling: BookingLinks> AsyncTool<BookingLinkToolContext<Scheduling>> for CreateBookingLink {
+ type Output = BookingLinkResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingLinkToolContext<Scheduling>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let context = context.0;
+ let link = context
+ .service
+ .create_link(request.user_id.as_ref(), self.team_id, self.draft.clone())
+ .await
+ .map_err(tool_error)?;
+ Ok(context.result(link))
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs
new file mode 100644
index 0000000000..b1d6f5d446
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs
@@ -0,0 +1,53 @@
+use super::*;
+use crate::domain::booking_links::BookingLinkDraft;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Edit one booking link after user review.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[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 present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
+)]
+pub struct EditBookingLink {
+ /// Existing Macro team ID, or null for a personal booking link.
+ pub team_id: Option<Uuid>,
+ /// Existing link identity returned by ListBookingLinks.
+ pub event_type_id: Uuid,
+ /// Revision returned by ListBookingLinks; guards against concurrent settings changes.
+ pub expected_revision: i64,
+ /// Full booking rules and availability for review. No other links are modified.
+ pub draft: BookingLinkDraft,
+}
+impl ToolAnnotated for EditBookingLink {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Edit booking link").with_idempotent();
+}
+#[async_trait]
+impl<Scheduling: BookingLinks> AsyncTool<BookingLinkToolContext<Scheduling>> for EditBookingLink {
+ type Output = BookingLinkResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingLinkToolContext<Scheduling>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let context = context.0;
+ let link = context
+ .service
+ .edit_link(
+ request.user_id.as_ref(),
+ self.team_id,
+ self.event_type_id,
+ self.expected_revision,
+ self.draft.clone(),
+ )
+ .await
+ .map_err(tool_error)?;
+ Ok(context.result(link))
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs b/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs
new file mode 100644
index 0000000000..519f438fb4
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/list_booking_links.rs
@@ -0,0 +1,74 @@
+use super::*;
+use crate::domain::models::Schedule;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Discover reusable links and everything needed to prepare an edit.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[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."
+)]
+pub struct ListBookingLinks {
+ /// Existing Macro team ID, or null for personal links.
+ pub team_id: Option<Uuid>,
+ /// Optional text to match in the link title, slug or description.
+ pub query: Option<String>,
+}
+/// Authorized discovery results with shareable links.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListBookingLinksResult {
+ /// Current team IDs; call ListBookingLinks again with one as teamId to read team links.
+ pub team_ids: Vec<Uuid>,
+ /// Authenticated user's ID; use this host for a personal draft.
+ pub user_id: String,
+ /// Personal or team profile identity.
+ pub profile_id: Uuid,
+ /// Current profile revision for editing.
+ pub revision: i64,
+ /// Reusable availability to copy into a new draft.
+ pub schedules: Vec<Schedule>,
+ /// Matching links including their complete drafts.
+ pub links: Vec<BookingLinkResult>,
+}
+impl ToolAnnotated for ListBookingLinks {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Find booking links");
+}
+#[async_trait]
+impl<Scheduling: BookingLinks> AsyncTool<BookingLinkToolContext<Scheduling>> for ListBookingLinks {
+ type Output = ListBookingLinksResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingLinkToolContext<Scheduling>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let context = context.0;
+ let result = context
+ .service
+ .list_links(
+ request.user_id.as_ref(),
+ self.team_id,
+ self.query.as_deref(),
+ )
+ .await
+ .map_err(tool_error)?;
+ Ok(ListBookingLinksResult {
+ team_ids: result.team_ids,
+ user_id: result.user_id,
+ profile_id: result.profile_id,
+ revision: result.revision,
+ schedules: result.schedules,
+ links: result
+ .links
+ .into_iter()
+ .map(|link| context.result(link))
+ .collect(),
+ })
+ }
+}
diff --git a/crates/calendar_scheduling/src/lib.rs b/crates/calendar_scheduling/src/lib.rs
index 40afb629e6..f76313fe53 100644
--- a/crates/calendar_scheduling/src/lib.rs
+++ b/crates/calendar_scheduling/src/lib.rs
@@ -1,7 +1,7 @@
//! Personal and team booking links, availability, and booking lifecycle.
#![deny(missing_docs)]
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
#[cfg(any(feature = "postgres", feature = "calendar"))]
pub mod outbound;
diff --git a/crates/calendar_scheduling/src/outbound/macro_services.rs b/crates/calendar_scheduling/src/outbound/macro_services.rs
index 34bbf85f2a..746a4c1acf 100644
--- a/crates/calendar_scheduling/src/outbound/macro_services.rs
+++ b/crates/calendar_scheduling/src/outbound/macro_services.rs
@@ -295,6 +295,14 @@ impl<O: CalendarOccurrenceService, M: CalendarCreationRecoveryService> Calendars
/// Membership adapter over the owning teams repository port.
pub struct MacroDirectory<T>(pub T);
impl<T: TeamRepository> Directory for MacroDirectory<T> {
+ async fn user_teams(&self, user: &str) -> Result<Vec<Uuid>, Error> {
+ let user = user.try_into().map_err(|_| Error::Forbidden)?;
+ self.0
+ .get_user_teams(&user)
+ .await
+ .map(|teams| teams.into_iter().map(|team| *team.id()).collect())
+ .map_err(|_| Error::Unavailable)
+ }
async fn members(&self, team: Uuid) -> Result<Vec<TeamMember>, Error> {
Ok(self
.0
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index fe56808b56..7792419125 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -1482,3 +1482,30 @@ To verify, start a Macro conversation as a free user with a previously saved
paid-model preference: the composer should show Gemini and send that model.
In a live session, confirm the model options contain only Gemini. Backend tests
also exercise direct ACP model-change requests, downgrade, and resume.
+
+## Booking links
+
+Ask the AI to find or reuse an existing booking link before creating another.
+`ListBookingLinks` returns personal links, current team IDs, full settings and
+shareable URLs (including paused links). It also supplies the revision used to
+protect edits from concurrent settings changes.
+
+`CreateBookingLink` and `EditBookingLink` open the same native booking review form
+in chat and in an agent session's elicitation. Edit title, slug, duration, location
+or Google Meet, enabled state, weekly hours, time zone, date overrides, buffers,
+notice, booking window, daily limit, questions and team hosts directly in the
+card. Create/Save accepts the complete edited draft; no extra confirmation is
+required. Cancel declines without saving. Link creation itself sends no calendar
+invitations. Guests receive an invitation only when they book through the normal
+booking page.
+
+A successful result shows the actual saved URL and whether the link accepts
+bookings. Editing hours affects only that link, preserving other links and personal
+default availability. If another settings edit made the revision stale, ask the AI
+to read the latest link and propose the edit again rather than retrying the stale
+revision. A network/save error preserves the review for retry; repeating an
+identical successful create or edit does not create another link.
+
+For isolated UI checks, `/src/features/scheduling/browser-test/booking-ai.html`
+mounts the actual review controls with the agent elicitation sink and no remote
+writes. It includes create/edit modes and simulated save failures.
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index ed002bf5f2..1b27f37319 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -472,6 +472,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ booking_link_tool_context: ai_tools::build_booking_link_tool_context(
+ pool.clone(),
+ macro_env::Environment::Local,
+ ),
calendar_tool_context: ai_tools::build_calendar_tool_context(
pool.clone(),
macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index f540ecbd51..f970aa05db 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -718,6 +718,10 @@ async fn main() -> anyhow::Result<()> {
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ booking_link_tool_context: ai_tools::build_booking_link_tool_context(
+ db.clone(),
+ config.environment,
+ ),
calendar_tool_context: ai_tools::build_calendar_tool_context(
db.clone(),
CalendarServiceUrl::new()?,
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 300bde3342..3e431c7671 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -448,6 +448,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
properties_tool_context,
email_tool_context,
call_tool_context,
+ booking_link_tool_context: ai_tools::build_booking_link_tool_context(
+ db.clone(),
+ config.environment,
+ ),
calendar_tool_context: ai_tools::build_calendar_tool_context(
db.clone(),
CalendarServiceUrl::new()?,