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(booking-links): clarify ownership and add MCP parity (#7915)

Jacob Beckerman5d49a8d73b92
diff --git a/Cargo.lock b/Cargo.lock
index 9042b51862..66c1128337 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1132,9 +1132,9 @@ checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
[[package]]
name = "ammonia"
-version = "4.1.4"
+version = "4.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc6d763210e2eb7670d1a5183a08bebefa3f97db2a738a684f2ce00bd49f681d"
+checksum = "36322ccf536de7b7afd259098615203e4cc5caca1b78482b58334a720c66e40a"
dependencies = [
"cssparser 0.37.0",
"html5ever 0.39.0",
diff --git a/Cargo.toml b/Cargo.toml
index 41f123e093..0d270c72b3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -438,7 +438,7 @@ strum_macros = "0.27.1"
unicode-segmentation = "1.9.0"
url = "2.5.0"
zip = "=2.4.2"
-ammonia = "4.1.4"
+ammonia = "4.1.7"
html-escape = "0.2"
subtle = "2.6.1"
diff --git a/apps/docs/AI/mcp/tools/change-booking.mdx b/apps/docs/AI/mcp/tools/change-booking.mdx
new file mode 100644
index 0000000000..76d09f2996
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/change-booking.mdx
@@ -0,0 +1,18 @@
+---
+title: ChangeBooking
+description: >-
+ Manage an existing Booking Links meeting found with ListBookings: cancel it,
+ approve a legacy pending booking, record or clear attendance, or reschedule to
+ a start returned by GetBookingRescheduleSlots.
+---
+
+# ChangeBooking
+
+Manage an existing Booking Links meeting found with ListBookings: cancel it, approve a legacy pending booking, record or clear attendance, or reschedule to a start returned by GetBookingRescheduleSlots. Cancellation, approval and rescheduling can notify attendees; explain the action and act only on user authorization. Attendance is available only after a confirmed meeting ends. Existing host/admin permissions and availability rules apply. Returns the actual saved booking; a failed or processing status requires reconciliation, not blind retries. This does not edit the reusable booking link.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `bookingId` | string | Yes | Existing booking ID discovered through ListBookings. |
+| `change` | BookingChange | Yes | A host's requested change to a booked meeting. |
diff --git a/apps/docs/AI/mcp/tools/get-booking-insights.mdx b/apps/docs/AI/mcp/tools/get-booking-insights.mdx
new file mode 100644
index 0000000000..64a820608d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/get-booking-insights.mdx
@@ -0,0 +1,17 @@
+---
+title: GetBookingInsights
+description: >-
+ Get the same Booking Links summary statistics and chart data as Insights, for
+ inclusive local dates in an IANA time zone (maximum 366 days).
+---
+
+# GetBookingInsights
+
+Get the same Booking Links summary statistics and chart data as Insights, for inclusive local dates in an IANA time zone (maximum 366 days). Returns current and equally long previous periods: total, completed, rescheduled, cancelled, host/guest no-shows, scheduled meeting minutes, average duration, daily trends, popular hours, and counts by link and host. Optional eventTypeId and hostId filters apply to both periods. Failed and processing requests are excluded. Completed means confirmed and ended without an explicit no-show, not verified attendance. Minutes are scheduled duration, not actual call duration. Rescheduled is counted once per booking. Dates use the booking current start. No guest contact information is returned.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing team ID, or null for personal insights. |
+| `query` | InsightQuery | Yes | Inclusive local dates and optional booking/host filters. |
diff --git a/apps/docs/AI/mcp/tools/get-booking-reschedule-slots.mdx b/apps/docs/AI/mcp/tools/get-booking-reschedule-slots.mdx
new file mode 100644
index 0000000000..44228d48b2
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/get-booking-reschedule-slots.mdx
@@ -0,0 +1,17 @@
+---
+title: GetBookingRescheduleSlots
+description: >-
+ Find available replacement times for a booking discovered through
+ ListBookings.
+---
+
+# GetBookingRescheduleSlots
+
+Find available replacement times for a booking discovered through ListBookings. The date is in the booking schedule time zone. Only the personal owner or team administrators may reschedule it. Returns absolute start/end times for ChangeBooking reschedule; availability is checked again when moving the meeting.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `bookingId` | string | Yes | Existing booking ID from ListBookings. |
+| `date` | string | Yes | Date in the booking schedule time zone. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 4a93fc6f7f..bfa9038eae 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -12,6 +12,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)
- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)
- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)
+- [ChangeBooking](/AI/mcp/tools/change-booking)
- [CommentOnDocument](/AI/mcp/tools/comment-on-document)
- [ConfigureAgent](/AI/mcp/tools/configure-agent)
- [ConfigureBot](/AI/mcp/tools/configure-bot)
@@ -46,6 +47,8 @@ These pages are generated from Macro's Rust MCP tool registry.
- [EditTag](/AI/mcp/tools/edit-tag)
- [EditWordDocument](/AI/mcp/tools/edit-word-document)
- [GenerateImage](/AI/mcp/tools/generate-image)
+- [GetBookingInsights](/AI/mcp/tools/get-booking-insights)
+- [GetBookingRescheduleSlots](/AI/mcp/tools/get-booking-reschedule-slots)
- [GetBotWebhooks](/AI/mcp/tools/get-bot-webhooks)
- [GetCompany](/AI/mcp/tools/get-company)
- [GetEntityProperties](/AI/mcp/tools/get-entity-properties)
@@ -55,6 +58,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)
- [ListAgents](/AI/mcp/tools/list-agents)
- [ListBookingLinks](/AI/mcp/tools/list-booking-links)
+- [ListBookings](/AI/mcp/tools/list-bookings)
- [ListBots](/AI/mcp/tools/list-bots)
- [ListCalendarEvents](/AI/mcp/tools/list-calendar-events)
- [ListCalendars](/AI/mcp/tools/list-calendars)
@@ -81,6 +85,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [NameSearch](/AI/mcp/tools/name-search)
- [QueryDatabase](/AI/mcp/tools/query-database)
- [ReadActivity](/AI/mcp/tools/read-activity)
+- [ReadBookingSettings](/AI/mcp/tools/read-booking-settings)
- [ReadCallRecord](/AI/mcp/tools/read-call-record)
- [ReadChannelMessageContext](/AI/mcp/tools/read-channel-message-context)
- [ReadChannelMessages](/AI/mcp/tools/read-channel-messages)
@@ -118,6 +123,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ShareWithChannel](/AI/mcp/tools/share-with-channel)
- [Subagent](/AI/mcp/tools/subagent)
- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)
+- [UpdateBookingSettings](/AI/mcp/tools/update-booking-settings)
- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)
- [UpdateInitiative](/AI/mcp/tools/update-initiative)
- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)
diff --git a/apps/docs/AI/mcp/tools/list-bookings.mdx b/apps/docs/AI/mcp/tools/list-bookings.mdx
new file mode 100644
index 0000000000..ccce461516
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/list-bookings.mdx
@@ -0,0 +1,18 @@
+---
+title: ListBookings
+description: >-
+ Read every booking starting in a half-open timestamp range for personal or
+ team Booking Links.
+---
+
+# ListBookings
+
+Read every booking starting in a half-open timestamp range for personal or team Booking Links. Returns IDs, status, hosts, guest details, answers, attendance and reschedule history; use these IDs to manage meetings. Both timestamps are required, with an explicit UTC offset. Maximum range 733 days. Oversized result sets fail rather than silently truncating: narrow the range. Use GetBookingInsights for aggregate statistics.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing team ID, or null for personal bookings. |
+| `from` | string | Yes | Inclusive start timestamp. |
+| `to` | string | Yes | Exclusive end timestamp. |
diff --git a/apps/docs/AI/mcp/tools/read-booking-settings.mdx b/apps/docs/AI/mcp/tools/read-booking-settings.mdx
new file mode 100644
index 0000000000..9da8700c2e
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/read-booking-settings.mdx
@@ -0,0 +1,17 @@
+---
+title: ReadBookingSettings
+description: >-
+ Read the full personal or team Booking Links configuration: booking-page name
+ and introduction, reusable schedules, default availability, and all link
+ settings with IDs and revision.
+---
+
+# ReadBookingSettings
+
+Read the full personal or team Booking Links configuration: booking-page name and introduction, reusable schedules, default availability, and all link settings with IDs and revision. Omit teamId for personal. Discover team IDs using ListBookingLinks. This read does not create a profile. Use the returned profile with UpdateBookingSettings to change shared availability or page settings.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing team ID from ListBookingLinks, or null for personal settings. |
diff --git a/apps/docs/AI/mcp/tools/update-booking-settings.mdx b/apps/docs/AI/mcp/tools/update-booking-settings.mdx
new file mode 100644
index 0000000000..5856bb61ca
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/update-booking-settings.mdx
@@ -0,0 +1,17 @@
+---
+title: UpdateBookingSettings
+description: >-
+ Update Booking Links settings after reading ReadBookingSettings.
+---
+
+# UpdateBookingSettings
+
+Update Booking Links settings after reading ReadBookingSettings. Pass the full profile with its current revision, preserving fields the user did not request changing. Supports booking-page name and introduction; adding, editing and deleting reusable schedules and date overrides; changing defaultScheduleId; reassigning link schedules; duplicating, deleting, enabling or pausing links. Generate new UUIDs for new schedules, links and questions; preserve existing IDs. Changing a shared schedule affects every link referencing it and personal default hours affect team hosting. Deleting a link does not cancel existing bookings. Explain affected links before changing shared hours or deleting. A stale revision fails: re-read and reconcile rather than overwriting. Use CreateBookingLink or EditBookingLink for ordinary single-link authoring and their conversational confirmation contract. Team edits require owner/admin access. Before saving, explain the proposed changes and their personal/team scope, ask whether to proceed, and wait for the user's approving reply in a later turn. Quote that reply verbatim in userConfirmation. Do not use the original request as confirmation.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `teamId` | string | No | Existing team ID from discovery, or null for personal settings. |
+| `profile` | Profile | Yes | Editable configuration for a person or team. |
+| `userConfirmation` | string | Yes | Verbatim user reply approving the proposed settings and affected links. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index d8ec46c906..964396ec17 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -3,6 +3,7 @@
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
+ "AI/mcp/tools/change-booking",
"AI/mcp/tools/comment-on-document",
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
@@ -37,6 +38,8 @@
"AI/mcp/tools/edit-tag",
"AI/mcp/tools/edit-word-document",
"AI/mcp/tools/generate-image",
+ "AI/mcp/tools/get-booking-insights",
+ "AI/mcp/tools/get-booking-reschedule-slots",
"AI/mcp/tools/get-bot-webhooks",
"AI/mcp/tools/get-company",
"AI/mcp/tools/get-entity-properties",
@@ -46,6 +49,7 @@
"AI/mcp/tools/issue-bot-credential",
"AI/mcp/tools/list-agents",
"AI/mcp/tools/list-booking-links",
+ "AI/mcp/tools/list-bookings",
"AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
@@ -72,6 +76,7 @@
"AI/mcp/tools/name-search",
"AI/mcp/tools/query-database",
"AI/mcp/tools/read-activity",
+ "AI/mcp/tools/read-booking-settings",
"AI/mcp/tools/read-call-record",
"AI/mcp/tools/read-channel-message-context",
"AI/mcp/tools/read-channel-messages",
@@ -109,6 +114,7 @@
"AI/mcp/tools/share-with-channel",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
+ "AI/mcp/tools/update-booking-settings",
"AI/mcp/tools/update-calendar-event",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 884601601a..e76377d72b 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -74,6 +74,7 @@
"AI/mcp/tools/bash-code-execution",
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
+ "AI/mcp/tools/change-booking",
"AI/mcp/tools/comment-on-document",
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
@@ -108,6 +109,8 @@
"AI/mcp/tools/edit-tag",
"AI/mcp/tools/edit-word-document",
"AI/mcp/tools/generate-image",
+ "AI/mcp/tools/get-booking-insights",
+ "AI/mcp/tools/get-booking-reschedule-slots",
"AI/mcp/tools/get-bot-webhooks",
"AI/mcp/tools/get-company",
"AI/mcp/tools/get-entity-properties",
@@ -117,6 +120,7 @@
"AI/mcp/tools/issue-bot-credential",
"AI/mcp/tools/list-agents",
"AI/mcp/tools/list-booking-links",
+ "AI/mcp/tools/list-bookings",
"AI/mcp/tools/list-bots",
"AI/mcp/tools/list-calendar-events",
"AI/mcp/tools/list-calendars",
@@ -143,6 +147,7 @@
"AI/mcp/tools/name-search",
"AI/mcp/tools/query-database",
"AI/mcp/tools/read-activity",
+ "AI/mcp/tools/read-booking-settings",
"AI/mcp/tools/read-call-record",
"AI/mcp/tools/read-channel-message-context",
"AI/mcp/tools/read-channel-messages",
@@ -180,6 +185,7 @@
"AI/mcp/tools/share-with-channel",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
+ "AI/mcp/tools/update-booking-settings",
"AI/mcp/tools/update-calendar-event",
"AI/mcp/tools/update-initiative",
"AI/mcp/tools/update-initiative-sharing",
diff --git a/apps/web/patches/@kobalte%[email protected] b/apps/web/patches/@kobalte%[email protected]
new file mode 100644
index 0000000000..3795f24e00
--- /dev/null
+++ b/apps/web/patches/@kobalte%[email protected]
@@ -0,0 +1,28 @@
+diff --git a/dist/index.cjs b/dist/index.cjs
+index 9b1289e66449ca7252cc4bd86922f8f400759460..b97bf015614c638adf4e0272e98db17577892f18 100644
+--- a/dist/index.cjs
++++ b/dist/index.cjs
+@@ -769,7 +769,8 @@ function scrollIntoViewport(targetElement, opts) {
+ targetElement
+ );
+ targetElement = scrollParent;
+- scrollParent = getScrollParent(targetElement);
++ // getScrollParent includes its argument; advance past the parent we just scrolled.
++ scrollParent = getScrollParent(targetElement.parentElement || root);
+ }
+ }
+ }
+diff --git a/dist/index.js b/dist/index.js
+index 503080597f7d15c7dce8f4a057c6faf6a3ad929f..90f9d8f7d7617f34ca323aa4ffe147731b4a651a 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -767,7 +767,8 @@ function scrollIntoViewport(targetElement, opts) {
+ targetElement
+ );
+ targetElement = scrollParent;
+- scrollParent = getScrollParent(targetElement);
++ // getScrollParent includes its argument; advance past the parent we just scrolled.
++ scrollParent = getScrollParent(targetElement.parentElement || root);
+ }
+ }
+ }
diff --git a/apps/web/src/components/ui/utils/scrollIntoViewport.test.ts b/apps/web/src/components/ui/utils/scrollIntoViewport.test.ts
new file mode 100644
index 0000000000..25535824d0
--- /dev/null
+++ b/apps/web/src/components/ui/utils/scrollIntoViewport.test.ts
@@ -0,0 +1,39 @@
+import { scrollIntoViewport } from '@kobalte/utils';
+import { expect, it, vi } from 'vitest';
+
+it('advances through nested scroll parents when the document cannot scroll', () => {
+ // Regression for the patched helper used when opening a menu by keyboard.
+ const overflow = document.documentElement.style.overflow;
+ const outer = document.createElement('div');
+ const inner = document.createElement('div');
+ const trigger = document.createElement('button');
+ outer.style.overflow = 'auto';
+ inner.style.overflow = 'auto';
+ inner.append(trigger);
+ outer.append(inner);
+ document.body.append(outer);
+ document.documentElement.style.overflow = 'hidden';
+ const outerScroll = vi.fn();
+ const innerScroll = vi.fn();
+ Object.defineProperty(outer, 'scrollTop', { get: () => 0, set: outerScroll });
+ Object.defineProperty(inner, 'scrollTop', { get: () => 0, set: innerScroll });
+ const getStyle = window.getComputedStyle.bind(window);
+ let visits = 0;
+ const style = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((node) => {
+ // Fail promptly instead of hanging the test process if the loop returns.
+ if (++visits > 20)
+ throw new Error('Scroll-parent traversal did not advance');
+ return getStyle(node);
+ });
+ try {
+ scrollIntoViewport(trigger);
+ expect(innerScroll).toHaveBeenCalledOnce();
+ expect(outerScroll).toHaveBeenCalledOnce();
+ } finally {
+ style.mockRestore();
+ document.documentElement.style.overflow = overflow;
+ outer.remove();
+ }
+});
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 11018f3e78..c15a8b259f 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
@@ -17,6 +17,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
BulkSetEntityPropertyOptions: (whose) =>
`change property options in ${whose} workspace`,
CalculateSpreadsheet: (whose) => `calculate in ${whose} spreadsheets`,
+ ChangeBooking: (whose) => `change a booking on ${whose} calendar`,
CommentOnDocument: (whose) => `comment on ${whose} documents`,
ConfigureAgent: (whose) => `change ${whose} agents`,
ConfigureBot: (whose) => `change ${whose} bots`,
@@ -50,6 +51,9 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
EditTag: (whose) => `edit tags in ${whose} workspace`,
EditWordDocument: (whose) => `edit ${whose} documents`,
GenerateImage: (whose) => `generate an image with ${whose} account`,
+ GetBookingInsights: (whose) => `read ${whose} booking statistics`,
+ GetBookingRescheduleSlots: (whose) =>
+ `check replacement times on ${whose} calendar`,
GetBotWebhooks: (whose) => `read ${whose} bot webhooks`,
GetCompany: (whose) => `look up companies in ${whose} workspace`,
GetEntityProperties: (whose) => `read properties in ${whose} workspace`,
@@ -58,6 +62,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`,
+ ListBookings: (whose) => `read ${whose} bookings`,
ListBookingLinks: (whose) => `read ${whose} booking links`,
ListBots: (whose) => `list ${whose} bots`,
ListCalendarEvents: (whose) => `read ${whose} calendar`,
@@ -86,6 +91,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
NameSearch: (whose) => `search ${whose} workspace`,
QueryDatabase: (whose) => `query ${whose} databases`,
ReadActivity: (whose) => `read ${whose} recent activity`,
+ ReadBookingSettings: (whose) => `read ${whose} booking settings`,
ReadCallRecord: (whose) => `read ${whose} call recordings`,
ReadChannelMessageContext: (whose) => `read ${whose} channel messages`,
ReadChannelMessages: (whose) => `read ${whose} channel messages`,
@@ -125,6 +131,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
`share an item from ${whose} account with a channel`,
Subagent: (whose) => `start a helper agent with ${whose} access`,
TextEditorCodeExecution: (whose) => `edit files with ${whose} access`,
+ UpdateBookingSettings: (whose) => `change ${whose} booking settings`,
UpdateCalendarEvent: (whose) => `change an event on ${whose} calendar`,
UpdateInitiative: (whose) => `change ${whose} initiatives`,
UpdateInitiativeSharing: (whose) => `change who can see ${whose} initiatives`,
diff --git a/apps/web/src/features/scheduling/components/availability-panel.tsx b/apps/web/src/features/scheduling/components/availability-panel.tsx
index ec0a3f6247..faeee32830 100644
--- a/apps/web/src/features/scheduling/components/availability-panel.tsx
+++ b/apps/web/src/features/scheduling/components/availability-panel.tsx
@@ -1,19 +1,12 @@
-import { SettingsCard } from '@app/features/settings/primitives';
import Clock from '@phosphor/clock.svg';
import Globe from '@phosphor/globe.svg';
import { Button } from '@ui';
import { createSignal, For, Show } from 'solid-js';
-import type {
- AvailabilitySchedule,
- SchedulingProfile,
- SchedulingScope,
-} from '../core/types';
+import type { AvailabilitySchedule, SchedulingProfile } from '../core/types';
import { WEEKDAYS } from '../core/types';
-import { OwnerBadge } from './owner-badge';
export function AvailabilityPanel(props: {
profile: SchedulingProfile;
- owner?: SchedulingScope;
canEdit: boolean;
saving: boolean;
onEdit: (schedule: AvailabilitySchedule) => void;
@@ -26,16 +19,13 @@ export function AvailabilityPanel(props: {
const usedBy = (id: string) =>
props.profile.eventTypes.filter((e) => e.scheduleId === id);
return (
- <SettingsCard>
+ <div class="divide-y divide-edge-muted border-y border-edge-muted">
<For
each={props.profile.schedules}
fallback={
<div class="flex flex-col items-center gap-3 px-6 py-8 text-center">
<Clock class="size-7 text-ink-muted" />
- <Show when={props.owner}>
- {(owner) => <OwnerBadge scope={owner()} />}
- </Show>
- <h2 class="font-semibold">Set your working hours</h2>
+ <h2 class="text-sm font-medium">Set your working hours</h2>
<p class="text-sm text-ink-muted">
Create a schedule to start accepting bookings.
</p>
@@ -43,7 +33,7 @@ export function AvailabilityPanel(props: {
}
>
{(schedule) => (
- <article class="px-6 py-4">
+ <article class="py-4">
<div class="flex flex-wrap items-start justify-between gap-5">
<button
type="button"
@@ -52,10 +42,7 @@ export function AvailabilityPanel(props: {
onClick={() => props.onEdit(schedule)}
>
<div class="flex flex-wrap items-center gap-3">
- <h2 class="font-semibold">{schedule.name}</h2>
- <Show when={props.owner}>
- {(owner) => <OwnerBadge scope={owner()} />}
- </Show>
+ <h2 class="text-sm font-medium">{schedule.name}</h2>
<Show when={defaultId() === schedule.id}>
<span class="rounded-md bg-active px-2 py-0.5 text-xs text-ink-muted">
Default
@@ -134,6 +121,6 @@ export function AvailabilityPanel(props: {
</article>
)}
</For>
- </SettingsCard>
+ </div>
);
}
diff --git a/apps/web/src/features/scheduling/components/event-types-panel.tsx b/apps/web/src/features/scheduling/components/event-types-panel.tsx
index b8e0af1192..97b62dcb28 100644
--- a/apps/web/src/features/scheduling/components/event-types-panel.tsx
+++ b/apps/web/src/features/scheduling/components/event-types-panel.tsx
@@ -1,4 +1,3 @@
-import { SettingsCard } from '@app/features/settings/primitives';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import External from '@phosphor/arrow-square-out.svg';
import Clock from '@phosphor/clock.svg';
@@ -9,7 +8,6 @@ import { Button, ToggleSwitch } from '@ui';
import { createSignal, For, Show } from 'solid-js';
import type { EventType, SchedulingScope } from '../core/types';
import { TextInput } from './fields';
-import { OwnerBadge } from './owner-badge';
export function EventTypesPanel(props: {
events: EventType[];
@@ -46,7 +44,7 @@ export function EventTypesPanel(props: {
/>
</div>
</Show>
- <SettingsCard>
+ <div class="divide-y divide-edge-muted border-y border-edge-muted">
<For
each={filtered()}
fallback={
@@ -66,9 +64,9 @@ export function EventTypesPanel(props: {
}
>
{(event) => (
- <article class="px-6 py-4">
- <div class="flex flex-wrap items-center gap-x-6 gap-y-4">
- <div class="min-w-48 flex-1">
+ <article class="py-4">
+ <div class="flex flex-wrap items-center gap-x-6 gap-y-3">
+ <div class="min-w-44 flex-1">
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
@@ -80,24 +78,16 @@ export function EventTypesPanel(props: {
{event.title}
</h2>
</button>
- <Show when={props.owner}>
- {(owner) => <OwnerBadge scope={owner()} />}
- </Show>
</div>
<p class="mt-1 truncate text-xs text-ink-muted">
/{event.slug}
</p>
- <Show when={event.description}>
- <p class="mt-2 line-clamp-1 text-sm text-ink-muted">
- {event.description}
- </p>
- </Show>
- <div class="mt-3 flex flex-wrap items-center gap-2 text-xs text-ink-muted">
- <span class="inline-flex items-center gap-1 rounded-md border border-edge-muted px-2 py-1">
+ <div class="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-muted">
+ <span class="inline-flex items-center gap-1">
<Clock class="size-3" />
{event.durationMinutes}m
</span>
- <span class="rounded-md border border-edge-muted px-2 py-1">
+ <span>
{event.mode === 'roundRobin'
? 'Round robin'
: event.mode === 'collective'
@@ -126,7 +116,7 @@ export function EventTypesPanel(props: {
/>
<a
aria-label={`Preview ${event.title}`}
- class="rounded-lg border border-edge-muted p-2 text-ink-muted hover:bg-hover"
+ class="rounded-md p-2 text-ink-muted outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink"
href={props.link(event)}
target="_blank"
rel="noopener noreferrer"
@@ -134,7 +124,7 @@ export function EventTypesPanel(props: {
<External class="size-4" />
</a>
<Button
- variant="outline"
+ variant="ghost"
size="icon-md"
label={`Copy link for ${event.title}`}
onClick={() => props.onCopy(event)}
@@ -146,7 +136,7 @@ export function EventTypesPanel(props: {
<DropdownMenu>
<DropdownMenu.Trigger
as={Button}
- variant="outline"
+ variant="ghost"
size="icon-md"
label={`Options for ${event.title}`}
>
@@ -201,7 +191,7 @@ export function EventTypesPanel(props: {
</article>
)}
</For>
- </SettingsCard>
+ </div>
</div>
);
}
diff --git a/apps/web/src/features/scheduling/components/insights-panel.tsx b/apps/web/src/features/scheduling/components/insights-panel.tsx
index 4bab8d58fd..0adf84fa80 100644
--- a/apps/web/src/features/scheduling/components/insights-panel.tsx
+++ b/apps/web/src/features/scheduling/components/insights-panel.tsx
@@ -48,10 +48,10 @@ function InsightSection(props: {
children: JSX.Element;
}) {
return (
- <section class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel">
- <header class="flex flex-wrap items-center justify-between gap-3 border-b border-edge-muted bg-surface-1 px-5 py-4">
+ <section class="min-w-0 overflow-hidden border-t border-edge-muted">
+ <header class="flex flex-wrap items-center justify-between gap-3 py-4">
<div>
- <h2 class="text-sm font-semibold">{props.title}</h2>
+ <h2 class="text-sm font-medium">{props.title}</h2>
<Show when={props.description}>
<p class="mt-1 text-xs text-ink-muted">{props.description}</p>
</Show>
@@ -77,7 +77,7 @@ function Metric(props: {
? props.value < props.previous
: props.value > props.previous);
return (
- <div class="flex min-w-0 flex-col gap-2 p-5">
+ <div class="flex min-w-0 flex-col gap-2 px-4 py-3">
<div class="flex items-center gap-1.5 text-sm text-ink-muted">
<span>{props.label}</span>
<Tooltip label={props.definition}>
@@ -90,7 +90,7 @@ function Metric(props: {
</button>
</Tooltip>
</div>
- <p class="text-3xl font-semibold tracking-tight tabular-nums">
+ <p class="text-2xl font-medium tracking-tight tabular-nums">
{Number.isInteger(props.value)
? props.value.toLocaleString()
: props.value.toLocaleString(undefined, { maximumFractionDigits: 1 })}
diff --git a/apps/web/src/features/scheduling/views/owner-settings-section.tsx b/apps/web/src/features/scheduling/views/owner-settings-section.tsx
index 7ba40e6ed1..7b86b8c239 100644
--- a/apps/web/src/features/scheduling/views/owner-settings-section.tsx
+++ b/apps/web/src/features/scheduling/views/owner-settings-section.tsx
@@ -161,7 +161,6 @@ export function OwnerSettingsSection(props: {
}
>
<AvailabilityPanel
- owner={scope()}
profile={p()}
canEdit={scope().canEdit}
saving={source.saving()}
@@ -199,7 +198,7 @@ export function OwnerSettingsSection(props: {
aria-label={`${scope().name} ${props.kind === 'page' ? 'booking page' : props.kind}`}
>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
- <OwnerBadge scope={scope()} />
+ <p class="text-sm text-ink-muted">Public booking page</p>
<div class="flex items-center gap-3">
<Show when={p().revision > 0}>
<a
@@ -224,8 +223,8 @@ export function OwnerSettingsSection(props: {
</Button>
</div>
</div>
- <div class="flex flex-col gap-4">
- <div class="flex flex-col gap-6 rounded-xl border border-edge-muted p-6">
+ <div class="grid items-start gap-8 @2xl:grid-cols-2">
+ <div class="flex flex-col gap-5">
<Field label="Display name">
<TextInput
disabled={!scope().canEdit}
@@ -267,7 +266,7 @@ export function OwnerSettingsSection(props: {
Save booking page
</Button>
</div>
- <aside class="rounded-xl border border-edge-muted p-6">
+ <aside class="rounded-lg border border-edge-muted p-5">
<p class="text-xs font-medium uppercase tracking-wide text-ink-muted">
Preview
</p>
@@ -300,9 +299,6 @@ export function OwnerSettingsSection(props: {
role="group"
aria-label={`${scope().name} ${props.kind === 'page' ? 'booking page' : props.kind}`}
>
- <div class="mb-4">
- <OwnerBadge scope={scope()} />
- </div>
<BookingsPanel
bookings={source.bookings()}
events={p().eventTypes}
@@ -333,9 +329,6 @@ export function OwnerSettingsSection(props: {
role="group"
aria-label={`${scope().name} ${props.kind === 'page' ? 'booking page' : props.kind}`}
>
- <div class="mb-4">
- <OwnerBadge scope={scope()} />
- </div>
<Show when={scope().id} keyed>
{(_scopeId) => (
<InsightsView
diff --git a/apps/web/src/features/scheduling/views/settings-view.test.tsx b/apps/web/src/features/scheduling/views/settings-view.test.tsx
index 075b6e4c3d..a8ddee69fd 100644
--- a/apps/web/src/features/scheduling/views/settings-view.test.tsx
+++ b/apps/web/src/features/scheduling/views/settings-view.test.tsx
@@ -114,49 +114,80 @@ function fixture(teamEditable = true) {
return { sources, saves };
}
-it('shows both owners and keeps link actions and editing within their owner', async () => {
+async function selectOwner(name: string) {
+ const trigger = screen.getByRole('button', { name: 'Booking link owner' });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'Enter' });
+ const item = await screen.findByRole('menuitem', { name });
+ item.focus();
+ fireEvent.keyDown(item, { key: 'Enter' });
+ await waitFor(() =>
+ expect(trigger.getAttribute('aria-expanded')).toBe('false')
+ );
+}
+
+it('scopes actions and creation to the selected owner', async () => {
const { sources, saves } = fixture();
- expect(screen.queryByLabelText('Calendar owner')).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'Personal catch-up' })
+ ).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Team planning' })).toBeNull();
+ await selectOwner('Team · Design');
const team = screen
.getByRole('button', { name: 'Team planning' })
.closest('article')!;
- const personal = screen
- .getByRole('button', { name: 'Personal catch-up' })
- .closest('article')!;
- expect(within(team).getByText('Team · Design')).toBeTruthy();
- expect(within(personal).getByText('Personal', { exact: true })).toBeTruthy();
expect(within(team).getByRole('link').getAttribute('href')).toBe(
'/book/team/meeting'
);
- expect(within(personal).getByRole('link').getAttribute('href')).toBe(
- '/book/personal/meeting'
- );
-
fireEvent.click(within(team).getByRole('switch'));
await waitFor(() => expect(saves).toHaveBeenCalledOnce());
expect(sources.get('team')!.profile()!.eventTypes[0].enabled).toBe(false);
expect(sources.get('personal')!.profile()!.eventTypes[0].enabled).toBe(true);
-
- const personalPageName = screen.getAllByRole('textbox', {
- name: 'Display name',
- })[0];
- fireEvent.input(personalPageName, { target: { value: 'Personal draft' } });
fireEvent.click(screen.getByRole('button', { name: 'Team planning' }));
fireEvent.click(screen.getByRole('button', { name: 'Save test event' }));
- await screen.findByRole('button', {
- name: 'Team planning edited',
- });
- expect(sources.get('personal')!.profile()!.eventTypes[0].title).toBe(
- 'Personal catch-up'
+ await screen.findByRole('button', { name: 'Team planning edited' });
+ fireEvent.click(screen.getByRole('button', { name: 'New booking link' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Save test event' }));
+ await waitFor(() =>
+ expect(sources.get('team')!.profile()!.eventTypes).toHaveLength(2)
);
- expect((personalPageName as HTMLInputElement).value).toBe('Personal draft');
+ expect(sources.get('personal')!.profile()!.eventTypes).toHaveLength(1);
+});
+
+it('keeps page drafts across navigation and scopes each section', async () => {
+ fixture();
+ fireEvent.click(screen.getByRole('tab', { name: 'Booking page' }));
+ fireEvent.input(screen.getByRole('textbox', { name: 'Display name' }), {
+ target: { value: 'Keep my draft' },
+ });
+ await selectOwner('Team · Design');
expect(
- screen.getByRole('button', { name: 'Personal catch-up' })
+ (screen.getByRole('textbox', { name: 'Display name' }) as HTMLInputElement)
+ .value
+ ).toBe('Design');
+ fireEvent.click(screen.getByRole('tab', { name: 'Availability' }));
+ expect(
+ screen.getByRole('group', { name: 'Design availability' })
).toBeTruthy();
+ expect(
+ screen.queryByRole('group', { name: 'Personal availability' })
+ ).toBeNull();
+ await selectOwner('Personal');
+ fireEvent.click(screen.getByRole('tab', { name: 'Booking page' }));
+ expect(
+ (screen.getByRole('textbox', { name: 'Display name' }) as HTMLInputElement)
+ .value
+ ).toBe('Keep my draft');
});
-it('searches all owners without switching other sections and preserves read-only team access', () => {
+it('preserves read-only access and clears search when switching owners', async () => {
fixture(false);
+ fireEvent.input(
+ screen.getByRole('searchbox', { name: 'Search booking links' }),
+ { target: { value: 'no match' } }
+ );
+ expect(screen.getByText('No matching booking links.')).toBeTruthy();
+ await selectOwner('Team · Design');
const team = screen
.getByRole('button', { name: 'Team planning' })
.closest('article')!;
@@ -164,44 +195,8 @@ it('searches all owners without switching other sections and preserves read-only
expect(
within(team).queryByRole('button', { name: 'Options for Team planning' })
).toBeNull();
- fireEvent.input(
- screen.getByRole('searchbox', { name: 'Search booking links' }),
- { target: { value: 'Design' } }
- );
- expect(
- screen.queryByRole('button', { name: 'Personal catch-up' })
- ).toBeNull();
- expect(screen.getByRole('button', { name: 'Team planning' })).toBeTruthy();
- expect(screen.getAllByRole('textbox', { name: 'Display name' })).toHaveLength(
- 2
- );
- fireEvent.click(screen.getByRole('button', { name: 'New booking link' }));
- expect(screen.getByRole('button', { name: 'Save test event' })).toBeTruthy();
- expect(screen.getByRole('button', { name: 'Team planning' })).toBeTruthy();
-});
-
-it('creates a link for the chosen owner without replacing other owners or their drafts', async () => {
- const { sources } = fixture();
- const personalPageName = screen.getAllByRole('textbox', {
- name: 'Display name',
- })[0];
- fireEvent.input(personalPageName, { target: { value: 'Keep this draft' } });
- fireEvent.keyDown(screen.getByRole('button', { name: 'New booking link' }), {
- key: 'Enter',
- });
- const teamOption = await screen.findByRole('menuitem', {
- name: 'Team · Design',
- });
- teamOption.focus();
- fireEvent.keyDown(teamOption, { key: 'Enter' });
- await screen.findByRole('button', { name: 'Save test event' });
+ expect(screen.queryByRole('button', { name: 'New booking link' })).toBeNull();
expect(
- screen.getByRole('button', { name: 'Personal catch-up' })
+ screen.getByText('Only team owners and admins can edit these settings.')
).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'Save test event' }));
- await waitFor(() =>
- expect(sources.get('team')!.profile()!.eventTypes).toHaveLength(2)
- );
- expect(sources.get('personal')!.profile()!.eventTypes).toHaveLength(1);
- expect((personalPageName as HTMLInputElement).value).toBe('Keep this draft');
});
diff --git a/apps/web/src/features/scheduling/views/settings-view.tsx b/apps/web/src/features/scheduling/views/settings-view.tsx
index 1485f84cae..42754aa03e 100644
--- a/apps/web/src/features/scheduling/views/settings-view.tsx
+++ b/apps/web/src/features/scheduling/views/settings-view.tsx
@@ -1,13 +1,22 @@
import {
SettingsButton as Button,
- SettingsCard,
- SettingsPage,
- SettingsRow,
- SettingsSection,
+ SettingsSheetContext,
} from '@app/features/settings/primitives';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
+import { Tabs } from '@kobalte/core/tabs';
+import CaretDown from '@phosphor/caret-down.svg';
+import Check from '@phosphor/check.svg';
import Plus from '@phosphor/plus.svg';
-import { createMemo, createSignal, For, mapArray, Show } from 'solid-js';
+import User from '@phosphor/user.svg';
+import Users from '@phosphor/users.svg';
+import {
+ createMemo,
+ createSignal,
+ For,
+ mapArray,
+ Show,
+ useContext,
+} from 'solid-js';
import { Field, TextInput } from '../components/fields';
import { OwnerBadge } from '../components/owner-badge';
import { useScheduling } from '../context/scheduling-context';
@@ -37,56 +46,26 @@ function CreateAction(props: {
else owner.createSchedule(trigger);
};
return (
- <Show when={editable().length > 0}>
- <Show
- when={editable().length > 1}
- fallback={
- <Button
- ref={trigger}
- variant="outline"
- size="sm"
- disabled={!editable()[0] || disabled(editable()[0])}
- onClick={() => create(editable()[0])}
- >
- <Plus class="size-4" />
- {label()}
- </Button>
- }
- >
- <DropdownMenu>
- <DropdownMenu.Trigger
- as={Button}
- ref={trigger}
- variant="outline"
- size="sm"
- >
- <Plus class="size-4" />
- {label()}
- </DropdownMenu.Trigger>
- <DropdownMenu.Portal>
- <DropdownMenu.Content class="menu-surface z-action-menu min-w-48 p-1 text-sm">
- <div class="px-3 py-2 text-xs text-ink-muted">Create for</div>
- <For each={editable()}>
- {(owner) => (
- <DropdownMenu.Item
- disabled={disabled(owner)}
- class="rounded-lg px-3 py-2 outline-none data-highlighted:bg-hover data-disabled:opacity-40"
- onSelect={() => create(owner)}
- >
- <OwnerBadge scope={owner.scope()} />
- </DropdownMenu.Item>
- )}
- </For>
- </DropdownMenu.Content>
- </DropdownMenu.Portal>
- </DropdownMenu>
- </Show>
+ <Show when={editable()[0]}>
+ {(owner) => (
+ <Button
+ ref={trigger}
+ variant="strong"
+ size="md"
+ disabled={disabled(owner())}
+ onClick={() => create(owner())}
+ >
+ <Plus class="size-4" />
+ {label()}
+ </Button>
+ )}
</Show>
);
}
export function SchedulingSettingsView() {
const capabilities = useScheduling();
+ const inSheet = useContext(SettingsSheetContext);
const browserZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const today = reportDate(new Date(), browserZone);
const [bookingFrom, setBookingFrom] = createSignal(
@@ -94,6 +73,13 @@ export function SchedulingSettingsView() {
);
const [bookingTo, setBookingTo] = createSignal(shiftReportDate(today, 30));
const [search, setSearch] = createSignal('');
+ const [selectedOwner, setSelectedOwner] = createSignal<string>();
+ const [sectionTab, setSectionTab] = createSignal('links');
+ const activeOwnerId = () =>
+ selectedOwner() &&
+ capabilities.scopes().some((s) => s.id === selectedOwner())
+ ? selectedOwner()
+ : capabilities.scopes()[0]?.id;
// Key by ID so profile updates and refreshed team metadata keep drafts mounted.
const owners = createMemo(
mapArray(
@@ -110,6 +96,8 @@ export function SchedulingSettingsView() {
}
)
);
+ const activeOwners = () =>
+ owners().filter((owner) => owner.scope().id === activeOwnerId());
const matching = (owner: SchedulingOwner) =>
owner.source
.profile()
@@ -121,184 +109,303 @@ export function SchedulingSettingsView() {
const section = (kind: 'availability' | 'page' | 'bookings' | 'insights') => (
<div class="flex flex-col gap-8">
<For each={owners()}>
- {(owner) => <OwnerSettingsSection kind={kind} owner={owner} />}
+ {(owner) => (
+ <div hidden={owner.scope().id !== activeOwnerId()}>
+ <Show
+ when={
+ owner.scope().id === activeOwnerId() ||
+ (kind === 'availability' && owner.schedule())
+ }
+ >
+ <OwnerSettingsSection kind={kind} owner={owner} />
+ </Show>
+ </div>
+ )}
</For>
</div>
);
return (
- <SettingsPage
- title="Booking links"
- description="Manage your booking links, availability, and scheduled meetings."
+ <div
+ data-settings-page
+ data-drawer-scroll-body={inSheet ? true : undefined}
+ class="@container/booking-settings h-full min-h-0 overflow-y-auto bg-panel text-ink select-children [overflow-anchor:none]"
>
- <For each={owners()}>
- {(owner) => (
- <>
- <Show when={owner.source.loading()}>
- <p role="status" class="text-sm text-ink-muted">
- Loading {owner.scope().name} scheduling…
- </p>
- </Show>
- <Show when={owner.source.error() || owner.error()}>
- <div
- role="alert"
- class="flex flex-wrap items-center gap-3 rounded-xl border border-edge-muted p-4"
- >
- <OwnerBadge scope={owner.scope()} />
- <p class="flex-1 text-sm text-failure">
- {owner.error() || owner.source.error()}
- </p>
- <Show when={owner.source.error()}>
- <Button
- variant="outline"
- size="sm"
- onClick={owner.source.reload}
- >
- Try again
- </Button>
- </Show>
- </div>
- </Show>
- <Show when={!owner.scope().canEdit}>
- <p class="flex flex-wrap items-center gap-2 text-sm text-ink-muted">
- <OwnerBadge scope={owner.scope()} />
- Only team owners and admins can edit these settings.
- </p>
- </Show>
- </>
- )}
- </For>
- <SettingsSection
- title="Booking links"
- description="Personal and team links, together in one place."
- actions={<CreateAction owners={owners()} kind="event" />}
+ <div
+ class="@container mx-auto w-full max-w-[960px] px-8 @max-[600px]/booking-settings:px-4"
+ classList={{
+ 'pt-8 pb-24 touch:pt-[calc(var(--mobile-content-inset-top,0px)+1rem)] touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+3rem)]':
+ !inSheet,
+ 'pt-2 pb-[max(24px,var(--mobile-sheet-safe-padding))]': inSheet,
+ }}
>
- <div class="max-w-sm">
- <TextInput
- type="search"
- aria-label="Search booking links"
- placeholder="Search booking links…"
- value={search()}
- onInput={(event) => setSearch(event.currentTarget.value)}
- />
- </div>
- <For each={owners()}>
- {(owner) => (
- <Show when={owner.event() || matching(owner)}>
- <OwnerSettingsSection
- kind="links"
- owner={owner}
- search={search()}
- />
- </Show>
- )}
- </For>
- <Show
- when={
- !owners().some((owner) => owner.event() || matching(owner)) &&
- !owners().some((owner) => owner.source.loading())
- }
+ <header
+ class="mb-5 flex flex-wrap items-center justify-between gap-3"
+ classList={{ 'justify-end': inSheet }}
>
- <p class="py-6 text-center text-sm text-ink-muted">
- {search()
- ? 'No matching booking links.'
- : 'Create your first booking link to let people book time with you.'}
- </p>
- </Show>
- </SettingsSection>
- <SettingsSection
- title="Availability"
- description="Working hours and date overrides for your personal and team calendars."
- actions={<CreateAction owners={owners()} kind="schedule" />}
- >
- {section('availability')}
- </SettingsSection>
- <SettingsSection
- title="Booking pages"
- description="Customize and share your personal and team booking pages."
- >
- {section('page')}
- </SettingsSection>
- <SettingsSection
- title="Teams"
- description="Schedule together with your Macro team."
- actions={
- <Button
- variant="outline"
- size="sm"
- onClick={capabilities.openTeamSettings}
- >
- Manage teams
- </Button>
- }
- >
- <SettingsCard>
- <For
- each={owners().filter((owner) => owner.scope().teamId)}
- fallback={
- <SettingsRow
- label="No team connected"
- description="Create or join a team to offer collective and round-robin meetings."
- />
- }
+ <Show when={!inSheet}>
+ <h1 class="text-xl font-medium tracking-tight">Booking links</h1>
+ </Show>
+ <DropdownMenu>
+ <DropdownMenu.Trigger
+ class="flex max-w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink"
+ aria-label="Booking link owner"
+ data-settings-target="teams"
+ aria-description={
+ activeOwners()[0]?.scope().teamId
+ ? `Team: ${activeOwners()[0]?.scope().name}`
+ : 'Personal'
+ }
+ >
+ <Show
+ when={activeOwners()[0]?.scope().teamId}
+ fallback={<User class="size-4 shrink-0 text-ink-muted" />}
+ >
+ <Users class="size-4 shrink-0 text-ink-muted" />
+ </Show>
+ <span class="min-w-0 break-words text-left">
+ {activeOwners()[0]?.scope().teamId
+ ? activeOwners()[0]?.scope().name
+ : 'Personal'}
+ </span>
+ <Show when={activeOwners()[0]?.scope().teamId}>
+ <span class="text-xs text-ink-muted">Team</span>
+ </Show>
+ <CaretDown class="size-3 shrink-0 text-ink-muted" />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content class="menu-surface z-action-menu min-w-56 max-w-80 p-1 text-sm">
+ <DropdownMenu.Group>
+ <DropdownMenu.GroupLabel class="px-2 py-1.5 text-xs text-ink-muted">
+ Manage booking links for
+ </DropdownMenu.GroupLabel>
+ <For each={owners()}>
+ {(owner) => (
+ <DropdownMenu.Item
+ class="flex items-center gap-2 rounded px-2 py-2 outline-none data-highlighted:bg-hover"
+ onSelect={() => {
+ setSelectedOwner(owner.scope().id);
+ setSearch('');
+ }}
+ >
+ <Show
+ when={owner.scope().teamId}
+ fallback={
+ <User class="size-4 shrink-0 text-ink-muted" />
+ }
+ >
+ <Users class="size-4 shrink-0 text-ink-muted" />
+ </Show>
+ <span class="min-w-0 flex-1 break-words">
+ {owner.scope().teamId
+ ? `Team · ${owner.scope().name}`
+ : 'Personal'}
+ </span>
+ <Show when={activeOwnerId() === owner.scope().id}>
+ <Check class="size-4" />
+ </Show>
+ </DropdownMenu.Item>
+ )}
+ </For>
+ </DropdownMenu.Group>
+ <DropdownMenu.Separator class="my-1 border-t border-edge-muted" />
+ <DropdownMenu.Item
+ class="rounded px-2 py-2 text-ink-muted outline-none data-highlighted:bg-hover"
+ onSelect={capabilities.openTeamSettings}
+ >
+ Manage teams
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu>
+ </header>
+ <Tabs value={sectionTab()} onChange={setSectionTab}>
+ <Tabs.List
+ aria-label="Booking link settings"
+ class="flex gap-6 overflow-x-auto border-b border-edge-muted"
>
+ <For
+ each={[
+ { value: 'links', label: 'Links', target: 'booking-links' },
+ {
+ value: 'availability',
+ label: 'Availability',
+ target: 'availability',
+ },
+ {
+ value: 'page',
+ label: 'Booking page',
+ target: 'booking-pages',
+ },
+ { value: 'bookings', label: 'Bookings', target: 'bookings' },
+ { value: 'insights', label: 'Insights', target: 'insights' },
+ ]}
+ >
+ {(tab) => (
+ <Tabs.Trigger
+ value={tab.value}
+ data-settings-target={tab.target}
+ class="shrink-0 border-b-2 border-transparent pt-1 pb-3 text-sm text-ink-muted outline-none data-selected:border-ink data-selected:text-ink focus-visible:ring-2 focus-visible:ring-ink"
+ >
+ {tab.label}
+ </Tabs.Trigger>
+ )}
+ </For>
+ </Tabs.List>
+ <For each={activeOwners()}>
{(owner) => (
- <SettingsRow
- label={owner.scope().name}
- description={
- owner.scope().canEdit
- ? 'Owner or admin · Collective and round-robin scheduling'
- : 'Team member'
- }
- />
+ <>
+ <Show when={owner.source.loading()}>
+ <p role="status" class="mt-4 text-sm text-ink-muted">
+ Loading {owner.scope().name} scheduling…
+ </p>
+ </Show>
+ <Show when={owner.source.error() || owner.error()}>
+ <div
+ role="alert"
+ class="flex flex-wrap items-center gap-3 rounded-xl border border-edge-muted p-4"
+ >
+ <OwnerBadge scope={owner.scope()} />
+ <p class="flex-1 text-sm text-failure">
+ {owner.error() || owner.source.error()}
+ </p>
+ <Show when={owner.source.error()}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={owner.source.reload}
+ >
+ Try again
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ <Show when={!owner.scope().canEdit}>
+ <p class="mt-4 flex flex-wrap items-center gap-2 text-sm text-ink-muted">
+ <OwnerBadge scope={owner.scope()} />
+ Only team owners and admins can edit these settings.
+ </p>
+ </Show>
+ </>
)}
</For>
- </SettingsCard>
- </SettingsSection>
- <SettingsSection
- title="Bookings"
- description="Review and manage meetings booked through your links."
- >
- <div class="flex flex-wrap items-end gap-4">
- <Field
- label="From"
- hint={`Dates in ${browserZone.replaceAll('_', ' ')}`}
+ <Tabs.Content
+ value="links"
+ class="pt-5"
+ forceMount={owners().some((owner) => !!owner.event())}
+ hidden={sectionTab() !== 'links'}
>
- <TextInput
- type="date"
- value={bookingFrom()}
- max={bookingTo()}
- onChange={(event) => {
- if (
- event.currentTarget.value &&
- event.currentTarget.value <= bookingTo()
- )
- setBookingFrom(event.currentTarget.value);
- }}
- />
- </Field>
- <Field label="Through">
- <TextInput
- type="date"
- value={bookingTo()}
- min={bookingFrom()}
- onChange={(event) => {
- if (
- event.currentTarget.value &&
- event.currentTarget.value >= bookingFrom()
- )
- setBookingTo(event.currentTarget.value);
- }}
- />
- </Field>
- </div>
- {section('bookings')}
- </SettingsSection>
- <SettingsSection
- title="Insights"
- description="See how your personal and team booking links are being used."
- >
- {section('insights')}
- </SettingsSection>
- </SettingsPage>
+ <section aria-label="Booking links">
+ <div class="mb-3 flex items-center justify-between gap-3">
+ <div class="min-w-0 max-w-64 flex-1">
+ <TextInput
+ type="search"
+ class="h-8"
+ aria-label="Search booking links"
+ placeholder="Search booking links…"
+ value={search()}
+ onInput={(event) => setSearch(event.currentTarget.value)}
+ />
+ </div>
+ <CreateAction owners={activeOwners()} kind="event" />
+ </div>
+ <For each={owners()}>
+ {(owner) => (
+ <div hidden={owner.scope().id !== activeOwnerId()}>
+ <Show
+ when={
+ owner.event() ||
+ (owner.scope().id === activeOwnerId() &&
+ matching(owner))
+ }
+ >
+ <OwnerSettingsSection
+ kind="links"
+ owner={owner}
+ search={search()}
+ />
+ </Show>
+ </div>
+ )}
+ </For>
+ <Show
+ when={
+ !activeOwners().some(
+ (owner) => owner.event() || matching(owner)
+ ) && !activeOwners().some((owner) => owner.source.loading())
+ }
+ >
+ <p class="py-6 text-center text-sm text-ink-muted">
+ {search()
+ ? 'No matching booking links.'
+ : 'Create your first booking link to let people book time with you.'}
+ </p>
+ </Show>
+ </section>
+ </Tabs.Content>
+ <Tabs.Content
+ value="availability"
+ class="pt-5"
+ forceMount={owners().some((owner) => !!owner.schedule())}
+ hidden={sectionTab() !== 'availability'}
+ >
+ <section aria-label="Availability">
+ <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
+ <p class="text-sm text-ink-muted">
+ {activeOwners()[0]?.scope().teamId
+ ? 'Team hours overlap with each host’s personal availability.'
+ : 'Your working hours, including meetings you host for a team.'}
+ </p>
+ <CreateAction owners={activeOwners()} kind="schedule" />
+ </div>
+ {section('availability')}
+ </section>
+ </Tabs.Content>
+ <Tabs.Content value="page" class="pt-5">
+ <section aria-label="Booking page">{section('page')}</section>
+ </Tabs.Content>
+ <Tabs.Content value="bookings" class="pt-5">
+ <section aria-label="Bookings" class="flex flex-col gap-5">
+ <div class="flex flex-wrap items-end gap-4">
+ <Field
+ label="From"
+ hint={`Dates in ${browserZone.replaceAll('_', ' ')}`}
+ >
+ <TextInput
+ type="date"
+ value={bookingFrom()}
+ max={bookingTo()}
+ onChange={(event) => {
+ if (
+ event.currentTarget.value &&
+ event.currentTarget.value <= bookingTo()
+ )
+ setBookingFrom(event.currentTarget.value);
+ }}
+ />
+ </Field>
+ <Field label="Through">
+ <TextInput
+ type="date"
+ value={bookingTo()}
+ min={bookingFrom()}
+ onChange={(event) => {
+ if (
+ event.currentTarget.value &&
+ event.currentTarget.value >= bookingFrom()
+ )
+ setBookingTo(event.currentTarget.value);
+ }}
+ />
+ </Field>
+ </div>
+ {section('bookings')}
+ </section>
+ </Tabs.Content>
+ <Tabs.Content value="insights" class="pt-5">
+ <section aria-label="Insights">{section('insights')}</section>
+ </Tabs.Content>
+ </Tabs>
+ </div>
+ </div>
);
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.test.tsx
new file mode 100644
index 0000000000..b1a803e662
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.test.tsx
@@ -0,0 +1,63 @@
+import {
+ deserializeToolCall,
+ deserializeToolResponse,
+} from '@service-cognition/generated/tools/tool';
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { afterEach, expect, it } from 'vitest';
+import { listBookingsHandler } from './BookingManagement';
+
+afterEach(cleanup);
+
+it('renders and expands an empty booking result instead of hiding it', () => {
+ const view = render(() => (
+ <listBookingsHandler.render
+ tool={{
+ id: 'list',
+ name: 'ListBookings',
+ data: { from: '2026-10-01T00:00:00Z', to: '2026-11-01T00:00:00Z' },
+ }}
+ response={{ id: 'list', name: 'ListBookings', data: { bookings: [] } }}
+ chat_id="chat"
+ message_id="message"
+ part_index={0}
+ isComplete
+ renderContext={{ isStreaming: false, followedBy: () => false }}
+ />
+ ));
+ expect(view.getByText('0 bookings')).toBeTruthy();
+ fireEvent.click(view.getByRole('button'));
+ expect(view.getByText(/"bookings": \[\]/)).toBeTruthy();
+});
+
+it('parses reporting filters and discriminated booking changes', () => {
+ expect(
+ deserializeToolCall({
+ id: 'report',
+ name: 'GetBookingInsights',
+ json: {
+ query: {
+ from: '2026-10-01',
+ to: '2026-10-31',
+ timeZone: 'America/New_York',
+ },
+ },
+ }).isOk()
+ ).toBe(true);
+ expect(
+ deserializeToolCall({
+ id: 'change',
+ name: 'ChangeBooking',
+ json: {
+ bookingId: crypto.randomUUID(),
+ change: { action: 'attendance', attendance: 'guestNoShow' },
+ },
+ }).isOk()
+ ).toBe(true);
+ expect(
+ deserializeToolResponse({
+ id: 'slots',
+ name: 'GetBookingRescheduleSlots',
+ json: { slots: [] },
+ }).isOk()
+ ).toBe(true);
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.tsx
new file mode 100644
index 0000000000..6abe739e14
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingManagement.tsx
@@ -0,0 +1,79 @@
+import Calendar from '@phosphor-icons/core/regular/calendar.svg';
+import { createSignal } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+type BookingManagementTool =
+ | 'ReadBookingSettings'
+ | 'UpdateBookingSettings'
+ | 'ListBookings'
+ | 'GetBookingInsights'
+ | 'GetBookingRescheduleSlots'
+ | 'ChangeBooking';
+
+function bookingManagementHandler(name: BookingManagementTool, label: string) {
+ return createToolRenderer({
+ name,
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const result = () => ctx.response?.data;
+ const status = () => {
+ const data = result();
+ if (data === undefined) return undefined;
+ if ('bookings' in data) return `${data.bookings.length} bookings`;
+ if ('slots' in data) return `${data.slots.length} times`;
+ if ('current' in data) return `${data.current.counts.total} events`;
+ if ('status' in data) return data.status;
+ return name === 'UpdateBookingSettings' ? 'Saved' : 'Loaded';
+ };
+ return (
+ <BaseTool
+ icon={Calendar}
+ type="call"
+ renderContext={ctx.renderContext}
+ response={
+ expanded() && result() !== undefined ? (
+ <pre class="max-h-96 overflow-auto whitespace-pre-wrap break-words p-3 text-xs">
+ {JSON.stringify(result(), null, 2)}
+ </pre>
+ ) : undefined
+ }
+ >
+ <span class="min-w-0 flex-1">{label}</span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={result() !== undefined}
+ status={status()}
+ />
+ </BaseTool>
+ );
+ },
+ });
+}
+
+export const readBookingSettingsHandler = bookingManagementHandler(
+ 'ReadBookingSettings',
+ 'Read booking settings'
+);
+export const updateBookingSettingsHandler = bookingManagementHandler(
+ 'UpdateBookingSettings',
+ 'Update booking settings'
+);
+export const listBookingsHandler = bookingManagementHandler(
+ 'ListBookings',
+ 'List bookings'
+);
+export const getBookingInsightsHandler = bookingManagementHandler(
+ 'GetBookingInsights',
+ 'Booking insights'
+);
+export const getBookingRescheduleSlotsHandler = bookingManagementHandler(
+ 'GetBookingRescheduleSlots',
+ 'Find replacement times'
+);
+export const changeBookingHandler = bookingManagementHandler(
+ 'ChangeBooking',
+ 'Change booking'
+);
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 a3f3deb569..d1ee0d1579 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
@@ -18,6 +18,14 @@ import {
editBookingLinkHandler,
listBookingLinksHandler,
} from './BookingLinks';
+import {
+ changeBookingHandler,
+ getBookingInsightsHandler,
+ getBookingRescheduleSlotsHandler,
+ listBookingsHandler,
+ readBookingSettingsHandler,
+ updateBookingSettingsHandler,
+} from './BookingManagement';
import {
configureBotHandler,
createBotHandler,
@@ -176,6 +184,12 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListBots: listBotsHandler,
ManageBotChannelAccess: manageBotChannelAccessHandler,
...lazyFormsToolHandlers,
+ ReadBookingSettings: readBookingSettingsHandler,
+ UpdateBookingSettings: updateBookingSettingsHandler,
+ ListBookings: listBookingsHandler,
+ GetBookingInsights: getBookingInsightsHandler,
+ GetBookingRescheduleSlots: getBookingRescheduleSlotsHandler,
+ ChangeBooking: changeBookingHandler,
ListBookingLinks: listBookingLinksHandler,
CreateBookingLink: createBookingLinkHandler,
EditBookingLink: editBookingLinkHandler,
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 a8606fbbc0..0471aecc30 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
@@ -616,6 +616,139 @@ export const SpreadsheetResponse = z.any().superRefine((x, ctx) => {
}
});
+export const ChangeBooking = z
+ .object({
+ bookingId: z.string().uuid(),
+ change: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ action: z.literal('approve') }).strict(),
+ z.object({ action: z.literal('cancel') }).strict(),
+ z
+ .object({
+ attendance: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('unknown'),
+ z.literal('attended'),
+ z.literal('guestNoShow'),
+ z.literal('hostNoShow'),
+ ];
+ 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',
+ });
+ }
+ }),
+ action: z.literal('attendance'),
+ })
+ .strict(),
+ z
+ .object({
+ startsAt: z.string().datetime({ offset: true }),
+ action: z.literal('reschedule'),
+ })
+ .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',
+ });
+ }
+ }),
+ })
+ .strict();
+
+export const Booking = z.object({
+ id: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ title: z.string(),
+ name: z.string(),
+ email: z.string(),
+ startsAt: z.string().datetime({ offset: true }),
+ endsAt: z.string().datetime({ offset: true }),
+ timeZone: z.string(),
+ hosts: z.array(z.string()),
+ status: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('pending'),
+ z.literal('confirmed'),
+ z.literal('cancelled'),
+ z.literal('processing'),
+ z.literal('failed'),
+ ];
+ 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',
+ });
+ }
+ }),
+ attendance: z
+ .intersection(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('unknown'),
+ z.literal('attended'),
+ z.literal('guestNoShow'),
+ z.literal('hostNoShow'),
+ ];
+ 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',
+ });
+ }
+ }),
+ z.any().default('unknown')
+ )
+ .optional(),
+ rescheduleCount: z.number().int().gte(0).lte(65535).optional(),
+ rescheduledAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ location: z.string(),
+ answers: z.record(z.string()),
+ questionLabels: z.record(z.string()).optional(),
+});
+
export const CommentOnDocument = z.object({
documentId: z.string().uuid(),
content: z.string(),
@@ -7805,6 +7938,90 @@ export const GenerateImageResponse = z.object({
note: z.union([z.string(), z.null()]).optional(),
});
+export const GetBookingInsights = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ query: z
+ .object({
+ from: z.string().date(),
+ to: z.string().date(),
+ timeZone: z.string(),
+ eventTypeId: z.union([z.string().uuid(), z.null()]).optional(),
+ hostId: z.union([z.string(), z.null()]).optional(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export const BookingInsights = z.object({
+ asOf: z.string().datetime({ offset: true }),
+ previousFrom: z.string().date(),
+ previousTo: z.string().date(),
+ current: z.object({
+ counts: z.object({
+ total: z.number().int().gte(0),
+ completed: z.number().int().gte(0),
+ rescheduled: z.number().int().gte(0),
+ cancelled: z.number().int().gte(0),
+ guestNoShow: z.number().int().gte(0),
+ hostNoShow: z.number().int().gte(0),
+ }),
+ meetingMinutes: z.number(),
+ averageMinutes: z.number(),
+ days: z.record(
+ z.object({
+ total: z.number().int().gte(0),
+ completed: z.number().int().gte(0),
+ rescheduled: z.number().int().gte(0),
+ cancelled: z.number().int().gte(0),
+ guestNoShow: z.number().int().gte(0),
+ hostNoShow: z.number().int().gte(0),
+ })
+ ),
+ hours: z.array(z.number().int().gte(0)),
+ eventCounts: z.record(z.number().int().gte(0)),
+ hostCounts: z.record(z.number().int().gte(0)),
+ }),
+ previous: z.object({
+ counts: z.object({
+ total: z.number().int().gte(0),
+ completed: z.number().int().gte(0),
+ rescheduled: z.number().int().gte(0),
+ cancelled: z.number().int().gte(0),
+ guestNoShow: z.number().int().gte(0),
+ hostNoShow: z.number().int().gte(0),
+ }),
+ meetingMinutes: z.number(),
+ averageMinutes: z.number(),
+ days: z.record(
+ z.object({
+ total: z.number().int().gte(0),
+ completed: z.number().int().gte(0),
+ rescheduled: z.number().int().gte(0),
+ cancelled: z.number().int().gte(0),
+ guestNoShow: z.number().int().gte(0),
+ hostNoShow: z.number().int().gte(0),
+ })
+ ),
+ hours: z.array(z.number().int().gte(0)),
+ eventCounts: z.record(z.number().int().gte(0)),
+ hostCounts: z.record(z.number().int().gte(0)),
+ }),
+});
+
+export const GetBookingRescheduleSlots = z
+ .object({ bookingId: z.string().uuid(), date: z.string().date() })
+ .strict();
+
+export const BookingSlotsResult = z.object({
+ slots: z.array(
+ z.object({
+ startsAt: z.string().datetime({ offset: true }),
+ endsAt: z.string().datetime({ offset: true }),
+ })
+ ),
+});
+
export const GetBotWebhooks = z.object({ botId: z.string().uuid() });
export const GetBotWebhooksResponse = z.object({
@@ -8332,6 +8549,90 @@ export const ListBookingLinksResult = z.object({
),
});
+export const ListBookings = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ from: z.string().datetime({ offset: true }),
+ to: z.string().datetime({ offset: true }),
+ })
+ .strict();
+
+export const BookingsResult = z.object({
+ bookings: z.array(
+ z.object({
+ id: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ title: z.string(),
+ name: z.string(),
+ email: z.string(),
+ startsAt: z.string().datetime({ offset: true }),
+ endsAt: z.string().datetime({ offset: true }),
+ timeZone: z.string(),
+ hosts: z.array(z.string()),
+ status: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('pending'),
+ z.literal('confirmed'),
+ z.literal('cancelled'),
+ z.literal('processing'),
+ z.literal('failed'),
+ ];
+ 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',
+ });
+ }
+ }),
+ attendance: z
+ .intersection(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('unknown'),
+ z.literal('attended'),
+ z.literal('guestNoShow'),
+ z.literal('hostNoShow'),
+ ];
+ 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',
+ });
+ }
+ }),
+ z.any().default('unknown')
+ )
+ .optional(),
+ rescheduleCount: z.number().int().gte(0).lte(65535).optional(),
+ rescheduledAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ location: z.string(),
+ answers: z.record(z.string()),
+ questionLabels: z.record(z.string()).optional(),
+ })
+ ),
+});
+
export const ListBots = z.record(z.any());
export const ListBotsResponse = z.object({
@@ -9949,6 +10250,92 @@ export const ReadActivityResponse = z.object({
truncated: z.boolean(),
});
+export const ReadBookingSettings = z
+ .object({ teamId: z.union([z.string().uuid(), z.null()]).optional() })
+ .strict();
+
+export const BookingSettingsResult = z.object({
+ profile: z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string(),
+ 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() })),
+ })
+ ),
+ })
+ ),
+ defaultScheduleId: z.union([z.string().uuid(), z.null()]).optional(),
+ eventTypes: z.array(
+ z.object({
+ id: z.string().uuid(),
+ 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(),
+ scheduleId: z.string().uuid(),
+ 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(),
+ })
+ ),
+ })
+ ),
+ revision: z.number().int(),
+ }),
+ pageUrl: z.string(),
+});
+
export const ReadCallRecord = z.object({ callId: z.string().uuid() });
export const ReadCallRecordResponse = z.object({
@@ -13430,6 +13817,96 @@ export const TextEditorCodeExecutionResponse = z.object({
}),
});
+export const UpdateBookingSettings = z
+ .object({
+ teamId: z.union([z.string().uuid(), z.null()]).optional(),
+ profile: z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string(),
+ 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() })
+ ),
+ })
+ ),
+ })
+ ),
+ defaultScheduleId: z.union([z.string().uuid(), z.null()]).optional(),
+ eventTypes: z.array(
+ z.object({
+ id: z.string().uuid(),
+ 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(),
+ scheduleId: z.string().uuid(),
+ 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(),
+ })
+ ),
+ })
+ ),
+ revision: z.number().int(),
+ }),
+ userConfirmation: z.string(),
+ })
+ .strict();
+
export const UpdateCalendarEvent = z.object({
eventId: z.string().uuid(),
calendarId: z.union([z.string().uuid(), z.null()]).optional(),
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 d0279a6e26..5245fcc41e 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
@@ -21,6 +21,7 @@ type ToolParserMap = {
call: types.CalculateSpreadsheet;
response: types.SpreadsheetResponse;
};
+ ChangeBooking: { call: types.ChangeBooking; response: types.Booking };
CommentOnDocument: {
call: types.CommentOnDocument;
response: types.CommentOnDocumentResponse;
@@ -133,6 +134,14 @@ type ToolParserMap = {
call: types.GenerateImage;
response: types.GenerateImageResponse;
};
+ GetBookingInsights: {
+ call: types.GetBookingInsights;
+ response: types.BookingInsights;
+ };
+ GetBookingRescheduleSlots: {
+ call: types.GetBookingRescheduleSlots;
+ response: types.BookingSlotsResult;
+ };
GetBotWebhooks: {
call: types.GetBotWebhooks;
response: types.GetBotWebhooksResponse;
@@ -160,6 +169,7 @@ type ToolParserMap = {
call: types.ListBookingLinks;
response: types.ListBookingLinksResult;
};
+ ListBookings: { call: types.ListBookings; response: types.BookingsResult };
ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
@@ -237,6 +247,10 @@ type ToolParserMap = {
call: types.ReadActivity;
response: types.ReadActivityResponse;
};
+ ReadBookingSettings: {
+ call: types.ReadBookingSettings;
+ response: types.BookingSettingsResult;
+ };
ReadCallRecord: {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
@@ -352,6 +366,10 @@ type ToolParserMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateBookingSettings: {
+ call: types.UpdateBookingSettings;
+ response: types.BookingSettingsResult;
+ };
UpdateCalendarEvent: {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
@@ -387,6 +405,7 @@ const toolParserMap = {
call: schemas.CalculateSpreadsheet,
response: schemas.SpreadsheetResponse,
},
+ ChangeBooking: { call: schemas.ChangeBooking, response: schemas.Booking },
CommentOnDocument: {
call: schemas.CommentOnDocument,
response: schemas.CommentOnDocumentResponse,
@@ -499,6 +518,14 @@ const toolParserMap = {
call: schemas.GenerateImage,
response: schemas.GenerateImageResponse,
},
+ GetBookingInsights: {
+ call: schemas.GetBookingInsights,
+ response: schemas.BookingInsights,
+ },
+ GetBookingRescheduleSlots: {
+ call: schemas.GetBookingRescheduleSlots,
+ response: schemas.BookingSlotsResult,
+ },
GetBotWebhooks: {
call: schemas.GetBotWebhooks,
response: schemas.GetBotWebhooksResponse,
@@ -532,6 +559,10 @@ const toolParserMap = {
call: schemas.ListBookingLinks,
response: schemas.ListBookingLinksResult,
},
+ ListBookings: {
+ call: schemas.ListBookings,
+ response: schemas.BookingsResult,
+ },
ListBots: { call: schemas.ListBots, response: schemas.ListBotsResponse },
ListCalendarEvents: {
call: schemas.ListCalendarEvents,
@@ -621,6 +652,10 @@ const toolParserMap = {
call: schemas.ReadActivity,
response: schemas.ReadActivityResponse,
},
+ ReadBookingSettings: {
+ call: schemas.ReadBookingSettings,
+ response: schemas.BookingSettingsResult,
+ },
ReadCallRecord: {
call: schemas.ReadCallRecord,
response: schemas.ReadCallRecordResponse,
@@ -751,6 +786,10 @@ const toolParserMap = {
call: schemas.TextEditorCodeExecution,
response: schemas.TextEditorCodeExecutionResponse,
},
+ UpdateBookingSettings: {
+ call: schemas.UpdateBookingSettings,
+ response: schemas.BookingSettingsResult,
+ },
UpdateCalendarEvent: {
call: schemas.UpdateCalendarEvent,
response: schemas.ToolCalendarEvent,
@@ -797,6 +836,7 @@ type ToolDataMap = {
call: types.CalculateSpreadsheet;
response: types.SpreadsheetResponse;
};
+ ChangeBooking: { call: types.ChangeBooking; response: types.Booking };
CommentOnDocument: {
call: types.CommentOnDocument;
response: types.CommentOnDocumentResponse;
@@ -909,6 +949,14 @@ type ToolDataMap = {
call: types.GenerateImage;
response: types.GenerateImageResponse;
};
+ GetBookingInsights: {
+ call: types.GetBookingInsights;
+ response: types.BookingInsights;
+ };
+ GetBookingRescheduleSlots: {
+ call: types.GetBookingRescheduleSlots;
+ response: types.BookingSlotsResult;
+ };
GetBotWebhooks: {
call: types.GetBotWebhooks;
response: types.GetBotWebhooksResponse;
@@ -936,6 +984,7 @@ type ToolDataMap = {
call: types.ListBookingLinks;
response: types.ListBookingLinksResult;
};
+ ListBookings: { call: types.ListBookings; response: types.BookingsResult };
ListBots: { call: types.ListBots; response: types.ListBotsResponse };
ListCalendarEvents: {
call: types.ListCalendarEvents;
@@ -1013,6 +1062,10 @@ type ToolDataMap = {
call: types.ReadActivity;
response: types.ReadActivityResponse;
};
+ ReadBookingSettings: {
+ call: types.ReadBookingSettings;
+ response: types.BookingSettingsResult;
+ };
ReadCallRecord: {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
@@ -1128,6 +1181,10 @@ type ToolDataMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateBookingSettings: {
+ call: types.UpdateBookingSettings;
+ response: types.BookingSettingsResult;
+ };
UpdateCalendarEvent: {
call: types.UpdateCalendarEvent;
response: types.ToolCalendarEvent;
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 00a443f33d..436d5b23ed 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
@@ -156,6 +156,44 @@ export type SpreadsheetValueKind =
| 'text'
| 'boolean'
| 'error';
+/**
+ * A host's requested change to a booked meeting.
+ */
+export type BookingChange =
+ | {
+ action: 'approve';
+ }
+ | {
+ action: 'cancel';
+ }
+ | {
+ attendance: BookingAttendance;
+ action: 'attendance';
+ }
+ | {
+ /**
+ * Absolute start chosen from available replacement slots.
+ */
+ startsAt: string;
+ action: 'reschedule';
+ };
+/**
+ * Attendance recorded by an assigned host or profile administrator after a meeting.
+ */
+export type BookingAttendance =
+ | 'unknown'
+ | 'attended'
+ | 'guestNoShow'
+ | 'hostNoShow';
+/**
+ * Booking lifecycle state.
+ */
+export type BookingStatus =
+ | 'pending'
+ | 'confirmed'
+ | 'cancelled'
+ | 'processing'
+ | 'failed';
/**
* The runtimes an agent can be moved onto.
*/
@@ -4963,6 +5001,83 @@ export interface SpreadsheetChange {
*/
range?: string | null;
}
+/**
+ * Manage an existing Booking Links meeting found with ListBookings: cancel it, approve a legacy pending booking, record or clear attendance, or reschedule to a start returned by GetBookingRescheduleSlots. Cancellation, approval and rescheduling can notify attendees; explain the action and act only on user authorization. Attendance is available only after a confirmed meeting ends. Existing host/admin permissions and availability rules apply. Returns the actual saved booking; a failed or processing status requires reconciliation, not blind retries. This does not edit the reusable booking link.
+ */
+export interface ChangeBooking {
+ /**
+ * Existing booking ID discovered through ListBookings.
+ */
+ bookingId: string;
+ change: BookingChange;
+}
+/**
+ * Public booking details, also visible to authorized profile members.
+ */
+export interface Booking {
+ /**
+ * Booking identity.
+ */
+ id: string;
+ /**
+ * Booking link identity.
+ */
+ eventTypeId: string;
+ /**
+ * Snapshot of the meeting title.
+ */
+ title: string;
+ /**
+ * Booker's name.
+ */
+ name: string;
+ /**
+ * Booker's email.
+ */
+ email: string;
+ /**
+ * Absolute meeting start.
+ */
+ startsAt: string;
+ /**
+ * Absolute meeting end.
+ */
+ endsAt: string;
+ /**
+ * Booker's display time zone.
+ */
+ timeZone: string;
+ /**
+ * Assigned hosts.
+ */
+ hosts: string[];
+ status: BookingStatus;
+ attendance?: BookingAttendance & string;
+ /**
+ * Number of successfully completed moves to a different start time.
+ */
+ rescheduleCount?: number;
+ /**
+ * When the most recent successful reschedule completed.
+ */
+ rescheduledAt?: string | null;
+ /**
+ * Final location or conference URL.
+ */
+ location: string;
+ /**
+ * Answers keyed by question identity.
+ */
+ answers: {
+ [k: string]: string;
+ };
+ /**
+ * Original labels for answers, independent of later event-type edits.
+ */
+ questionLabels?: {
+ [k: string]: string;
+ };
+}
/**
* Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead.
*/
@@ -8347,6 +8462,160 @@ export interface GenerateImageResponse {
*/
note?: string | null;
}
+/**
+ * Get the same Booking Links summary statistics and chart data as Insights, for inclusive local dates in an IANA time zone (maximum 366 days). Returns current and equally long previous periods: total, completed, rescheduled, cancelled, host/guest no-shows, scheduled meeting minutes, average duration, daily trends, popular hours, and counts by link and host. Optional eventTypeId and hostId filters apply to both periods. Failed and processing requests are excluded. Completed means confirmed and ended without an explicit no-show, not verified attendance. Minutes are scheduled duration, not actual call duration. Rescheduled is counted once per booking. Dates use the booking current start. No guest contact information is returned.
+ */
+export interface GetBookingInsights {
+ /**
+ * Existing team ID, or null for personal insights.
+ */
+ teamId?: string | null;
+ query: InsightQuery;
+}
+/**
+ * Inclusive local dates and optional booking/host filters.
+ */
+export interface InsightQuery {
+ /**
+ * First local date, inclusive.
+ */
+ from: string;
+ /**
+ * Last local date, inclusive; maximum 366 days.
+ */
+ to: string;
+ /**
+ * IANA zone used for dates and hour-of-day grouping.
+ */
+ timeZone: string;
+ /**
+ * Restrict to one booking link; omit for all links.
+ */
+ eventTypeId?: string | null;
+ /**
+ * Restrict to one assigned host; omit for all hosts.
+ */
+ hostId?: string | null;
+}
+/**
+ * Current and equally long preceding local-calendar periods.
+ */
+export interface BookingInsights {
+ /**
+ * Time at which completion was evaluated.
+ */
+ asOf: string;
+ /**
+ * Preceding period's first local date.
+ */
+ previousFrom: string;
+ /**
+ * Preceding period's last local date.
+ */
+ previousTo: string;
+ current: InsightPeriod;
+ previous: InsightPeriod;
+}
+/**
+ * One complete period of metrics and chart data, with no guest contact information.
+ */
+export interface InsightPeriod {
+ counts: InsightCounts;
+ /**
+ * Scheduled minutes of completed meetings, not actual call duration.
+ */
+ meetingMinutes: number;
+ /**
+ * Average scheduled duration of all confirmed bookings, including future ones.
+ */
+ averageMinutes: number;
+ /**
+ * Local-date counts, including dates with zero bookings.
+ */
+ days: {
+ [k: string]: InsightCounts;
+ };
+ /**
+ * Booking counts by local hour, indexed from 0 to 23.
+ */
+ hours: number[];
+ /**
+ * Booking counts by link identity.
+ */
+ eventCounts: {
+ [k: string]: number;
+ };
+ /**
+ * Booking counts by host; collective bookings count once for each host.
+ */
+ hostCounts: {
+ [k: string]: number;
+ };
+}
+/**
+ * Counts can overlap: a rescheduled event can also be completed or cancelled.
+ */
+export interface InsightCounts {
+ /**
+ * All bookings except failed and processing requests.
+ */
+ total: number;
+ /**
+ * Confirmed, ended bookings excluding explicit no-shows.
+ */
+ completed: number;
+ /**
+ * Bookings with at least one completed reschedule, counted once.
+ */
+ rescheduled: number;
+ /**
+ * Cancelled bookings, grouped by their scheduled start.
+ */
+ cancelled: number;
+ /**
+ * Explicit guest no-shows only.
+ */
+ guestNoShow: number;
+ /**
+ * Explicit host no-shows only.
+ */
+ hostNoShow: number;
+}
+/**
+ * Find available replacement times for a booking discovered through ListBookings. The date is in the booking schedule time zone. Only the personal owner or team administrators may reschedule it. Returns absolute start/end times for ChangeBooking reschedule; availability is checked again when moving the meeting.
+ */
+export interface GetBookingRescheduleSlots {
+ /**
+ * Existing booking ID from ListBookings.
+ */
+ bookingId: string;
+ /**
+ * Date in the booking schedule time zone.
+ */
+ date: string;
+}
+/**
+ * Authorized booking slots.
+ */
+export interface BookingSlotsResult {
+ /**
+ * Complete list of matching slots.
+ */
+ slots: Slot[];
+}
+/**
+ * Available slot and the hosts who can satisfy it.
+ */
+export interface Slot {
+ /**
+ * Absolute start.
+ */
+ startsAt: string;
+ /**
+ * Absolute end.
+ */
+ endsAt: string;
+}
/**
* Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token minted from the chat card or bot settings after IssueBotCredential or CreateBot; send it in the returned credentialHeader and send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
*/
@@ -8942,6 +9211,32 @@ export interface Schedule {
*/
overrides: DateOverride[];
}
+/**
+ * Read every booking starting in a half-open timestamp range for personal or team Booking Links. Returns IDs, status, hosts, guest details, answers, attendance and reschedule history; use these IDs to manage meetings. Both timestamps are required, with an explicit UTC offset. Maximum range 733 days. Oversized result sets fail rather than silently truncating: narrow the range. Use GetBookingInsights for aggregate statistics.
+ */
+export interface ListBookings {
+ /**
+ * Existing team ID, or null for personal bookings.
+ */
+ teamId?: string | null;
+ /**
+ * Inclusive start timestamp.
+ */
+ from: string;
+ /**
+ * Exclusive end timestamp.
+ */
+ to: string;
+}
+/**
+ * Authorized booking bookings.
+ */
+export interface BookingsResult {
+ /**
+ * Complete list of matching bookings.
+ */
+ bookings: Booking[];
+}
/**
* 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.
*/
@@ -10353,6 +10648,136 @@ export interface ToolActivityEvent {
*/
occurredAt: string;
}
+/**
+ * Read the full personal or team Booking Links configuration: booking-page name and introduction, reusable schedules, default availability, and all link settings with IDs and revision. Omit teamId for personal. Discover team IDs using ListBookingLinks. This read does not create a profile. Use the returned profile with UpdateBookingSettings to change shared availability or page settings.
+ */
+export interface ReadBookingSettings {
+ /**
+ * Existing team ID from ListBookingLinks, or null for personal settings.
+ */
+ teamId?: string | null;
+}
+/**
+ * Editable settings together with the public booking-page address.
+ */
+export interface BookingSettingsResult {
+ profile: Profile;
+ /**
+ * Public booking page; a revision-zero profile must be saved before sharing.
+ */
+ pageUrl: string;
+}
+/**
+ * Editable configuration for a person or team.
+ */
+export interface Profile {
+ /**
+ * Public, opaque profile identity.
+ */
+ id: string;
+ /**
+ * Display name on the public page.
+ */
+ name: string;
+ /**
+ * Public introduction.
+ */
+ description: string;
+ /**
+ * Reusable schedules.
+ */
+ schedules: Schedule[];
+ /**
+ * Personal hours used by team events; absent legacy profiles use their first schedule.
+ */
+ defaultScheduleId?: string | null;
+ /**
+ * Booking links.
+ */
+ eventTypes: EventType[];
+ /**
+ * Optimistic concurrency version.
+ */
+ revision: number;
+}
+/**
+ * A reusable booking link.
+ */
+export interface EventType {
+ /**
+ * Stable identity.
+ */
+ id: string;
+ /**
+ * 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;
+ /**
+ * Referenced availability schedule.
+ */
+ scheduleId: string;
+ 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[];
+}
/**
* Retrieve the transcript for a specific call record. Use ListEntities with includeTypes: ["call"] first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListEntities. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/"you".
*/
@@ -12296,6 +12721,20 @@ export interface TextEditorCodeExecutionResult {
export interface TextEditorCodeExecutionToolError {
error_code: CodeExecutionErrorCode;
}
+/**
+ * Update Booking Links settings after reading ReadBookingSettings. Pass the full profile with its current revision, preserving fields the user did not request changing. Supports booking-page name and introduction; adding, editing and deleting reusable schedules and date overrides; changing defaultScheduleId; reassigning link schedules; duplicating, deleting, enabling or pausing links. Generate new UUIDs for new schedules, links and questions; preserve existing IDs. Changing a shared schedule affects every link referencing it and personal default hours affect team hosting. Deleting a link does not cancel existing bookings. Explain affected links before changing shared hours or deleting. A stale revision fails: re-read and reconcile rather than overwriting. Use CreateBookingLink or EditBookingLink for ordinary single-link authoring and their conversational confirmation contract. Team edits require owner/admin access. Before saving, explain the proposed changes and their personal/team scope, ask whether to proceed, and wait for the user's approving reply in a later turn. Quote that reply verbatim in userConfirmation. Do not use the original request as confirmation.
+ */
+export interface UpdateBookingSettings {
+ /**
+ * Existing team ID from discovery, or null for personal settings.
+ */
+ teamId?: string | null;
+ profile: Profile;
+ /**
+ * Verbatim user reply approving the proposed settings and affected links.
+ */
+ userConfirmation: string;
+}
/**
* Update an existing calendar event. Only the supplied fields change; omitted fields keep their current values. The change is written to Google immediately and attendees are notified of it, so confirm details with the user first. Get the `eventId` from ListCalendarEvents.
*
diff --git a/bun.lock b/bun.lock
index 2cde92643a..7daea6d200 100644
--- a/bun.lock
+++ b/bun.lock
@@ -533,6 +533,7 @@
"esbuild",
],
"patchedDependencies": {
+ "@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index f52f7e3f54..a5adebe5cd 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -30,7 +30,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_scheduling = { path = "../calendar_scheduling", features = ["ai_tools", "postgres", "calendar", "client"] }
calendar_events = { path = "../calendar_events", features = ["ai_tools", "call-meetings", "mutation-client", "postgres"] }
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 4a08a356b7..df62ec90f2 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -608,6 +608,11 @@ pub async fn build_tool_service_context_from_env(
.and_then(|value| value.parse::<bool>().ok())
.unwrap_or(false),
),
+ booking_management_tool_context: crate::tool_context::build_booking_management_tool_context(
+ CalendarServiceUrl::new()?,
+ env.internal_api_key.to_string(),
+ environment,
+ ),
booking_link_tool_context: crate::tool_context::build_booking_link_tool_context(
pool.clone(),
environment,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 33fb23c731..5bb213e5dc 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -30,7 +30,7 @@ use bots::inbound::toolset::bot_toolset;
use calendar_events::inbound::team_toolset::team_calendar_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,
+ booking_link_toolset, booking_management_toolset, mcp_toolset as booking_link_mcp_toolset,
};
use call::inbound::toolset::call_toolset;
use channels::inbound::toolset::channel_toolset;
@@ -69,15 +69,15 @@ pub use tool_context::{
NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,
NoOpSnsEndpointManager, NoOpTaskProperties, RequestContext, RoutineToolContext,
TaskPropertiesAdapter, ToolActivityToolContext, 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, ToolFormsToolContext, ToolFrecencyService,
+ ToolBookingLinkToolContext, ToolBookingManagementToolContext, 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, ToolFormsToolContext, ToolFrecencyService,
ToolGithubPullRequestService, ToolImageGenerationToolContext, ToolImportService,
ToolImportToolContext, ToolInitiativeToolContext, ToolMcpSelector, ToolNotificationQueue,
ToolNotificationService, ToolNotificationToolContext, ToolPipedreamConnection,
@@ -86,16 +86,16 @@ pub use tool_context::{
ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,
ToolTeamCalendarToolContext, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
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_forms_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_calendar_tool_context, build_team_repository,
- build_team_tool_context,
+ build_booking_link_tool_context, build_booking_management_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_forms_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_calendar_tool_context, build_team_repository, build_team_tool_context,
};
pub use tool_context::{ToolConnectorToolContext, build_connector_tool_context};
#[cfg(any(test, feature = "test-support"))]
@@ -234,6 +234,7 @@ pub const EAGER_TOOLS: &[&str] = &[
/// sent to the AI provider.
pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
let toolset = subagent_toolset()
+ .add_subtoolset::<ToolBookingManagementToolContext>(booking_management_toolset())
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolTeamCalendarToolContext>(team_calendar_toolset())
.add_subtoolset::<RoutineToolContext>(routines::inbound::routine_toolset());
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index 9c23255eb1..ca4b655ae3 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -499,3 +499,29 @@ fn booking_link_mutations_execute_without_a_review_on_every_host() {
}
mod booking_links;
+
+#[test]
+fn booking_management_has_mcp_and_chat_parity() {
+ let names = [
+ "ReadBookingSettings",
+ "UpdateBookingSettings",
+ "ListBookings",
+ "GetBookingInsights",
+ "GetBookingRescheduleSlots",
+ "ChangeBooking",
+ ];
+ for host in [
+ AiHost::Chat,
+ AiHost::AgentSession,
+ AiHost::ChannelBot,
+ AiHost::Mcp,
+ ] {
+ let tools = tools_for(host);
+ for name in names {
+ assert!(
+ tools.toolset.tools.contains_key(name),
+ "{host:?} must expose {name}"
+ );
+ }
+ }
+}
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 4c421163b3..b22530ccd1 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -544,6 +544,27 @@ pub fn build_booking_link_tool_context(
}
}
+/// Booking administration is executed by the calendar service, including provider recovery.
+pub type ToolBookingManagementToolContext =
+ calendar_scheduling::inbound::toolset::BookingManagementToolContext<
+ calendar_scheduling::outbound::administration_client::SchedulingAdministrationClient,
+ >;
+/// Construct the authenticated scheduling client at the host composition root.
+pub fn build_booking_management_tool_context(
+ calendar_url: macro_service_urls::CalendarServiceUrl,
+ internal_api_key: String,
+ environment: macro_env::Environment,
+) -> ToolBookingManagementToolContext {
+ calendar_scheduling::inbound::toolset::BookingManagementToolContext {
+ service: Arc::new(calendar_scheduling::outbound::administration_client::SchedulingAdministrationClient::new(calendar_url.to_string(), internal_api_key)),
+ 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>;
@@ -1637,6 +1658,8 @@ pub struct ToolServiceContext {
pub calendar_tool_context: ToolCalendarToolContext,
pub team_calendar_tool_context: ToolTeamCalendarToolContext,
pub booking_link_tool_context: ToolBookingLinkToolContext,
+ /// Calendar-service-backed booking administration.
+ pub booking_management_tool_context: ToolBookingManagementToolContext,
pub notification_tool_context: ToolNotificationToolContext,
pub databases_tool_context: ToolDatabasesToolContext,
pub forms_tool_context: ToolFormsToolContext,
diff --git a/crates/calendar_scheduling/Cargo.toml b/crates/calendar_scheduling/Cargo.toml
index ce8e36c322..c09717ae5c 100644
--- a/crates/calendar_scheduling/Cargo.toml
+++ b/crates/calendar_scheduling/Cargo.toml
@@ -5,6 +5,7 @@ edition = "2024"
publish = false
[features]
+client = ["dep:reqwest"]
default = []
ai_tools = ["dep:ai_toolset", "dep:async-trait", "dep:schemars", "dep:anyhow"]
postgres = ["dep:sqlx"]
@@ -12,6 +13,7 @@ inbound = ["dep:axum", "dep:macro_authorization"]
calendar = ["dep:calendar_events", "dep:teams", "dep:macro_user_id"]
[dependencies]
+reqwest = { workspace = true, optional = true }
ai_toolset = { path = "../ai_toolset", optional = true }
async-trait = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
diff --git a/crates/calendar_scheduling/src/domain.rs b/crates/calendar_scheduling/src/domain.rs
index f242969a4b..ea903fdea9 100644
--- a/crates/calendar_scheduling/src/domain.rs
+++ b/crates/calendar_scheduling/src/domain.rs
@@ -8,3 +8,8 @@ mod recovery;
pub mod booking_link_models;
pub mod booking_links;
+
+pub mod insights;
+pub mod management;
+
+pub mod administration;
diff --git a/crates/calendar_scheduling/src/domain/administration.rs b/crates/calendar_scheduling/src/domain/administration.rs
new file mode 100644
index 0000000000..707dfdeea5
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/administration.rs
@@ -0,0 +1,103 @@
+//! Authorized scheduling operations exposed to administration clients.
+use super::{
+ insights::{BookingInsights, InsightQuery},
+ management::BookingChange,
+ models::*,
+ ports::*,
+ service::Service,
+};
+use chrono::{DateTime, NaiveDate, Utc};
+use std::future::Future;
+use uuid::Uuid;
+
+/// Scheduling administration; implementations preserve the owning service's policy.
+pub trait SchedulingAdministration: Send + Sync + 'static {
+ /// Read a personal or team profile without creating it.
+ fn settings(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ ) -> impl Future<Output = Result<Profile, Error>> + Send;
+ /// Save at the supplied revision, requiring owner/admin access.
+ fn save(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ profile: Profile,
+ ) -> impl Future<Output = Result<Profile, Error>> + Send;
+ /// Read all authorized bookings in a half-open range, or fail on overflow.
+ fn bookings_in_range(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ from: DateTime<Utc>,
+ to: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Vec<Booking>, Error>> + Send;
+ /// Read filtered metrics for current and previous local-calendar periods.
+ fn booking_insights(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: InsightQuery,
+ ) -> impl Future<Output = Result<BookingInsights, Error>> + Send;
+ /// Apply an authorized booking lifecycle change.
+ fn change_booking(
+ &self,
+ user: &str,
+ id: Uuid,
+ change: BookingChange,
+ ) -> impl Future<Output = Result<Booking, Error>> + Send;
+ /// Discover replacement times as the profile owner/admin.
+ fn host_replacement_slots(
+ &self,
+ user: &str,
+ id: Uuid,
+ date: NaiveDate,
+ ) -> impl Future<Output = Result<Vec<Slot>, Error>> + Send;
+}
+impl<R: Repository, C: Calendars, D: Directory> SchedulingAdministration for Service<R, C, D> {
+ async fn settings(&self, user: &str, team: Option<Uuid>) -> Result<Profile, Error> {
+ self.settings(user, team).await
+ }
+ async fn save(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ profile: Profile,
+ ) -> Result<Profile, Error> {
+ self.save(user, team, profile).await
+ }
+ async fn bookings_in_range(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ from: DateTime<Utc>,
+ to: DateTime<Utc>,
+ ) -> Result<Vec<Booking>, Error> {
+ self.bookings_in_range(user, team, from, to).await
+ }
+ async fn booking_insights(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: InsightQuery,
+ ) -> Result<BookingInsights, Error> {
+ self.booking_insights(user, team, query).await
+ }
+ async fn change_booking(
+ &self,
+ user: &str,
+ id: Uuid,
+ change: BookingChange,
+ ) -> Result<Booking, Error> {
+ self.change_booking(user, id, change).await
+ }
+ async fn host_replacement_slots(
+ &self,
+ user: &str,
+ id: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ self.host_replacement_slots(user, id, date).await
+ }
+}
diff --git a/crates/calendar_scheduling/src/domain/insights.rs b/crates/calendar_scheduling/src/domain/insights.rs
new file mode 100644
index 0000000000..e68c457333
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/insights.rs
@@ -0,0 +1,202 @@
+//! Calendar-local booking statistics with the same definitions as the settings UI.
+use super::{models::*, ports::*, service::Service};
+use chrono::{DateTime, Duration, NaiveDate, TimeZone, Timelike, Utc};
+use chrono_tz::Tz;
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet};
+use uuid::Uuid;
+
+/// Inclusive local dates and optional booking/host filters.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct InsightQuery {
+ /// First local date, inclusive.
+ pub from: NaiveDate,
+ /// Last local date, inclusive; maximum 366 days.
+ pub to: NaiveDate,
+ /// IANA zone used for dates and hour-of-day grouping.
+ #[cfg_attr(feature = "ai_tools", schemars(with = "String"))]
+ pub time_zone: Tz,
+ /// Restrict to one booking link; omit for all links.
+ pub event_type_id: Option<Uuid>,
+ /// Restrict to one assigned host; omit for all hosts.
+ pub host_id: Option<String>,
+}
+/// Counts can overlap: a rescheduled event can also be completed or cancelled.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InsightCounts {
+ /// All bookings except failed and processing requests.
+ pub total: u32,
+ /// Confirmed, ended bookings excluding explicit no-shows.
+ pub completed: u32,
+ /// Bookings with at least one completed reschedule, counted once.
+ pub rescheduled: u32,
+ /// Cancelled bookings, grouped by their scheduled start.
+ pub cancelled: u32,
+ /// Explicit guest no-shows only.
+ pub guest_no_show: u32,
+ /// Explicit host no-shows only.
+ pub host_no_show: u32,
+}
+impl InsightCounts {
+ fn add(&mut self, b: &Booking, now: DateTime<Utc>) -> bool {
+ let completed = b.status == BookingStatus::Confirmed
+ && b.ends_at <= now
+ && !matches!(
+ b.attendance,
+ BookingAttendance::GuestNoShow | BookingAttendance::HostNoShow
+ );
+ self.total += 1;
+ self.completed += u32::from(completed);
+ self.rescheduled += u32::from(b.reschedule_count > 0);
+ self.cancelled += u32::from(b.status == BookingStatus::Cancelled);
+ self.guest_no_show += u32::from(b.attendance == BookingAttendance::GuestNoShow);
+ self.host_no_show += u32::from(b.attendance == BookingAttendance::HostNoShow);
+ completed
+ }
+}
+/// One complete period of metrics and chart data, with no guest contact information.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InsightPeriod {
+ /// Summary event counts.
+ pub counts: InsightCounts,
+ /// Scheduled minutes of completed meetings, not actual call duration.
+ pub meeting_minutes: f64,
+ /// Average scheduled duration of all confirmed bookings, including future ones.
+ pub average_minutes: f64,
+ /// Local-date counts, including dates with zero bookings.
+ pub days: BTreeMap<NaiveDate, InsightCounts>,
+ /// Booking counts by local hour, indexed from 0 to 23.
+ pub hours: Vec<u32>,
+ /// Booking counts by link identity.
+ pub event_counts: BTreeMap<Uuid, u32>,
+ /// Booking counts by host; collective bookings count once for each host.
+ pub host_counts: BTreeMap<String, u32>,
+}
+/// Current and equally long preceding local-calendar periods.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BookingInsights {
+ /// Time at which completion was evaluated.
+ pub as_of: DateTime<Utc>,
+ /// Preceding period's first local date.
+ pub previous_from: NaiveDate,
+ /// Preceding period's last local date.
+ pub previous_to: NaiveDate,
+ /// Requested period.
+ pub current: InsightPeriod,
+ /// Comparison period, using identical filters and definitions.
+ pub previous: InsightPeriod,
+}
+fn period(
+ bookings: &[Booking],
+ query: &InsightQuery,
+ from: NaiveDate,
+ to: NaiveDate,
+ now: DateTime<Utc>,
+) -> InsightPeriod {
+ let mut result = InsightPeriod {
+ hours: vec![0; 24],
+ ..Default::default()
+ };
+ let mut date = from;
+ while date <= to {
+ result.days.insert(date, InsightCounts::default());
+ let Some(next) = date.succ_opt() else { break };
+ date = next;
+ }
+ let mut duration = 0.;
+ let mut confirmed = 0u32;
+ for b in bookings {
+ if matches!(b.status, BookingStatus::Failed | BookingStatus::Processing)
+ || query.event_type_id.is_some_and(|id| id != b.event_type_id)
+ || query
+ .host_id
+ .as_ref()
+ .is_some_and(|id| !b.hosts.contains(id))
+ {
+ continue;
+ }
+ let local = b.starts_at.with_timezone(&query.time_zone);
+ let Some(day) = result.days.get_mut(&local.date_naive()) else {
+ continue;
+ };
+ day.add(b, now);
+ let completed = result.counts.add(b, now);
+ result.hours[local.hour() as usize] += 1;
+ *result.event_counts.entry(b.event_type_id).or_default() += 1;
+ for host in b.hosts.iter().collect::<BTreeSet<_>>() {
+ *result.host_counts.entry(host.clone()).or_default() += 1;
+ }
+ let minutes = ((b.ends_at - b.starts_at).num_milliseconds() as f64 / 60_000.).max(0.);
+ if completed {
+ result.meeting_minutes += minutes;
+ }
+ if b.status == BookingStatus::Confirmed {
+ duration += minutes;
+ confirmed += 1;
+ }
+ }
+ if confirmed > 0 {
+ result.average_minutes = duration / f64::from(confirmed);
+ }
+ result
+}
+impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
+ /// Read complete authorized statistics; never silently truncate bookings.
+ pub async fn booking_insights(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: InsightQuery,
+ ) -> Result<BookingInsights, Error> {
+ let days = (query.to - query.from).num_days() + 1;
+ if !(1..=366).contains(&days) {
+ return Err(Error::Invalid(
+ "Choose an inclusive date range of 1 to 366 days".into(),
+ ));
+ }
+ let invalid_date =
+ || Error::Invalid("Choose dates within the supported calendar range".into());
+ let previous_from = query
+ .from
+ .checked_sub_signed(Duration::days(days))
+ .ok_or_else(invalid_date)?;
+ let previous_to = query.from.pred_opt().ok_or_else(invalid_date)?;
+ // A padded UTC read also covers zones with ambiguous or skipped local midnight.
+ // Period grouping below uses the requested IANA zone and exact local dates.
+ let start = Utc
+ .from_utc_datetime(
+ &previous_from
+ .and_hms_opt(0, 0, 0)
+ .ok_or_else(invalid_date)?,
+ )
+ .checked_sub_signed(Duration::days(1))
+ .ok_or_else(invalid_date)?;
+ let end = Utc
+ .from_utc_datetime(&query.to.and_hms_opt(0, 0, 0).ok_or_else(invalid_date)?)
+ .checked_add_signed(Duration::days(2))
+ .ok_or_else(invalid_date)?;
+ // Split the padded read to preserve the existing 733-day per-read limit.
+ let midpoint = start + (end - start) / 2;
+ let mut bookings = self.bookings_in_range(user, team, start, midpoint).await?;
+ bookings.extend(self.bookings_in_range(user, team, midpoint, end).await?);
+ let now = Utc::now();
+ Ok(BookingInsights {
+ as_of: now,
+ previous_from,
+ previous_to,
+ current: period(&bookings, &query, query.from, query.to, now),
+ previous: period(&bookings, &query, previous_from, previous_to, now),
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/domain/insights/test.rs b/crates/calendar_scheduling/src/domain/insights/test.rs
new file mode 100644
index 0000000000..92adb604ae
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/insights/test.rs
@@ -0,0 +1,59 @@
+use super::*;
+use serde_json::json;
+fn booking(status: &str, attendance: &str, start: &str) -> Booking {
+ serde_json::from_value(json!({
+ "id": Uuid::nil(), "eventTypeId": Uuid::nil(), "title": "Meeting", "name": "Guest", "email": "[email protected]",
+ "startsAt": start, "endsAt": "2026-11-01T07:00:00Z", "timeZone": "UTC", "hosts": ["host", "host"],
+ "status": status, "attendance": attendance, "rescheduleCount": 2, "location": "Office", "answers": {}
+ })).unwrap()
+}
+fn query() -> InsightQuery {
+ InsightQuery {
+ from: "2026-11-01".parse().unwrap(),
+ to: "2026-11-02".parse().unwrap(),
+ time_zone: chrono_tz::America::New_York,
+ event_type_id: None,
+ host_id: None,
+ }
+}
+#[test]
+fn matches_ui_definitions_and_dst_local_dates() {
+ let q = query();
+ let records = vec![
+ booking("confirmed", "unknown", "2026-11-01T05:30:00Z"),
+ booking("confirmed", "guestNoShow", "2026-11-01T06:30:00Z"),
+ booking("cancelled", "unknown", "2026-11-01T06:30:00Z"),
+ booking("failed", "unknown", "2026-11-01T06:30:00Z"),
+ booking("processing", "unknown", "2026-11-01T06:30:00Z"),
+ booking("confirmed", "unknown", "2026-11-01T03:30:00Z"),
+ ];
+ let p = period(
+ &records,
+ &q,
+ q.from,
+ q.to,
+ "2026-11-03T00:00:00Z".parse().unwrap(),
+ );
+ assert_eq!(p.counts.total, 3);
+ assert_eq!(p.counts.completed, 1);
+ assert_eq!(p.counts.rescheduled, 3);
+ assert_eq!(p.counts.cancelled, 1);
+ assert_eq!(p.counts.guest_no_show, 1);
+ assert_eq!(p.meeting_minutes, 90.);
+ assert_eq!(p.average_minutes, 60.);
+ assert_eq!(p.hours[1], 3); // Both instances of the repeated DST hour.
+ assert_eq!(p.host_counts["host"], 3); // Duplicate host IDs cannot inflate counts.
+ assert_eq!(p.days[&q.to].total, 0);
+}
+#[test]
+fn filters_and_future_meetings_do_not_invent_completion() {
+ let mut q = query();
+ let records = vec![booking("confirmed", "unknown", "2026-11-01T05:30:00Z")];
+ let now = "2026-11-01T00:00:00Z".parse().unwrap();
+ assert_eq!(period(&records, &q, q.from, q.to, now).counts.completed, 0);
+ q.host_id = Some("other".into());
+ assert_eq!(period(&records, &q, q.from, q.to, now).counts.total, 0);
+ q.host_id = None;
+ q.event_type_id = Some(Uuid::now_v7());
+ assert_eq!(period(&records, &q, q.from, q.to, now).counts.total, 0);
+}
diff --git a/crates/calendar_scheduling/src/domain/management.rs b/crates/calendar_scheduling/src/domain/management.rs
new file mode 100644
index 0000000000..edb2fa253e
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/management.rs
@@ -0,0 +1,58 @@
+//! Booking management workflows shared by interactive and headless clients.
+use super::{models::*, ports::*, service::Service};
+use chrono::{DateTime, NaiveDate, Utc};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// A host's requested change to a booked meeting.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(tag = "action", rename_all = "camelCase", deny_unknown_fields)]
+pub enum BookingChange {
+ /// Approve a legacy pending booking and send its calendar invitations.
+ Approve,
+ /// Cancel a booking and notify its attendees.
+ Cancel,
+ /// Record or clear attendance after the meeting ends.
+ Attendance {
+ /// Recorded outcome.
+ attendance: BookingAttendance,
+ },
+ /// Move the existing meeting to an available time; notify attendees.
+ Reschedule {
+ /// Absolute start chosen from available replacement slots.
+ #[serde(rename = "startsAt")]
+ starts_at: DateTime<Utc>,
+ },
+}
+impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
+ /// Apply a change using the same authorization and lifecycle rules as the UI.
+ pub async fn change_booking(
+ &self,
+ user: &str,
+ id: Uuid,
+ change: BookingChange,
+ ) -> Result<Booking, Error> {
+ match change {
+ BookingChange::Approve => self.approve(user, id).await,
+ BookingChange::Cancel => self.cancel(id, None, Some(user)).await,
+ BookingChange::Attendance { attendance } => {
+ self.set_attendance(user, id, attendance).await
+ }
+ BookingChange::Reschedule { starts_at } => {
+ let record = self.manage(user, id).await?;
+ Ok(self.reschedule(id, record.token, starts_at).await?.booking)
+ }
+ }
+ }
+ /// Discover replacement times without exposing the booking's bearer token.
+ pub async fn host_replacement_slots(
+ &self,
+ user: &str,
+ id: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ let record = self.manage(user, id).await?;
+ self.replacement_slots(id, record.token, date).await
+ }
+}
diff --git a/crates/calendar_scheduling/src/domain/models.rs b/crates/calendar_scheduling/src/domain/models.rs
index c5f049cb18..f9153330ab 100644
--- a/crates/calendar_scheduling/src/domain/models.rs
+++ b/crates/calendar_scheduling/src/domain/models.rs
@@ -73,6 +73,7 @@ pub struct Question {
pub required: bool,
}
/// A reusable booking link.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventType {
@@ -116,6 +117,7 @@ pub struct EventType {
pub questions: Vec<Question>,
}
/// Editable configuration for a person or team.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
@@ -146,6 +148,7 @@ pub struct OwnedProfile {
pub profile: Profile,
}
/// Booking lifecycle state.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BookingStatus {
@@ -161,6 +164,7 @@ pub enum BookingStatus {
Failed,
}
/// Attendance recorded by an assigned host or profile administrator after a meeting.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BookingAttendance {
@@ -175,6 +179,7 @@ pub enum BookingAttendance {
HostNoShow,
}
/// Public booking details, also visible to authorized profile members.
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Booking {
@@ -193,6 +198,7 @@ pub struct Booking {
/// Absolute meeting end.
pub ends_at: DateTime<Utc>,
/// Booker's display time zone.
+ #[cfg_attr(feature = "ai_tools", schemars(with = "String"))]
pub time_zone: chrono_tz::Tz,
/// Assigned hosts.
pub hosts: Vec<String>,
@@ -275,7 +281,8 @@ pub struct BusyRange {
pub end: DateTime<Utc>,
}
/// Available slot and the hosts who can satisfy it.
-#[derive(Clone, Debug, Serialize)]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Slot {
/// Absolute start.
diff --git a/crates/calendar_scheduling/src/domain/service/test.rs b/crates/calendar_scheduling/src/domain/service/test.rs
index 7e3d441754..52fc964ca2 100644
--- a/crates/calendar_scheduling/src/domain/service/test.rs
+++ b/crates/calendar_scheduling/src/domain/service/test.rs
@@ -1221,3 +1221,8 @@ impl AttachmentReadiness for Arc<Calendar> {
}
}
mod booking_links;
+
+mod management;
+
+#[cfg(all(feature = "client", feature = "inbound"))]
+mod http_administration;
diff --git a/crates/calendar_scheduling/src/domain/service/test/http_administration.rs b/crates/calendar_scheduling/src/domain/service/test/http_administration.rs
new file mode 100644
index 0000000000..07d01383ab
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/service/test/http_administration.rs
@@ -0,0 +1,130 @@
+//! Real HTTP adapter/router contract with in-memory scheduling persistence.
+use super::*;
+use crate::{
+ domain::{
+ administration::SchedulingAdministration, insights::InsightQuery, management::BookingChange,
+ },
+ inbound::router::{RouterState, router},
+ outbound::administration_client::SchedulingAdministrationClient,
+};
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
+};
+use model_user::UserContext;
+use rootcause::Report;
+
+#[derive(Clone)]
+struct Identity;
+impl MacroAuthorizationService for Identity {
+ async fn authorize(&self, _: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+ async fn authorize_internal(
+ &self,
+ key: &str,
+ claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ if key != "test-key" {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(claims.user_id.map(|user_id| UserContext {
+ user_id,
+ ..Default::default()
+ }))
+ }
+}
+
+#[tokio::test]
+async fn client_and_router_preserve_authority_and_all_management_workflows() {
+ let user = "macro|[email protected]";
+ let service = Arc::new(TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ ));
+ let app = axum::Router::new().nest(
+ "/calendar/scheduling",
+ router(RouterState::new(
+ service.clone(),
+ MacroAuthorizationState::new(Arc::new(Identity)),
+ )),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/calendar", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = SchedulingAdministrationClient::new(url.clone(), "test-key".into());
+ let initial = client.settings(user, None).await.unwrap();
+ assert_eq!(initial.revision, 0);
+ let mut wanted = profile(None);
+ wanted.id = initial.id;
+ wanted.event_types[0].hosts = vec![user.into()];
+ let saved = client.save(user, None, wanted.clone()).await.unwrap();
+ assert_eq!(saved.revision, 1);
+ assert!(matches!(
+ client.save(user, None, wanted).await,
+ Err(Error::Conflict)
+ ));
+ let record = service
+ .book(saved.id, saved.event_types[0].id, request())
+ .await
+ .unwrap();
+ let date = record.booking.starts_at.date_naive();
+ let bookings = client
+ .bookings_in_range(user, None, record.booking.starts_at, record.booking.ends_at)
+ .await
+ .unwrap();
+ assert_eq!(bookings.len(), 1);
+ let insights = client
+ .booking_insights(
+ user,
+ None,
+ InsightQuery {
+ from: date,
+ to: date,
+ time_zone: chrono_tz::UTC,
+ event_type_id: None,
+ host_id: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(insights.current.counts.total, 1);
+ assert_eq!(insights.current.counts.completed, 0);
+ let id = record.booking.id;
+ assert!(matches!(
+ client
+ .change_booking("macro|[email protected]", id, BookingChange::Cancel)
+ .await,
+ Err(Error::Forbidden)
+ ));
+ let slots = client.host_replacement_slots(user, id, date).await.unwrap();
+ let next = slots
+ .iter()
+ .find(|s| s.starts_at != record.booking.starts_at)
+ .unwrap();
+ let moved = client
+ .change_booking(
+ user,
+ id,
+ BookingChange::Reschedule {
+ starts_at: next.starts_at,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(moved.reschedule_count, 1);
+ let cancelled = client
+ .change_booking(user, id, BookingChange::Cancel)
+ .await
+ .unwrap();
+ assert_eq!(cancelled.status, BookingStatus::Cancelled);
+ let unauthenticated = SchedulingAdministrationClient::new(url, "wrong-key".into());
+ assert!(matches!(
+ unauthenticated.settings(user, None).await,
+ Err(Error::Forbidden)
+ ));
+ server.abort();
+}
diff --git a/crates/calendar_scheduling/src/domain/service/test/management.rs b/crates/calendar_scheduling/src/domain/service/test/management.rs
new file mode 100644
index 0000000000..1690a797a9
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/service/test/management.rs
@@ -0,0 +1,195 @@
+use super::*;
+use crate::domain::{insights::InsightQuery, management::BookingChange};
+
+#[tokio::test]
+async fn reports_require_membership_and_preserve_range_semantics() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let team = Some(Uuid::now_v7());
+ let query = InsightQuery {
+ from: "2026-10-01".parse().unwrap(),
+ to: "2026-10-31".parse().unwrap(),
+ time_zone: chrono_tz::America::New_York,
+ event_type_id: None,
+ host_id: None,
+ };
+ assert!(matches!(
+ service
+ .booking_insights("outsider", team, query.clone())
+ .await,
+ Err(Error::Forbidden)
+ ));
+ let report = service
+ .booking_insights("member", team, query.clone())
+ .await
+ .unwrap();
+ assert_eq!(report.previous_from.to_string(), "2026-08-31");
+ assert_eq!(report.previous_to.to_string(), "2026-09-30");
+ assert_eq!(report.current.days.len(), 31);
+ assert_eq!(report.current.counts.total, 0);
+ let mut invalid = query;
+ invalid.to = "2028-01-01".parse().unwrap();
+ assert!(matches!(
+ service.booking_insights("member", team, invalid).await,
+ Err(Error::Invalid(_))
+ ));
+}
+
+#[tokio::test]
+async fn management_uses_existing_authorization_and_availability() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let record = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let id = record.booking.id;
+ let date = record.booking.starts_at.date_naive();
+ assert!(matches!(
+ service.host_replacement_slots("outsider", id, date).await,
+ Err(Error::Forbidden)
+ ));
+ assert!(matches!(
+ service
+ .change_booking("outsider", id, BookingChange::Cancel)
+ .await,
+ Err(Error::Forbidden)
+ ));
+ assert!(matches!(
+ service
+ .change_booking(
+ "admin",
+ id,
+ BookingChange::Attendance {
+ attendance: BookingAttendance::Attended
+ }
+ )
+ .await,
+ Err(Error::Invalid(_))
+ ));
+ let slots = service
+ .host_replacement_slots("admin", id, date)
+ .await
+ .unwrap();
+ let replacement = slots
+ .iter()
+ .find(|slot| slot.starts_at != record.booking.starts_at)
+ .unwrap();
+ let moved = service
+ .change_booking(
+ "admin",
+ id,
+ BookingChange::Reschedule {
+ starts_at: replacement.starts_at,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(moved.starts_at, replacement.starts_at);
+ assert_eq!(moved.reschedule_count, 1);
+ assert_eq!(
+ service
+ .change_booking("admin", id, BookingChange::Cancel)
+ .await
+ .unwrap()
+ .status,
+ BookingStatus::Cancelled
+ );
+}
+
+#[cfg(feature = "ai_tools")]
+#[tokio::test]
+async fn management_tools_read_save_and_reject_stale_or_unauthorized_writes() {
+ use crate::inbound::toolset::{BookingManagementToolContext, booking_management_toolset};
+ use ai_toolset::{RequestContext, ToolSet};
+ use serde_json::json;
+ let service = Arc::new(TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ ));
+ let team = Some(Uuid::now_v7());
+ service.save("admin", team, profile(team)).await.unwrap();
+ let context = BookingManagementToolContext {
+ service: service.clone(),
+ public_origin: String::new(),
+ };
+ let tools = booking_management_toolset();
+ let request =
+ || RequestContext::new(serde_json::from_value(json!("macro|[email protected]")).unwrap());
+ // A personal read does not depend on externally supplied actor IDs.
+ let personal = tools
+ .try_tool_call(
+ context.clone(),
+ request(),
+ "ReadBookingSettings",
+ &json!({}),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(personal["profile"]["revision"], 0);
+ assert!(
+ personal["pageUrl"]
+ .as_str()
+ .unwrap()
+ .starts_with("/app/book/")
+ );
+ let mut changed = personal["profile"].clone();
+ changed["name"] = json!("My new booking page");
+ assert!(
+ tools
+ .try_tool_call(
+ context.clone(),
+ request(),
+ "UpdateBookingSettings",
+ &json!({"profile": changed, "userConfirmation": " "})
+ )
+ .await
+ .unwrap()
+ .is_err()
+ );
+ let saved = tools
+ .try_tool_call(
+ context.clone(),
+ request(),
+ "UpdateBookingSettings",
+ &json!({"profile": changed, "userConfirmation": "Yes, save those settings."}),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(saved["profile"]["name"], "My new booking page");
+ assert_eq!(saved["profile"]["revision"], 1);
+ assert!(
+ tools
+ .try_tool_call(
+ context.clone(),
+ request(),
+ "UpdateBookingSettings",
+ &json!({"profile": personal["profile"], "userConfirmation": "Yes, save those settings."})
+ )
+ .await
+ .unwrap()
+ .is_err()
+ );
+ assert!(
+ tools
+ .try_tool_call(
+ context,
+ request(),
+ "ReadBookingSettings",
+ &json!({"teamId": team})
+ )
+ .await
+ .unwrap()
+ .is_err()
+ );
+}
diff --git a/crates/calendar_scheduling/src/inbound/router.rs b/crates/calendar_scheduling/src/inbound/router.rs
index eb38042a05..83735807b5 100644
--- a/crates/calendar_scheduling/src/inbound/router.rs
+++ b/crates/calendar_scheduling/src/inbound/router.rs
@@ -1,5 +1,11 @@
//! Thin HTTP routes; membership, availability, and write policy live in the service.
-use crate::domain::{models::*, ports::*, service::Service};
+use crate::domain::{
+ insights::{BookingInsights, InsightQuery},
+ management::BookingChange,
+ models::*,
+ ports::*,
+ service::Service,
+};
use axum::{
Json, Router,
extract::{DefaultBodyLimit, FromRef, Path, Query, State},
@@ -54,6 +60,9 @@ pub fn router<
get(settings::<R, C, D, A>).put(save::<R, C, D, A>),
)
.route("/bookings", get(bookings::<R, C, D, A>))
+ .route("/insights", post(insights::<R, C, D, A>))
+ .route("/bookings/{id}/change", post(change::<R, C, D, A>))
+ .route("/bookings/{id}/slots", get(host_slots::<R, C, D, A>))
.route("/bookings/{id}/manage", get(manage::<R, C, D, A>))
.route("/bookings/{id}/approve", post(approve::<R, C, D, A>))
.route("/bookings/{id}/attendance", post(attendance::<R, C, D, A>))
@@ -368,6 +377,53 @@ async fn manage<R: Repository, C: Calendars, D: Directory, A: MacroAuthorization
}))
}
+async fn insights<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Query(scope): Query<Scope>,
+ Json(query): Json<InsightQuery>,
+) -> Result<Json<BookingInsights>, ApiError> {
+ Ok(Json(
+ s.service
+ .booking_insights(
+ user.authorization.user.macro_user_id.as_ref(),
+ scope.team_id,
+ query,
+ )
+ .await?,
+ ))
+}
+async fn change<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+ Json(change): Json<BookingChange>,
+) -> Result<Json<BookingResponse>, ApiError> {
+ Ok(Json(BookingResponse {
+ booking: s
+ .service
+ .change_booking(user.authorization.user.macro_user_id.as_ref(), id, change)
+ .await?,
+ }))
+}
+async fn host_slots<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+ Query(query): Query<ReplacementQuery>,
+) -> Result<Json<SlotsResponse>, ApiError> {
+ Ok(Json(SlotsResponse {
+ slots: s
+ .service
+ .host_replacement_slots(
+ user.authorization.user.macro_user_id.as_ref(),
+ id,
+ query.date,
+ )
+ .await?,
+ }))
+}
+
fn booking_token(headers: &HeaderMap) -> Result<Uuid, ApiError> {
headers
.get(axum::http::header::AUTHORIZATION)
diff --git a/crates/calendar_scheduling/src/inbound/toolset.rs b/crates/calendar_scheduling/src/inbound/toolset.rs
index 9ad653a77d..8c30c3bcf2 100644
--- a/crates/calendar_scheduling/src/inbound/toolset.rs
+++ b/crates/calendar_scheduling/src/inbound/toolset.rs
@@ -84,3 +84,43 @@ fn require_confirmation(confirmation: &str) -> Result<(), ToolCallError> {
#[cfg(test)]
mod test;
+
+mod read_booking_settings;
+pub use read_booking_settings::ReadBookingSettings;
+mod update_booking_settings;
+pub use update_booking_settings::UpdateBookingSettings;
+mod list_bookings;
+pub use list_bookings::ListBookings;
+mod get_booking_insights;
+pub use get_booking_insights::GetBookingInsights;
+mod get_booking_reschedule_slots;
+pub use get_booking_reschedule_slots::GetBookingRescheduleSlots;
+mod change_booking;
+pub use change_booking::ChangeBooking;
+
+/// Calendar administration service and public application origin.
+pub struct BookingManagementToolContext<Scheduling> {
+ /// Authorized scheduling service or its transport adapter.
+ pub service: Arc<Scheduling>,
+ /// Public application origin.
+ pub public_origin: String,
+}
+impl<Scheduling> Clone for BookingManagementToolContext<Scheduling> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ public_origin: self.public_origin.clone(),
+ }
+ }
+}
+/// Full settings, booking lifecycle and reporting tools, available in every AI host.
+pub fn booking_management_toolset<S: crate::domain::administration::SchedulingAdministration>()
+-> AsyncToolCollection<BookingManagementToolContext<S>> {
+ AsyncToolCollection::new()
+ .add_tool::<ReadBookingSettings, BookingManagementToolContext<S>>()
+ .add_tool::<UpdateBookingSettings, BookingManagementToolContext<S>>()
+ .add_tool::<ListBookings, BookingManagementToolContext<S>>()
+ .add_tool::<GetBookingInsights, BookingManagementToolContext<S>>()
+ .add_tool::<GetBookingRescheduleSlots, BookingManagementToolContext<S>>()
+ .add_tool::<ChangeBooking, BookingManagementToolContext<S>>()
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/change_booking.rs b/crates/calendar_scheduling/src/inbound/toolset/change_booking.rs
new file mode 100644
index 0000000000..608e0f3895
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/change_booking.rs
@@ -0,0 +1,46 @@
+use super::{BookingManagementToolContext, tool_error};
+use crate::domain::{administration::SchedulingAdministration, models::*};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Change booking through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "ChangeBooking",
+ description = "Manage an existing Booking Links meeting found with ListBookings: cancel it, approve a legacy pending booking, record or clear attendance, or reschedule to a start returned by GetBookingRescheduleSlots. Cancellation, approval and rescheduling can notify attendees; explain the action and act only on user authorization. Attendance is available only after a confirmed meeting ends. Existing host/admin permissions and availability rules apply. Returns the actual saved booking; a failed or processing status requires reconciliation, not blind retries. This does not edit the reusable booking link."
+)]
+pub struct ChangeBooking {
+ /// Existing booking ID discovered through ListBookings.
+ pub booking_id: Uuid,
+ /// Requested change to this meeting.
+ pub change: crate::domain::management::BookingChange,
+}
+impl ToolAnnotated for ChangeBooking {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Change booking");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>> for ChangeBooking {
+ type Output = Booking;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ context
+ .0
+ .service
+ .change_booking(
+ request.user_id.as_ref(),
+ self.booking_id,
+ self.change.clone(),
+ )
+ .await
+ .map_err(tool_error)
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/get_booking_insights.rs b/crates/calendar_scheduling/src/inbound/toolset/get_booking_insights.rs
new file mode 100644
index 0000000000..506c6c6032
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/get_booking_insights.rs
@@ -0,0 +1,44 @@
+use super::{BookingManagementToolContext, tool_error};
+use crate::domain::administration::SchedulingAdministration;
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Booking insights through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "GetBookingInsights",
+ description = "Get the same Booking Links summary statistics and chart data as Insights, for inclusive local dates in an IANA time zone (maximum 366 days). Returns current and equally long previous periods: total, completed, rescheduled, cancelled, host/guest no-shows, scheduled meeting minutes, average duration, daily trends, popular hours, and counts by link and host. Optional eventTypeId and hostId filters apply to both periods. Failed and processing requests are excluded. Completed means confirmed and ended without an explicit no-show, not verified attendance. Minutes are scheduled duration, not actual call duration. Rescheduled is counted once per booking. Dates use the booking current start. No guest contact information is returned."
+)]
+pub struct GetBookingInsights {
+ /// Existing team ID, or null for personal insights.
+ pub team_id: Option<Uuid>,
+ /// Inclusive local date range, reporting time zone, and optional filters.
+ pub query: crate::domain::insights::InsightQuery,
+}
+impl ToolAnnotated for GetBookingInsights {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Booking insights");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>>
+ for GetBookingInsights
+{
+ type Output = crate::domain::insights::BookingInsights;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ context
+ .0
+ .service
+ .booking_insights(request.user_id.as_ref(), self.team_id, self.query.clone())
+ .await
+ .map_err(tool_error)
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/get_booking_reschedule_slots.rs b/crates/calendar_scheduling/src/inbound/toolset/get_booking_reschedule_slots.rs
new file mode 100644
index 0000000000..a118a78e7b
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/get_booking_reschedule_slots.rs
@@ -0,0 +1,52 @@
+use super::{BookingManagementToolContext, tool_error};
+use crate::domain::{administration::SchedulingAdministration, models::*};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Find replacement times through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "GetBookingRescheduleSlots",
+ description = "Find available replacement times for a booking discovered through ListBookings. The date is in the booking schedule time zone. Only the personal owner or team administrators may reschedule it. Returns absolute start/end times for ChangeBooking reschedule; availability is checked again when moving the meeting."
+)]
+pub struct GetBookingRescheduleSlots {
+ /// Existing booking ID from ListBookings.
+ pub booking_id: Uuid,
+ /// Date in the booking schedule time zone.
+ pub date: chrono::NaiveDate,
+}
+/// Authorized booking slots.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BookingSlotsResult {
+ /// Complete list of matching slots.
+ pub slots: Vec<Slot>,
+}
+impl ToolAnnotated for GetBookingRescheduleSlots {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Find replacement times");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>>
+ for GetBookingRescheduleSlots
+{
+ type Output = BookingSlotsResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(BookingSlotsResult {
+ slots: context
+ .0
+ .service
+ .host_replacement_slots(request.user_id.as_ref(), self.booking_id, self.date)
+ .await
+ .map_err(tool_error)?,
+ })
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/list_bookings.rs b/crates/calendar_scheduling/src/inbound/toolset/list_bookings.rs
new file mode 100644
index 0000000000..aa3bf2a6a1
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/list_bookings.rs
@@ -0,0 +1,52 @@
+use super::{BookingManagementToolContext, tool_error};
+use crate::domain::{administration::SchedulingAdministration, models::*};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// List bookings through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "ListBookings",
+ description = "Read every booking starting in a half-open timestamp range for personal or team Booking Links. Returns IDs, status, hosts, guest details, answers, attendance and reschedule history; use these IDs to manage meetings. Both timestamps are required, with an explicit UTC offset. Maximum range 733 days. Oversized result sets fail rather than silently truncating: narrow the range. Use GetBookingInsights for aggregate statistics."
+)]
+pub struct ListBookings {
+ /// Existing team ID, or null for personal bookings.
+ pub team_id: Option<Uuid>,
+ /// Inclusive start timestamp.
+ pub from: chrono::DateTime<chrono::Utc>,
+ /// Exclusive end timestamp.
+ pub to: chrono::DateTime<chrono::Utc>,
+}
+/// Authorized booking bookings.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BookingsResult {
+ /// Complete list of matching bookings.
+ pub bookings: Vec<Booking>,
+}
+impl ToolAnnotated for ListBookings {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List bookings");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>> for ListBookings {
+ type Output = BookingsResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(BookingsResult {
+ bookings: context
+ .0
+ .service
+ .bookings_in_range(request.user_id.as_ref(), self.team_id, self.from, self.to)
+ .await
+ .map_err(tool_error)?,
+ })
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/read_booking_settings.rs b/crates/calendar_scheduling/src/inbound/toolset/read_booking_settings.rs
new file mode 100644
index 0000000000..1cb99cd227
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/read_booking_settings.rs
@@ -0,0 +1,62 @@
+use super::{BookingManagementToolContext, tool_error};
+use crate::domain::{administration::SchedulingAdministration, models::*};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Read booking settings through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "ReadBookingSettings",
+ description = "Read the full personal or team Booking Links configuration: booking-page name and introduction, reusable schedules, default availability, and all link settings with IDs and revision. Omit teamId for personal. Discover team IDs using ListBookingLinks. This read does not create a profile. Use the returned profile with UpdateBookingSettings to change shared availability or page settings."
+)]
+pub struct ReadBookingSettings {
+ /// Existing team ID from ListBookingLinks, or null for personal settings.
+ pub team_id: Option<Uuid>,
+}
+/// Editable settings together with the public booking-page address.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BookingSettingsResult {
+ /// Full settings, including the current revision for writes.
+ pub profile: Profile,
+ /// Public booking page; a revision-zero profile must be saved before sharing.
+ pub page_url: String,
+}
+impl<Scheduling> BookingManagementToolContext<Scheduling> {
+ pub(super) fn settings_result(&self, profile: Profile) -> BookingSettingsResult {
+ let page_url = format!(
+ "{}/app/book/{}",
+ self.public_origin.trim_end_matches('/'),
+ profile.id
+ );
+ BookingSettingsResult { profile, page_url }
+ }
+}
+impl ToolAnnotated for ReadBookingSettings {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read booking settings");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>>
+ for ReadBookingSettings
+{
+ type Output = BookingSettingsResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let profile = context
+ .0
+ .service
+ .settings(request.user_id.as_ref(), self.team_id)
+ .await
+ .map_err(tool_error)?;
+ Ok(context.0.settings_result(profile))
+ }
+}
diff --git a/crates/calendar_scheduling/src/inbound/toolset/update_booking_settings.rs b/crates/calendar_scheduling/src/inbound/toolset/update_booking_settings.rs
new file mode 100644
index 0000000000..34b332d9a3
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/update_booking_settings.rs
@@ -0,0 +1,49 @@
+use super::read_booking_settings::BookingSettingsResult;
+use super::{BookingManagementToolContext, require_confirmation, tool_error};
+use crate::domain::{administration::SchedulingAdministration, models::*};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+use uuid::Uuid;
+
+/// Update booking settings through the authorized scheduling service.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(
+ title = "UpdateBookingSettings",
+ description = "Update Booking Links settings after reading ReadBookingSettings. Pass the full profile with its current revision, preserving fields the user did not request changing. Supports booking-page name and introduction; adding, editing and deleting reusable schedules and date overrides; changing defaultScheduleId; reassigning link schedules; duplicating, deleting, enabling or pausing links. Generate new UUIDs for new schedules, links and questions; preserve existing IDs. Changing a shared schedule affects every link referencing it and personal default hours affect team hosting. Deleting a link does not cancel existing bookings. Explain affected links before changing shared hours or deleting. A stale revision fails: re-read and reconcile rather than overwriting. Use CreateBookingLink or EditBookingLink for ordinary single-link authoring and their conversational confirmation contract. Team edits require owner/admin access. Before saving, explain the proposed changes and their personal/team scope, ask whether to proceed, and wait for the user's approving reply in a later turn. Quote that reply verbatim in userConfirmation. Do not use the original request as confirmation."
+)]
+pub struct UpdateBookingSettings {
+ /// Existing team ID from discovery, or null for personal settings.
+ pub team_id: Option<Uuid>,
+ /// Full desired profile including the revision read from ReadBookingSettings.
+ pub profile: Profile,
+ /// Verbatim user reply approving the proposed settings and affected links.
+ pub user_confirmation: String,
+}
+impl ToolAnnotated for UpdateBookingSettings {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Update booking settings");
+}
+#[async_trait]
+impl<S: SchedulingAdministration> AsyncTool<BookingManagementToolContext<S>>
+ for UpdateBookingSettings
+{
+ type Output = BookingSettingsResult;
+ async fn call(
+ &self,
+ context: ServiceContext<BookingManagementToolContext<S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ require_confirmation(&self.user_confirmation)?;
+ let profile = context
+ .0
+ .service
+ .save(request.user_id.as_ref(), self.team_id, self.profile.clone())
+ .await
+ .map_err(tool_error)?;
+ Ok(context.0.settings_result(profile))
+ }
+}
diff --git a/crates/calendar_scheduling/src/lib.rs b/crates/calendar_scheduling/src/lib.rs
index f76313fe53..176f74ce32 100644
--- a/crates/calendar_scheduling/src/lib.rs
+++ b/crates/calendar_scheduling/src/lib.rs
@@ -3,5 +3,5 @@
pub mod domain;
#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
-#[cfg(any(feature = "postgres", feature = "calendar"))]
+#[cfg(any(feature = "postgres", feature = "calendar", feature = "client"))]
pub mod outbound;
diff --git a/crates/calendar_scheduling/src/outbound.rs b/crates/calendar_scheduling/src/outbound.rs
index e631e87b04..fd7912894e 100644
--- a/crates/calendar_scheduling/src/outbound.rs
+++ b/crates/calendar_scheduling/src/outbound.rs
@@ -3,3 +3,6 @@
pub mod macro_services;
#[cfg(feature = "postgres")]
pub mod postgres;
+
+#[cfg(feature = "client")]
+pub mod administration_client;
diff --git a/crates/calendar_scheduling/src/outbound/administration_client.rs b/crates/calendar_scheduling/src/outbound/administration_client.rs
new file mode 100644
index 0000000000..44defe4d0e
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound/administration_client.rs
@@ -0,0 +1,167 @@
+//! Scheduling administration through the calendar service's authenticated API.
+use crate::domain::{
+ administration::SchedulingAdministration,
+ insights::{BookingInsights, InsightQuery},
+ management::BookingChange,
+ models::*,
+};
+use chrono::{DateTime, NaiveDate, Utc};
+use reqwest::{Client, Method, RequestBuilder, StatusCode};
+use serde::{Deserialize, de::DeserializeOwned};
+use uuid::Uuid;
+
+/// Keeps calendar provider writes and recovery in the calendar service.
+pub struct SchedulingAdministrationClient {
+ base_url: String,
+ internal_api_key: String,
+ http: Client,
+}
+impl SchedulingAdministrationClient {
+ /// `calendar_url` includes the `/calendar` gateway prefix.
+ pub fn new(calendar_url: String, internal_api_key: String) -> Self {
+ Self {
+ base_url: format!("{}/scheduling", calendar_url.trim_end_matches('/')),
+ internal_api_key,
+ http: Client::builder()
+ .timeout(std::time::Duration::from_secs(60))
+ .build()
+ .expect("static HTTP client configuration is valid"),
+ }
+ }
+ fn request(
+ &self,
+ method: Method,
+ path: &str,
+ user: &str,
+ team: Option<Uuid>,
+ ) -> RequestBuilder {
+ let request = self
+ .http
+ .request(method, format!("{}{path}", self.base_url))
+ .header("x-internal-auth-key", &self.internal_api_key)
+ .header("x-internal-macro-user-id", user);
+ match team {
+ Some(team) => request.query(&[("teamId", team)]),
+ None => request,
+ }
+ }
+ async fn send<T: DeserializeOwned>(&self, request: RequestBuilder) -> Result<T, Error> {
+ let response = request.send().await.map_err(|_| Error::Unavailable)?;
+ if response.status().is_success() {
+ return response.json().await.map_err(|_| Error::Unavailable);
+ }
+ let status = response.status();
+ let body = response.json::<ErrorBody>().await.ok();
+ Err(match status {
+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => Error::Forbidden,
+ StatusCode::NOT_FOUND => Error::NotFound,
+ StatusCode::CONFLICT => Error::Conflict,
+ StatusCode::TOO_MANY_REQUESTS => Error::RateLimited,
+ StatusCode::BAD_REQUEST => Error::Invalid(
+ body.map(|b| b.message)
+ .unwrap_or_else(|| "Invalid scheduling request".into()),
+ ),
+ _ => Error::Unavailable,
+ })
+ }
+}
+#[derive(Deserialize)]
+struct ErrorBody {
+ message: String,
+}
+#[derive(Deserialize)]
+struct ProfileBody {
+ profile: Profile,
+}
+#[derive(Deserialize)]
+struct BookingsBody {
+ bookings: Vec<Booking>,
+}
+#[derive(Deserialize)]
+struct BookingBody {
+ booking: Booking,
+}
+#[derive(Deserialize)]
+struct SlotsBody {
+ slots: Vec<Slot>,
+}
+impl SchedulingAdministration for SchedulingAdministrationClient {
+ async fn settings(&self, user: &str, team: Option<Uuid>) -> Result<Profile, Error> {
+ Ok(self
+ .send::<ProfileBody>(self.request(Method::GET, "/settings", user, team))
+ .await?
+ .profile)
+ }
+ async fn save(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ profile: Profile,
+ ) -> Result<Profile, Error> {
+ Ok(self
+ .send::<ProfileBody>(
+ self.request(Method::PUT, "/settings", user, team)
+ .json(&profile),
+ )
+ .await?
+ .profile)
+ }
+ async fn bookings_in_range(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ from: DateTime<Utc>,
+ to: DateTime<Utc>,
+ ) -> Result<Vec<Booking>, Error> {
+ Ok(self
+ .send::<BookingsBody>(
+ self.request(Method::GET, "/bookings", user, team)
+ .query(&[("from", from), ("to", to)]),
+ )
+ .await?
+ .bookings)
+ }
+ async fn booking_insights(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ query: InsightQuery,
+ ) -> Result<BookingInsights, Error> {
+ self.send(
+ self.request(Method::POST, "/insights", user, team)
+ .json(&query),
+ )
+ .await
+ }
+ async fn change_booking(
+ &self,
+ user: &str,
+ id: Uuid,
+ change: BookingChange,
+ ) -> Result<Booking, Error> {
+ Ok(self
+ .send::<BookingBody>(
+ self.request(Method::POST, &format!("/bookings/{id}/change"), user, None)
+ .json(&change),
+ )
+ .await?
+ .booking)
+ }
+ async fn host_replacement_slots(
+ &self,
+ user: &str,
+ id: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ Ok(self
+ .send::<SlotsBody>(
+ self.request(Method::GET, &format!("/bookings/{id}/slots"), user, None)
+ .query(&[("date", date)]),
+ )
+ .await?
+ .slots)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/outbound/administration_client/test.rs b/crates/calendar_scheduling/src/outbound/administration_client/test.rs
new file mode 100644
index 0000000000..bd2e2a429f
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound/administration_client/test.rs
@@ -0,0 +1,61 @@
+use super::*;
+
+#[test]
+fn requests_preserve_authenticated_actor_scope_and_wire_shape() {
+ let client = SchedulingAdministrationClient::new(
+ "https://calendar.example/calendar/".into(),
+ "test-key".into(),
+ );
+ let team = Uuid::now_v7();
+ let request = client
+ .request(
+ Method::GET,
+ "/settings",
+ Some(team),
+ )
+ .build()
+ .unwrap();
+ assert_eq!(request.url().path(), "/calendar/scheduling/settings");
+ assert_eq!(
+ request.url().query(),
+ Some(format!("teamId={team}").as_str())
+ );
+ assert_eq!(
+ request.headers()["x-internal-macro-user-id"],
+ );
+ assert_eq!(request.headers()["x-internal-auth-key"], "test-key");
+ let change = BookingChange::Attendance {
+ attendance: BookingAttendance::GuestNoShow,
+ };
+ assert_eq!(
+ serde_json::to_value(change).unwrap(),
+ serde_json::json!({"action":"attendance", "attendance":"guestNoShow"})
+ );
+}
+
+#[tokio::test]
+async fn stale_revision_response_remains_a_conflict() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut bytes = [0u8; 2048];
+ socket.read(&mut bytes).await.unwrap();
+ socket
+ .write_all(b"HTTP/1.1 409 Conflict\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}")
+ .await
+ .unwrap();
+ });
+ let client = SchedulingAdministrationClient::new(
+ format!("http://{address}/calendar"),
+ "test-key".into(),
+ );
+ assert!(matches!(
+ client.settings("macro|[email protected]", None).await,
+ Err(Error::Conflict)
+ ));
+ server.await.unwrap();
+}
diff --git a/crates/email_utils/src/sanitizer.rs b/crates/email_utils/src/sanitizer.rs
index a82a6a2e5b..7576358c92 100644
--- a/crates/email_utils/src/sanitizer.rs
+++ b/crates/email_utils/src/sanitizer.rs
@@ -9,6 +9,7 @@
use ammonia::Builder;
use regex::Regex;
use scraper::{Html, Selector};
+use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::LazyLock;
@@ -159,6 +160,38 @@ static CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| build_cleaner(fals
/// Cleaner for locally-authored bodies; see [`sanitize_authored_html`].
static AUTHORED_CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| build_cleaner(true));
+const ALLOWED_URL_SCHEMES: [&str; 6] = ["http", "https", "mailto", "cid", "tel", "sms"];
+
+// Ammonia cannot filter inline styles while also allowing <style> elements.
+// Use its patched CSS parser independently; stylesheet text still goes through
+// sanitize_style_blocks after the outer HTML has been cleaned.
+static STYLE_ATTRIBUTE_CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| {
+ let mut cleaner = Builder::default();
+ cleaner.add_generic_attributes(&["style"]);
+ cleaner.filter_style_properties(get_safe_css_properties());
+ cleaner.url_schemes(HashSet::from(ALLOWED_URL_SCHEMES));
+ cleaner
+});
+static STYLE_ATTRIBUTE_SELECTOR: LazyLock<Selector> =
+ LazyLock::new(|| Selector::parse("div").expect("static selector is valid"));
+
+fn sanitize_style_attribute(value: &str) -> String {
+ let escaped = value
+ .replace('&', "&amp;")
+ .replace('"', "&quot;")
+ .replace('<', "&lt;");
+ let cleaned = STYLE_ATTRIBUTE_CLEANER
+ .clean(&format!("<div style=\"{escaped}\"></div>"))
+ .to_string();
+ let fragment = Html::parse_fragment(&cleaned);
+ fragment
+ .select(&STYLE_ATTRIBUTE_SELECTOR)
+ .next()
+ .and_then(|element| element.value().attr("style"))
+ .unwrap_or_default()
+ .to_owned()
+}
+
fn build_cleaner(allow_editor_round_trip: bool) -> Builder<'static> {
let mut cleaner = Builder::default();
@@ -217,10 +250,16 @@ fn build_cleaner(allow_editor_round_trip: bool) -> Builder<'static> {
"summary", // Modern
]);
- cleaner.filter_style_properties(get_safe_css_properties());
+ cleaner.attribute_filter(|_, attribute, value| {
+ Some(if attribute == "style" {
+ Cow::Owned(sanitize_style_attribute(value))
+ } else {
+ Cow::Borrowed(value)
+ })
+ });
// Allow common, generally safe attributes
- // IMPORTANT: `style` is included here, enabling Ammonia's CSS filter
+ // The attribute callback above applies Ammonia's CSS filter to `style`.
cleaner.add_generic_attributes(&[
"style",
"class",
@@ -274,14 +313,7 @@ fn build_cleaner(allow_editor_round_trip: bool) -> Builder<'static> {
cleaner.add_tag_attributes("details", &["open"]);
// Link safety and url schemes
- let mut allowed_schemes = HashSet::new();
- allowed_schemes.insert("http");
- allowed_schemes.insert("https");
- allowed_schemes.insert("mailto");
- allowed_schemes.insert("cid");
- allowed_schemes.insert("tel");
- allowed_schemes.insert("sms");
- cleaner.url_schemes(allowed_schemes);
+ cleaner.url_schemes(HashSet::from(ALLOWED_URL_SCHEMES));
if allow_editor_round_trip {
// `data-*` attributes are inert, and the composer round-trips through
diff --git a/crates/email_utils/src/sanitizer/test.rs b/crates/email_utils/src/sanitizer/test.rs
index 24b0575091..e35940d948 100644
--- a/crates/email_utils/src/sanitizer/test.rs
+++ b/crates/email_utils/src/sanitizer/test.rs
@@ -1,5 +1,43 @@
use super::*;
+#[test]
+fn inline_style_url_quotes_remain_escaped_after_html_round_trip() {
+ let html = r#"<div style='background-image:url("cid:\"")'>content</div>"#;
+
+ for sanitize in [
+ sanitize_email_html,
+ sanitize_html_fragment,
+ sanitize_authored_html,
+ ] {
+ let sanitized = sanitize(html);
+ let fragment = Html::parse_fragment(&sanitized);
+ let element = fragment.select(&STYLE_ATTRIBUTE_SELECTOR).next().unwrap();
+ assert_eq!(
+ element.value().attr("style"),
+ Some(r#"background-image:url("cid:\"")"#),
+ "CSS quotes must remain escaped after decoding HTML entities"
+ );
+ }
+}
+
+#[test]
+fn inline_style_filtering_and_stylesheet_filtering_both_apply() {
+ let html = r#"<style>.a{color:blue;position:fixed}</style>
+ <div style="color:red;position:fixed;background-image:url(javascript:alert)">content</div>"#;
+
+ for sanitize in [
+ sanitize_email_html,
+ sanitize_html_fragment,
+ sanitize_authored_html,
+ ] {
+ let sanitized = sanitize(html);
+ assert!(sanitized.contains("color:blue;"));
+ assert!(sanitized.contains("color:red"));
+ assert!(!sanitized.contains("position"));
+ assert!(!sanitized.contains("javascript"));
+ }
+}
+
#[test]
fn strips_script_svg_math_and_foreign_object_vectors() {
let html = r#"<html><body>
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 9d598c1f54..7e4dac3b27 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -1618,3 +1618,29 @@ a rejected configuration must retain the unsent draft and attachments.
Usage records follow the provider's delivered speed for each call, including tool
loops. OpenAI prompts exceeding 272,000 tokens use the long-context rate for that
call. Standard and accelerated rates have separate pricing keys.
+
+### Booking settings, meetings, and reporting through MCP
+
+All AI hosts, including MCP, also provide:
+
+- `ReadBookingSettings`: full personal/team page, shared schedules, default hours,
+ link settings and revision. Discover team IDs with `ListBookingLinks`.
+- `UpdateBookingSettings`: save a complete profile at the read revision. Preserve
+ unrelated settings; explain the proposal and quote the user’s later approving
+ reply in `userConfirmation`, as with link authoring. Supports page text,
+ schedule CRUD, default hours, link schedule assignments, duplication, deletion
+ and enabled state. Shared-hours
+ changes affect all referencing links; deleting a link keeps existing meetings.
+ Use the existing confirmed create/edit tools for ordinary link authoring.
+- `ListBookings`: complete meetings and answers in a half-open timestamp range.
+ Narrow the range on overflow; do not treat an error as an empty report.
+- `GetBookingRescheduleSlots` and `ChangeBooking`: discover replacements, move or
+ cancel meetings, approve legacy pending requests, and record/clear attendance.
+ Rescheduling requires the personal owner or team admin. Attendance also allows
+ assigned hosts after confirmed meetings end. Changes can notify attendees.
+- `GetBookingInsights`: inclusive local dates, IANA time zone, optional link/host
+ filters, current and previous period metrics, daily/hourly trends, and link/host
+ counts. Uses the same definitions as the visual Insights page. Meeting minutes
+ measure scheduled duration; completion does not claim verified attendance.
+
+These tools use the same domain permissions and booking lifecycle as the UI.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 6faef3cf60..4440529e0f 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1327,14 +1327,14 @@ so invitees can open those links.
Calendar connections live in **Settings → Calendar** (`/app/settings/calendar`).
Scheduling lives in the separate **Settings → Booking links** item
-(`/app/settings/booking-links`), with Booking links, Availability, Booking pages,
-Teams, Bookings, and Insights in one scrolling page. The calendar toolbar’s
-booking actions open Booking links; email and integration connection shortcuts
-continue to open Calendar.
-There is no second sidebar or global owner switch. Personal and team booking links
-appear together with ownership badges. New booking link and New schedule ask which
-owner to create for when multiple editable owners are available, then open inline editors;
-event options are stacked sections. Save changes or Cancel returns to the list.
+(`/app/settings/booking-links`). Use the owner menu at the top right to choose
+**Personal** or **Team · team name**,
+then use **Links**, **Availability**, **Booking page**, **Bookings**, or **Insights**.
+Every section and creation action applies to that selected owner. The default is
+Personal. **Manage teams** in that menu opens team settings. The calendar toolbar’s booking
+actions open Booking links; connection shortcuts continue to open Calendar.
+**New booking link** and **New schedule** create for the selected owner and open
+inline editors. Save changes or Cancel returns to that owner's list.
Connected calendars offers Connect account (the existing Google consent flow),
Connect calendar for accounts missing calendar permission, and Disconnect with
confirmation. Disconnect removes calendar access/data, not the Gmail connection.
@@ -1350,11 +1350,12 @@ Booking status filters use the same segmented control as the CRM sidebar.
In Availability, each weekday has an enable switch, time ranges, an add button,
and a copy-hours menu; select target days and Apply before saving the schedule.
Date overrides and the searchable timezone picker sit below the weekly hours.
-Ownership badges identify Personal or Team · team name on links and availability.
-Public booking pages, bookings, and insights are grouped by owner and remain visible
-together; editing one owner does not switch the rest of the page. Search booking
-links by title, slug, or owner. Team owners/admins can edit team links; ordinary members can view them. `Event types` creates, edits,
-pauses, duplicates, previews, and copies booking links. Event settings include
+The header shows the selected owner; team owners have an explicit **Team** label.
+Links and availability use flat rows, with actions beside each item.
+Booking pages, bookings, and insights show only the selected owner. Search filters
+that owner’s links and clears when switching owners. Team owners/admins can edit
+team links; ordinary members can view them. `Links` creates, edits, pauses,
+duplicates, previews, and copies booking links. Event settings include
weekly availability, collective/all-host or round-robin/one-host assignment,
notice, buffers, booking horizon, daily limits, and custom questions. New event
types stay paused until `Accept bookings` is selected and changes are saved.
@@ -1362,8 +1363,8 @@ types stay paused until `Accept bookings` is selected and changes are saved.
zone. Set a default schedule for new event types; a schedule cannot be deleted
until its event types use another one. Collective and round-robin team meetings
respect each host’s personal default hours when configured, plus busy calendars.
-`Teams` summarizes connected teams and links to team settings; the member roster
-lives in team settings. Choose hosts for a team booking link inside its editor.
+**Manage teams** opens team settings, where the member roster lives. Choose hosts
+for a team booking link inside its editor.
`Booking page` edits the public name and description. `Bookings` shows
upcoming, unconfirmed, past, and cancelled meetings; admins can confirm requests,
reschedule, or cancel them. Choose From/Through dates to load bookings (initially 30 days before and after today), then search by guest/title/email and filter by event type. Dates use your browser time zone; shorten the range if more than 5,000 bookings match.
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index ed51ba77af..6a1f660a01 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-3wWxSfUdJGk55nicYAy/nVi+qpCKARt95wotnoByosA=",
- "x86_64-linux": "sha256-Cynm6t+15CaXQh09cpOkwgjx5qJGVjOEiTusnyKRxIU="
+ "aarch64-darwin": "sha256-OD86QcxVQTz0qj222kCOqPnrtVQ5HQEO0KgaTlwuMv8=",
+ "x86_64-linux": "sha256-k2OoP7TgU5bi3P09+F1BAaN+wiKpNkp+HR6gWibOZr8="
}
}
diff --git a/package.json b/package.json
index b27efc4c3f..86f6f9fe6d 100644
--- a/package.json
+++ b/package.json
@@ -43,7 +43,8 @@
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
- "@tauri-apps/[email protected]": "apps/web/patches/@tauri-apps%[email protected]"
+ "@tauri-apps/[email protected]": "apps/web/patches/@tauri-apps%[email protected]",
+ "@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]"
},
"private": true,
"scripts": {
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 485ffa8f58..7bc176cba8 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -501,6 +501,11 @@ 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_management_tool_context: ai_tools::build_booking_management_tool_context(
+ macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
+ "test-internal-api-key".to_string(),
+ macro_env::Environment::Local,
+ ),
booking_link_tool_context: ai_tools::build_booking_link_tool_context(
pool.clone(),
macro_env::Environment::Local,
diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rs
index 1b400c5984..392bb76563 100644
--- a/services/document_cognition_service/src/server.rs
+++ b/services/document_cognition_service/src/server.rs
@@ -743,6 +743,11 @@ pub async fn run() -> anyhow::Result<()> {
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ booking_management_tool_context: ai_tools::build_booking_management_tool_context(
+ CalendarServiceUrl::new()?,
+ internal_api_key.clone(),
+ config.environment,
+ ),
booking_link_tool_context: ai_tools::build_booking_link_tool_context(
db.clone(),
config.environment,
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 84ed33aaed..8422a13306 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -542,6 +542,11 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
properties_tool_context,
email_tool_context,
call_tool_context,
+ booking_management_tool_context: ai_tools::build_booking_management_tool_context(
+ CalendarServiceUrl::new()?,
+ config.internal_api_key.to_string(),
+ config.environment,
+ ),
booking_link_tool_context: ai_tools::build_booking_link_tool_context(
db.clone(),
config.environment,