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.

fix(booking): confirm link details in conversation (#7667)

Wolf Mermelsteine9dd15e669cc
diff --git a/apps/docs/AI/mcp/tools/create-booking-link.mdx b/apps/docs/AI/mcp/tools/create-booking-link.mdx
index d9c8c41efc..1a2258bbaa 100644
--- a/apps/docs/AI/mcp/tools/create-booking-link.mdx
+++ b/apps/docs/AI/mcp/tools/create-booking-link.mdx
@@ -6,11 +6,12 @@ description: >-
# CreateBookingLink
-Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
-| `teamId` | string | No | Existing Macro team ID, or null for a personal booking link. |
+| `teamId` | string | No | Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link. |
| `draft` | BookingLinkDraft | Yes | Complete proposal reviewed and validated before saving. |
+| `userConfirmation` | string | Yes | The user's reply approving the specific proposal you already showed them, quoted verbatim. Never use their original request, paraphrase their reply, or invent approval. |
diff --git a/apps/docs/AI/mcp/tools/edit-booking-link.mdx b/apps/docs/AI/mcp/tools/edit-booking-link.mdx
index bcba3a15cc..ab9ca122cb 100644
--- a/apps/docs/AI/mcp/tools/edit-booking-link.mdx
+++ b/apps/docs/AI/mcp/tools/edit-booking-link.mdx
@@ -6,13 +6,14 @@ description: >-
# EditBookingLink
-Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
-| `teamId` | string | No | Existing Macro team ID, or null for a personal booking link. |
+| `teamId` | string | No | Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link. |
| `eventTypeId` | string | Yes | Existing link identity returned by ListBookingLinks. |
| `expectedRevision` | integer | Yes | Revision returned by ListBookingLinks; guards against concurrent settings changes. |
| `draft` | BookingLinkDraft | Yes | Complete proposal reviewed and validated before saving. |
+| `userConfirmation` | string | Yes | The user's reply approving the specific proposal you already showed them, quoted verbatim. Never use their original request, paraphrase their reply, or invent approval. |
diff --git a/apps/web/scripts/generate-dcs-tools.ts b/apps/web/scripts/generate-dcs-tools.ts
index 0bcb049ad3..23a0dd98bc 100644
--- a/apps/web/scripts/generate-dcs-tools.ts
+++ b/apps/web/scripts/generate-dcs-tools.ts
@@ -192,6 +192,7 @@ async function generateToolsFile(schema: FrontendSchemas) {
import type { ResultError } from '@core/util/result';
import { err, ok, type Result } from 'neverthrow';
+import { bookingLinkHistory } from '../../booking-link-history';
import * as schemas from './schemas';
import type * as types from './types';
@@ -247,7 +248,7 @@ function deserializeTool<T extends NamedTool>(
return err([{ code: 'not_found', message: \`tool name not found \${tool.name}\` }]);
}
const parser = toolParserMap[tool.name as ToolName];
- const maybeToolCall = parser[direction].safeParse(tool.json);
+ const maybeToolCall = parser[direction].safeParse(bookingLinkHistory(tool.name, direction, tool.json));
if (maybeToolCall.success) {
return ok({
id: tool.id,
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
index 944b4aa06a..57b2880de6 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
@@ -425,6 +425,21 @@ describe('ElicitationPart', () => {
schema: emptySchema,
});
+ it.each(['CreateBookingLink', 'EditBookingLink'])(
+ 'dismisses legacy %s requests without exposing IDs or a form',
+ (tool) => {
+ const request = review(tool, { teamId: 'internal-team-id', draft: {} });
+ pending = { ...live(), request };
+ const view = render(() => (
+ <ElicitationPart turn={0} part={part({ request })} />
+ ));
+ expect(view.queryByTestId('form')).toBeNull();
+ expect(view.queryByText('internal-team-id')).toBeNull();
+ fireEvent.click(view.getByRole('button', { name: 'Dismiss request' }));
+ expect(respond).toHaveBeenCalledWith({ action: 'decline' });
+ }
+ );
+
it("opens the tool's own composer, and Create answers with the whole draft", () => {
const request = review('CreateCalendarEvent', eventDraft);
pending = { ...live(), request };
diff --git a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
index 11dd80328c..b30224fc31 100644
--- a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
+++ b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
@@ -1,5 +1,3 @@
-import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
-import { BookingDraftComposer } from '@core/component/AI/component/tool/booking-link/DraftComposer';
/**
* The live controls for a question the agent is waiting on, shared by the
* session's card and the channel's Magic Chip: a form's fields and Submit,
@@ -319,6 +317,14 @@ export function parseDraftedTool(
request: UserToolRequest,
toolCall: string
): DraftedTool | undefined {
+ // Old sessions may still contain a booking review. Keep its internal IDs out
+ // of the generic form and let the user dismiss it to resume the conversation.
+ if (
+ request.tool === 'CreateBookingLink' ||
+ request.tool === 'EditBookingLink'
+ ) {
+ return { name: request.tool, data: request.draft };
+ }
const call = deserializeToolCall({
id: toolCall,
name: request.tool,
@@ -362,10 +368,20 @@ export function UserToolComposer(props: {
props.tool.name === 'EditBookingLink'
}
>
- <BookingDraftComposer
- initialData={props.tool.data as BookingLinkArgs}
- sink={sink<BookingLinkArgs>()}
- />
+ <div class="flex flex-col items-start gap-2 text-sm text-ink-muted">
+ <p>
+ Booking links are now confirmed in conversation. Dismiss this older
+ request and ask the agent to summarize the details.
+ </p>
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={locked()}
+ onClick={() => void props.review.respond({ action: 'decline' })}
+ >
+ Dismiss request
+ </Button>
+ </div>
</Match>
<Match when={props.tool.name === 'CreateCalendarEvent'}>
<CalendarDraftComposer
diff --git a/apps/web/src/features/scheduling/browser-test/booking-ai.html b/apps/web/src/features/scheduling/browser-test/booking-ai.html
deleted file mode 100644
index 974d47dc5f..0000000000
--- a/apps/web/src/features/scheduling/browser-test/booking-ai.html
+++ /dev/null
@@ -1 +0,0 @@
-<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Booking AI review QA</title></head><body><div id="root"></div><script type="module" src="./booking-ai.tsx"></script></body></html>
diff --git a/apps/web/src/features/scheduling/browser-test/booking-ai.tsx b/apps/web/src/features/scheduling/browser-test/booking-ai.tsx
deleted file mode 100644
index ad73f7c02d..0000000000
--- a/apps/web/src/features/scheduling/browser-test/booking-ai.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import '../../../index.css';
-import '@fontsource-variable/inter';
-import { createSignal, onMount, Show } from 'solid-js';
-import { render } from 'solid-js/web';
-import { createElicitationReviewSink } from '../../block-agent/state/elicitation-review-sink';
-import { macroLightTheme } from '../../theme/themes/macro-light';
-import { themeCssVars } from '../../theme/utils/themeColorTokens';
-import { BookingLinkDraftComposer } from '../components/booking-link-draft-composer';
-import type { BookingLinkArgs } from '../core/booking-link';
-import { newEventType, newSchedule } from '../core/types';
-
-function Fixture() {
- onMount(() => {
- for (const [key, value] of Object.entries(themeCssVars(macroLightTheme)))
- document.documentElement.style.setProperty(key, value);
- document.documentElement.style.colorScheme = 'light';
- });
- const schedule = newSchedule('America/New_York');
- const { id: _scheduleId, ...hours } = schedule;
- const {
- id: _eventId,
- scheduleId: _sid,
- ...details
- } = newEventType(schedule.id, ['macro|[email protected]'], false);
- const initial: BookingLinkArgs = {
- teamId: null,
- draft: {
- event: { ...details, title: 'Intro call', slug: 'intro', enabled: true },
- schedule: hours,
- },
- };
- const [draft, setDraft] = createSignal<BookingLinkArgs>();
- const [result, setResult] = createSignal('');
- const [fail, setFail] = createSignal(false);
- const [reviewCount, setReviewCount] = createSignal(0);
- const sink = createElicitationReviewSink<BookingLinkArgs>({
- canAnswer: () => true,
- respond: async (answer) => {
- if (fail())
- throw new Error(
- 'Configuration changed. Refresh and review the latest booking link.'
- );
- setReviewCount((count) => count + 1);
- setResult(JSON.stringify(answer, null, 2));
- setDraft(undefined);
- return true;
- },
- });
- return (
- <main class="h-screen overflow-auto bg-panel p-2 text-ink sm:p-6">
- <div class="mx-auto flex max-w-3xl flex-col gap-3">
- <h1 class="text-xl font-semibold">Booking link review</h1>
- <p>
- Isolated QA fixture. Decisions use the agent elicitation sink; no
- hosted data or invitations.
- </p>
- <div class="flex flex-wrap gap-4">
- <button
- onClick={() => {
- setDraft(undefined);
- queueMicrotask(() => setDraft(structuredClone(initial)));
- }}
- >
- New booking link
- </button>
- <button
- onClick={() => {
- setDraft(undefined);
- queueMicrotask(() =>
- setDraft({
- ...structuredClone(initial),
- eventTypeId: crypto.randomUUID(),
- expectedRevision: 7,
- })
- );
- }}
- >
- Edit booking link
- </button>
- <label>
- <input
- type="checkbox"
- checked={fail()}
- onChange={(event) => setFail(event.currentTarget.checked)}
- />
- Simulate save error
- </label>
- </div>
- <Show when={draft()} keyed>
- {(value) => (
- <BookingLinkDraftComposer
- initialData={value}
- sink={sink}
- members={[]}
- />
- )}
- </Show>
- <output aria-label="Review count">{reviewCount()}</output>
- <pre
- class="overflow-auto whitespace-pre-wrap break-all"
- aria-label="Review result"
- >
- {result()}
- </pre>
- </div>
- </main>
- );
-}
-render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx b/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx
deleted file mode 100644
index a8500c4cf8..0000000000
--- a/apps/web/src/features/scheduling/components/booking-link-draft-composer.test.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import {
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
-} from '@solidjs/testing-library';
-import { afterEach, expect, it, vi } from 'vitest';
-import type { BookingLinkArgs } from '../core/booking-link';
-import { newEventType, newSchedule } from '../core/types';
-import { BookingLinkDraftComposer } from './booking-link-draft-composer';
-
-afterEach(cleanup);
-function fixture(execute = vi.fn(async (_args: BookingLinkArgs) => true)) {
- const schedule = newSchedule('America/New_York');
- const event = {
- ...newEventType(schedule.id, ['macro|[email protected]'], false),
- title: 'Intro',
- slug: 'intro',
- };
- const reject = vi.fn(async () => true);
- render(() => (
- <BookingLinkDraftComposer
- initialData={{ draft: { event, schedule } }}
- members={[]}
- sink={{
- canAct: () => true,
- lockedNotice: () => undefined,
- onExecute: execute,
- onReject: reject,
- }}
- />
- ));
- return { execute, reject };
-}
-it('submits edited details and hours together exactly once', async () => {
- const { execute } = fixture();
- fireEvent.input(screen.getByLabelText('Title'), {
- target: { value: 'Discovery' },
- });
- fireEvent.input(screen.getByLabelText('Monday start 1'), {
- target: { value: '10:00' },
- });
- fireEvent.click(
- screen.getAllByRole('button', { name: 'Create booking link' })[0]
- );
- await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
- expect(execute.mock.calls[0][0].draft.event.title).toBe('Discovery');
- expect(
- execute.mock.calls[0][0].draft.schedule.weekly[1].windows[0].start
- ).toBe('10:00');
- fireEvent.click(
- screen.getAllByRole('button', { name: 'Create booking link' })[0]
- );
- expect(execute).toHaveBeenCalledTimes(1);
-});
-it('cancels without executing the draft', async () => {
- const { execute, reject } = fixture();
- fireEvent.click(screen.getByRole('button', { name: 'Cancel review' }));
- await waitFor(() => expect(reject).toHaveBeenCalledTimes(1));
- expect(execute).not.toHaveBeenCalled();
-});
-it('keeps the edited draft usable after an execution failure', async () => {
- const execute = vi.fn(async () => {
- throw new Error('Configuration changed. Refresh and try again.');
- });
- fixture(execute);
- fireEvent.input(screen.getByLabelText('Title'), {
- target: { value: 'Retained edit' },
- });
- fireEvent.click(
- screen.getAllByRole('button', { name: 'Create booking link' })[0]
- );
- expect((await screen.findByRole('alert')).textContent).toContain(
- 'Configuration changed'
- );
- expect((screen.getByLabelText('Title') as HTMLInputElement).value).toBe(
- 'Retained edit'
- );
-});
-
-it('allows an identical create retry even when the saved slug is already listed', async () => {
- const schedule = newSchedule('UTC');
- const event = {
- ...newEventType(schedule.id, ['macro|[email protected]'], false),
- title: 'Intro',
- slug: 'intro',
- };
- const execute = vi.fn(async (_args: BookingLinkArgs) => true);
- render(() => (
- <BookingLinkDraftComposer
- initialData={{ draft: { event, schedule } }}
- members={[]}
- events={[event]}
- sink={{
- canAct: () => true,
- lockedNotice: () => undefined,
- onExecute: execute,
- onReject: async () => true,
- }}
- />
- ));
- fireEvent.click(
- screen.getAllByRole('button', { name: 'Create booking link' })[0]
- );
- await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
-});
-it('lets the user repair incomplete availability and its name in the review', async () => {
- const schedule = { ...newSchedule('UTC'), name: '', weekly: [] };
- const event = {
- ...newEventType(schedule.id, ['macro|[email protected]'], false),
- title: 'Intro',
- slug: 'intro',
- };
- const execute = vi.fn(async (_args: BookingLinkArgs) => true);
- render(() => (
- <BookingLinkDraftComposer
- initialData={{ draft: { event, schedule } }}
- members={[]}
- sink={{
- canAct: () => true,
- lockedNotice: () => undefined,
- onExecute: execute,
- onReject: async () => true,
- }}
- />
- ));
- fireEvent.input(screen.getByLabelText('Availability name'), {
- target: { value: 'Repaired hours' },
- });
- fireEvent.click(
- screen.getAllByRole('button', { name: 'Create booking link' })[0]
- );
- await waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
- expect(execute.mock.calls[0][0].draft.schedule.weekly).toHaveLength(7);
- expect(execute.mock.calls[0][0].draft.schedule.name).toBe('Repaired hours');
-});
diff --git a/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx b/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx
deleted file mode 100644
index 6f0bbd4caf..0000000000
--- a/apps/web/src/features/scheduling/components/booking-link-draft-composer.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import type { UserToolReviewSink } from '@core/component/AI/component/tool/user-tool-review';
-import { createSignal, onCleanup, Show } from 'solid-js';
-import {
- type BookingLinkArgs,
- editableBookingWeek,
-} from '../core/booking-link';
-import {
- type AvailabilitySchedule,
- type EventType,
- type SchedulingMember,
- validateSchedule,
-} from '../core/types';
-import { EventEditor } from './event-editor';
-import { Field, TextInput } from './fields';
-import { ScheduleFields } from './schedule-editor';
-
-/** One review form shared by chat and agent elicitation, using the normal booking controls. */
-export function BookingLinkDraftComposer(props: {
- initialData: BookingLinkArgs;
- sink: UserToolReviewSink<BookingLinkArgs>;
- members: SchedulingMember[];
- events?: EventType[];
-}) {
- // These identities only connect the local controls. The domain assigns persisted IDs.
- const scheduleId = crypto.randomUUID();
- const eventId =
- 'eventTypeId' in props.initialData
- ? props.initialData.eventTypeId
- : crypto.randomUUID();
- const [schedule, setSchedule] = createSignal<AvailabilitySchedule>({
- ...props.initialData.draft.schedule,
- weekly: editableBookingWeek(props.initialData.draft.schedule.weekly),
- id: scheduleId,
- });
- const [event, setEvent] = createSignal<EventType>({
- ...props.initialData.draft.event,
- dailyLimit: props.initialData.draft.event.dailyLimit ?? null,
- id: eventId,
- scheduleId,
- });
- const [pending, setPending] = createSignal(false);
- const [finished, setFinished] = createSignal(false);
- const [error, setError] = createSignal('');
- const locked = () => pending() || finished() || !props.sink.canAct();
- const args = (nextEvent = event()): BookingLinkArgs => {
- const { id: _eventId, scheduleId: _scheduleId, ...eventDraft } = nextEvent;
- const { id: _id, ...scheduleDraft } = schedule();
- return {
- ...props.initialData,
- draft: { event: eventDraft, schedule: scheduleDraft },
- };
- };
- const changeSchedule = (
- update: (current: AvailabilitySchedule) => AvailabilitySchedule
- ) => {
- if (locked()) return;
- setSchedule(update);
- props.sink.onEdit?.(args());
- };
- const decide = async (nextEvent?: EventType) => {
- if (locked()) return;
- setError('');
- if (nextEvent) {
- const message = validateSchedule(schedule());
- if (message) {
- setError(message);
- return;
- }
- }
- setPending(true);
- try {
- const done = nextEvent
- ? await props.sink.onExecute(args(nextEvent))
- : await props.sink.onReject();
- setFinished(done);
- if (!done)
- setError(
- 'Could not finish this review. Your edits are preserved; try again.'
- );
- } catch (cause) {
- setError(
- cause instanceof Error
- ? cause.message
- : 'Could not save the booking link. Try again.'
- );
- } finally {
- setPending(false);
- }
- };
- onCleanup(() => props.sink.onDispose?.());
- return (
- <div
- data-booking-link-composer
- class="max-h-[min(80dvh,52rem)] min-w-0 overflow-y-auto overscroll-contain rounded-xl border border-edge-muted bg-panel p-3 text-ink sm:p-4"
- >
- <p class="mb-4 text-sm text-ink-muted">
- Review your booking link. Changes to availability apply only to this
- link. No invitations are sent until a guest books.
- </p>
- <Show when={props.sink.lockedNotice()}>
- {(notice) => <p class="mb-3 text-sm text-ink-muted">{notice()}</p>}
- </Show>
- <Show when={error()}>
- <p role="alert" class="mb-3 text-sm text-failure">
- {error()}
- </p>
- </Show>
- <fieldset
- disabled={locked()}
- inert={locked()}
- class="min-w-0 disabled:opacity-60"
- >
- <EventEditor
- event={event()}
- events={
- 'eventTypeId' in props.initialData ? (props.events ?? []) : []
- }
- schedules={[schedule()]}
- members={props.members}
- team={!!props.initialData.teamId}
- saving={pending()}
- cancelEditingLabel="Cancel review"
- submitLabel={
- 'eventTypeId' in props.initialData
- ? 'Save booking link'
- : 'Create booking link'
- }
- onChange={(value) => {
- if (locked()) return;
- setEvent(value);
- props.sink.onEdit?.(args(value));
- }}
- onSave={(value) => decide(value)}
- onCancel={() => void decide()}
- availability={
- <div class="flex min-w-0 flex-col gap-5">
- <Field label="Availability name">
- <TextInput
- required
- value={schedule().name}
- onInput={(event) => {
- const name = event.currentTarget.value;
- changeSchedule((current) => ({ ...current, name }));
- }}
- />
- </Field>
- <ScheduleFields schedule={schedule()} onChange={changeSchedule} />
- </div>
- }
- />
- </fieldset>
- </div>
- );
-}
diff --git a/apps/web/src/features/scheduling/core/booking-link.ts b/apps/web/src/features/scheduling/core/booking-link.ts
deleted file mode 100644
index 9c9a7ebb19..0000000000
--- a/apps/web/src/features/scheduling/core/booking-link.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type {
- CreateBookingLink,
- EditBookingLink,
-} from '@service-cognition/generated/tools/types';
-
-export type BookingLinkArgs = CreateBookingLink | EditBookingLink;
-
-/** Complete the editable week; retain duplicate-day windows so validation can flag overlaps. */
-export function editableBookingWeek(
- weekly: BookingLinkArgs['draft']['schedule']['weekly']
-) {
- return Array.from({ length: 7 }, (_, day) => ({
- day,
- windows: weekly
- .filter((entry) => entry.day === day)
- .flatMap((entry) => entry.windows),
- }));
-}
diff --git a/apps/web/src/features/scheduling/queries/booking-link-review.ts b/apps/web/src/features/scheduling/queries/booking-link-review.ts
deleted file mode 100644
index de5406c394..0000000000
--- a/apps/web/src/features/scheduling/queries/booking-link-review.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { queryClient } from '@queries/client';
-import { cognitionApiServiceClient } from '@service-cognition/client';
-import type { BookingLinkArgs } from '../core/booking-link';
-import { schedulingKeys } from './keys';
-
-export type BookingReviewIdentity = {
- chat_id: string;
- messageId: string;
- toolCallId: string;
-};
-export const executeBookingReview = (
- identity: BookingReviewIdentity,
- args: BookingLinkArgs
-) =>
- cognitionApiServiceClient.callTool<'CreateBookingLink' | 'EditBookingLink'>({
- ...identity,
- args,
- });
-export const persistBookingReview = (
- identity: BookingReviewIdentity,
- args: BookingLinkArgs
-) =>
- cognitionApiServiceClient.updateToolCall<
- 'CreateBookingLink' | 'EditBookingLink'
- >({ ...identity, args });
-export const rejectBookingReview = (identity: BookingReviewIdentity) =>
- cognitionApiServiceClient.rejectToolCall(identity);
-export const invalidateBookingLinks = () =>
- queryClient.invalidateQueries({ queryKey: schedulingKeys._def });
diff --git a/apps/web/src/features/scheduling/vitest.config.ts b/apps/web/src/features/scheduling/vitest.config.ts
index 51dbde7591..30b28c40ce 100644
--- a/apps/web/src/features/scheduling/vitest.config.ts
+++ b/apps/web/src/features/scheduling/vitest.config.ts
@@ -18,7 +18,6 @@ export default defineConfig({
include: [
'src/features/scheduling/**/*.{test,spec}.{ts,tsx}',
'src/lib/core/component/AI/component/tool/BookingLinks.test.tsx',
- 'src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx',
],
},
});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx
index be60eaada7..e901425656 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.test.tsx
@@ -1,12 +1,13 @@
import { newEventType, newSchedule } from '@app/features/scheduling/core/types';
+import {
+ deserializeToolCall,
+ deserializeToolResponse,
+} from '@service-cognition/generated/tools/tool';
import { cleanup, render } from '@solidjs/testing-library';
-import { afterEach, expect, it, vi } from 'vitest';
+import { afterEach, expect, it } from 'vitest';
import { createBookingLinkHandler } from './BookingLinks';
import { ToolErrorContext } from './ToolRenderer';
-vi.mock('./booking-link/ChatCompose', () => ({
- BookingChatCompose: () => <div>Editable booking review</div>,
-}));
afterEach(cleanup);
const schedule = newSchedule('UTC');
const draft = {
@@ -21,7 +22,7 @@ const context = {
tool: {
id: 'booking-call',
name: 'CreateBookingLink' as const,
- data: { draft },
+ data: { draft, userConfirmation: 'Yes, create it.' },
},
chat_id: 'chat',
message_id: 'message',
@@ -29,16 +30,15 @@ const context = {
isComplete: true,
renderContext: { isStreaming: false, followedBy: () => false },
};
-it('restores the editable review when a failed persisted response is remounted', () => {
+it('never opens an editable review when saving fails', () => {
const view = render(() => (
<ToolErrorContext.Provider value={() => 'failed'}>
<createBookingLinkHandler.render {...context} />
</ToolErrorContext.Provider>
));
- expect(view.getByText('Editable booking review')).toBeTruthy();
- expect(
- view.getByText('The previous save failed. Review your draft and try again.')
- ).toBeTruthy();
+ expect(view.queryByRole('textbox')).toBeNull();
+ expect(view.queryByText('Editable booking review')).toBeNull();
+ expect(view.getByText('Create booking link')).toBeTruthy();
});
it('shows the actual saved URL and paused state after execution', () => {
const view = render(() => (
@@ -48,13 +48,11 @@ it('shows the actual saved URL and paused state after execution', () => {
id: 'booking-call',
name: 'CreateBookingLink',
data: {
- UserAction: {
- profileId: crypto.randomUUID(),
- eventTypeId: crypto.randomUUID(),
- revision: 1,
- draft,
- url: 'https://macro.com/app/book/profile/intro',
- },
+ profileId: crypto.randomUUID(),
+ eventTypeId: crypto.randomUUID(),
+ revision: 1,
+ draft,
+ url: 'https://macro.com/app/book/profile/intro',
},
}}
/>
@@ -64,3 +62,32 @@ it('shows the actual saved URL and paused state after execution', () => {
);
expect(view.getByText(/Paused/)).toBeTruthy();
});
+
+it('keeps historical booking results readable without inventing confirmation', () => {
+ const { id: _eventId, scheduleId: _scheduleId, ...event } = draft.event;
+ const { id: _id, ...schedule } = draft.schedule;
+ const oldDraft = { event, schedule };
+ const call = deserializeToolCall({
+ id: 'old',
+ name: 'CreateBookingLink',
+ json: { draft: oldDraft },
+ });
+ expect(call.isOk()).toBe(true);
+ if (call.isOk() && call.value.name === 'CreateBookingLink') {
+ expect(call.value.data).toMatchObject({ userConfirmation: '' });
+ }
+ const saved = {
+ profileId: crypto.randomUUID(),
+ eventTypeId: crypto.randomUUID(),
+ revision: 1,
+ draft: oldDraft,
+ url: 'https://macro.com/app/book/profile/intro',
+ };
+ const response = deserializeToolResponse({
+ id: 'old',
+ name: 'CreateBookingLink',
+ json: { UserAction: saved },
+ });
+ expect(response.isOk()).toBe(true);
+ if (response.isOk()) expect(response.value.data).toEqual(saved);
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx
index f3ff5163e3..90c2cf6d42 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/BookingLinks.tsx
@@ -1,14 +1,9 @@
import Link from '@phosphor-icons/core/regular/link.svg';
import type { BookingLinkResult } from '@service-cognition/generated/tools/types';
-import { createSignal, For, Match, Switch } from 'solid-js';
+import { createSignal, For } from 'solid-js';
import { BaseTool } from './BaseTool';
-import { BookingChatCompose } from './booking-link/ChatCompose';
import { Tool } from './Tool';
-import {
- createToolRenderer,
- type RenderContext,
- useToolError,
-} from './ToolRenderer';
+import { createToolRenderer, type RenderContext } from './ToolRenderer';
function LinkCard(props: {
label: string;
@@ -83,56 +78,18 @@ function mutationHandler(name: 'CreateBookingLink' | 'EditBookingLink') {
return createToolRenderer({
name,
render: (ctx) => {
- const response = () => ctx.response?.data;
- const error = () => useToolError();
- const saved = () => {
- const result = response();
- return typeof result === 'object' &&
- result !== null &&
- 'UserAction' in result
- ? result.UserAction
- : undefined;
- };
- const label =
- name === 'CreateBookingLink'
- ? 'Create booking link'
- : 'Edit booking link';
+ const saved = () => ctx.response?.data;
return (
- <Switch
- fallback={
- <LinkCard
- label={label}
- renderContext={ctx.renderContext}
- status={response() === 'Rejected' ? 'Cancelled' : undefined}
- />
+ <LinkCard
+ label={
+ name === 'CreateBookingLink'
+ ? 'Create booking link'
+ : 'Edit booking link'
}
- >
- <Match when={response() === 'PendingUserExecution' || error()}>
- <p class="text-sm text-ink-muted">
- {error()
- ? 'The previous save failed. Review your draft and try again.'
- : ''}
- </p>
- <BookingChatCompose
- name={name}
- chatId={ctx.chat_id}
- messageId={ctx.message_id}
- toolCallId={ctx.tool.id}
- initialData={ctx.tool.data}
- streamLocked={ctx.renderContext.isStreaming}
- />
- </Match>
- <Match when={saved()}>
- {(link) => (
- <LinkCard
- label={label}
- links={[link()]}
- status="Saved"
- renderContext={ctx.renderContext}
- />
- )}
- </Match>
- </Switch>
+ links={saved() ? [saved()!] : undefined}
+ status={saved() ? 'Saved' : undefined}
+ renderContext={ctx.renderContext}
+ />
);
},
});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx
deleted file mode 100644
index aaab87e7e2..0000000000
--- a/apps/web/src/lib/core/component/AI/component/tool/booking-link/ChatCompose.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
-import {
- executeBookingReview,
- invalidateBookingLinks,
- persistBookingReview,
- rejectBookingReview,
-} from '@app/features/scheduling/queries/booking-link-review';
-import { useChatContext } from '@core/component/AI/context';
-import { toast } from '@core/component/Toast/Toast';
-import { useChatQuery } from '@queries/chat';
-import { deserializeToolResponse } from '@service-cognition/generated/tools/tool';
-import { debounce } from '@solid-primitives/scheduled';
-import type { UserToolReviewSink } from '../user-tool-review';
-import { BookingDraftComposer } from './DraftComposer';
-
-/** Chat persists drafts and finishes the existing deferred tool call. */
-export function BookingChatCompose(props: {
- chatId: string;
- messageId: string;
- toolCallId: string;
- name: 'CreateBookingLink' | 'EditBookingLink';
- initialData: BookingLinkArgs;
- streamLocked: boolean;
-}) {
- const chat = useChatContext();
- const query = useChatQuery(() => props.chatId);
- const canAct = () =>
- query.isSuccess &&
- query.data.userAccessLevel === 'owner' &&
- !props.streamLocked;
- const identity = () => ({
- chat_id: props.chatId,
- messageId: props.messageId,
- toolCallId: props.toolCallId,
- });
- let latest: BookingLinkArgs | undefined;
- let queue = Promise.resolve();
- let finalized = false;
- const persist = () => {
- const args = latest;
- if (!args || finalized) return;
- const previous = queue;
- queue = (async () => {
- await previous;
- if (finalized) return;
- try {
- const result = await persistBookingReview(identity(), args);
- if (result.isErr()) toast.failure('Could not save booking draft');
- } catch {
- toast.failure('Could not save booking draft');
- }
- })();
- };
- const deferredPersist = debounce(persist, 200);
- function updateResponse(response: unknown, args?: BookingLinkArgs) {
- chat.setMessages((messages) =>
- messages.map((message) => {
- if (message.id !== props.messageId || !Array.isArray(message.content))
- return message;
- return {
- ...message,
- content: message.content.map((part) => {
- if (
- part.type === 'toolCallResponseJson' &&
- part.id === props.toolCallId
- )
- return { ...part, json: response };
- if (
- args &&
- part.type === 'toolCall' &&
- part.id === props.toolCallId
- )
- return { ...part, json: args };
- return part;
- }),
- };
- })
- );
- }
- const sink: UserToolReviewSink<BookingLinkArgs> = {
- canAct,
- lockedNotice: () =>
- props.streamLocked
- ? 'Waiting for the response to finish.'
- : query.isSuccess && query.data.userAccessLevel !== 'owner'
- ? 'Only the chat owner can finish this booking link.'
- : undefined,
- onEdit: (args) => {
- latest = args;
- deferredPersist();
- },
- onExecute: async (args) => {
- deferredPersist.clear();
- await queue;
- const result = await executeBookingReview(identity(), args);
- if (result.isErr())
- throw new Error('Could not save the booking link. Please try again.');
- const response = result.value;
- // Validate the result with the generated contract before presenting a saved link.
- const parsed = deserializeToolResponse({
- id: props.toolCallId,
- name: props.name,
- json: response,
- });
- if (
- parsed.isErr() ||
- typeof response !== 'object' ||
- response === null ||
- !('UserAction' in response)
- ) {
- const message =
- typeof response === 'object' &&
- response !== null &&
- 'error' in response &&
- typeof response.error === 'string'
- ? response.error
- : 'The booking link was not saved. Please try again.';
- throw new Error(message);
- }
- finalized = true;
- updateResponse(response, args);
- void invalidateBookingLinks();
- return true;
- },
- onReject: async () => {
- deferredPersist.clear();
- await queue;
- const result = await rejectBookingReview(identity());
- if (result.isErr())
- throw new Error('Could not cancel the review. Please try again.');
- finalized = true;
- updateResponse('Rejected');
- return true;
- },
- onDispose: () => {
- deferredPersist.clear();
- if (!finalized) persist();
- },
- };
- return <BookingDraftComposer initialData={props.initialData} sink={sink} />;
-}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx
deleted file mode 100644
index 7740f1c39f..0000000000
--- a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.test.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { newEventType, newSchedule } from '@app/features/scheduling/core/types';
-import { cleanup, render } from '@solidjs/testing-library';
-import { afterEach, expect, it, vi } from 'vitest';
-import { BookingDraftComposer } from './DraftComposer';
-
-vi.mock('@core/context/user', () => ({
- useUserId: () => () => 'macro|[email protected]',
-}));
-vi.mock('@queries/team/teams', () => ({
- useCurrentTeamQuery: () => ({ isSuccess: false, isError: false }),
-}));
-vi.mock('@app/features/scheduling/queries/source', () => ({
- useSchedulingProfileQuery: () => ({ isSuccess: false, isError: false }),
-}));
-vi.mock('@core/user', () => ({
- tryMacroId: (id: string) => id,
- getDisplayName: (id: string) => id,
- macroIdToEmail: (id: string) => id,
-}));
-afterEach(cleanup);
-it.each([undefined, '019a19f7-2a01-7c21-809e-fc6bfb9ef327'])(
- 'renders without treating unknown team membership as removal: %s',
- (teamId) => {
- const schedule = newSchedule('UTC');
- const event = {
- ...newEventType(schedule.id, ['macro|[email protected]'], !!teamId),
- title: 'Intro',
- slug: 'intro',
- };
- const view = render(() => (
- <BookingDraftComposer
- initialData={{ teamId, draft: { event, schedule } }}
- sink={{
- canAct: () => true,
- lockedNotice: () => undefined,
- onExecute: async () => true,
- onReject: async () => true,
- }}
- />
- ));
- expect(view.getByLabelText('Title')).toBeTruthy();
- expect(view.queryByText('Former team member')).toBeNull();
- expect(view.getByRole('button', { name: 'Cancel' })).toBeTruthy();
- }
-);
diff --git a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx
deleted file mode 100644
index 1af0de9d1e..0000000000
--- a/apps/web/src/lib/core/component/AI/component/tool/booking-link/DraftComposer.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { BookingLinkDraftComposer } from '@app/features/scheduling/components/booking-link-draft-composer';
-import type { BookingLinkArgs } from '@app/features/scheduling/core/booking-link';
-import { useSchedulingProfileQuery } from '@app/features/scheduling/queries/source';
-import { useUserId } from '@core/context/user';
-import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';
-import { useCurrentTeamQuery } from '@queries/team/teams';
-import { Button } from '@ui';
-import { Show, Suspense } from 'solid-js';
-import type { UserToolReviewSink } from '../user-tool-review';
-
-type Props = {
- initialData: BookingLinkArgs;
- sink: UserToolReviewSink<BookingLinkArgs>;
-};
-function Content(props: Props) {
- const user = useUserId();
- const profile = useSchedulingProfileQuery(() => ({
- id: props.initialData.teamId ?? user() ?? 'me',
- teamId: props.initialData.teamId ?? undefined,
- name: '',
- canEdit: true,
- }));
- const team = useCurrentTeamQuery(() => !!props.initialData.teamId);
- const members = () => {
- const data = team.isSuccess ? team.data : undefined;
- const roster =
- data && data.team.id === props.initialData.teamId
- ? data.members
- : props.initialData.draft.event.hosts.map((user_id) => ({ user_id }));
- return roster.map((member) => {
- const id = tryMacroId(member.user_id);
- return {
- id: member.user_id,
- name: id ? getDisplayName(id) : member.user_id,
- email: id ? macroIdToEmail(id) : member.user_id,
- };
- });
- };
- return (
- <>
- <Show
- when={profile.isError || (!!props.initialData.teamId && team.isError)}
- >
- <div role="status" class="mb-3 text-sm text-ink-muted">
- Could not load current booking settings. Your draft is preserved.
- <Button
- variant="ghost"
- onClick={() => {
- void profile.refetch();
- if (props.initialData.teamId) void team.refetch();
- }}
- >
- Retry loading
- </Button>
- </div>
- </Show>
- <BookingLinkDraftComposer
- {...props}
- members={members()}
- events={profile.isSuccess ? profile.data.eventTypes : []}
- />
- </>
- );
-}
-/** Local boundary prevents settings queries from suspending the transcript. */
-export function BookingDraftComposer(props: Props) {
- return (
- <Suspense
- fallback={<p class="p-4 text-ink-muted">Loading booking editor…</p>}
- >
- <Content {...props} />
- </Suspense>
- );
-}
diff --git a/apps/web/src/lib/service-clients/service-cognition/booking-link-history.ts b/apps/web/src/lib/service-clients/service-cognition/booking-link-history.ts
new file mode 100644
index 0000000000..bb0a7f712b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/booking-link-history.ts
@@ -0,0 +1,21 @@
+/** Read old booking transcripts without restoring the removed execution UI. */
+export function bookingLinkHistory(
+ name: string,
+ direction: 'call' | 'response',
+ json: unknown
+): unknown {
+ if (
+ (name !== 'CreateBookingLink' && name !== 'EditBookingLink') ||
+ typeof json !== 'object' ||
+ json === null
+ ) {
+ return json;
+ }
+ if (direction === 'response' && 'UserAction' in json) return json.UserAction;
+ if (direction === 'call' && !('userConfirmation' in json)) {
+ // Display only: empty confirmation cannot execute on the backend, and these
+ // tools no longer have a frontend execution path. Never fabricate approval.
+ return { ...json, userConfirmation: '' };
+ }
+ return json;
+}
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 215f37c29d..a1df0491b7 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
@@ -1635,119 +1635,93 @@ export const CreateBookingLink = z
.strict(),
})
.strict(),
+ userConfirmation: z.string(),
})
.strict();
-export const UserToolResponseForBookingLinkResult = z
- .any()
- .superRefine((x, ctx) => {
- const schemas = [
- z.literal('PendingUserExecution'),
- z.literal('Rejected'),
- z
+export const BookingLinkResult = z.object({
+ profileId: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ revision: z.number().int(),
+ draft: z
+ .object({
+ event: z
.object({
- UserAction: z.object({
- profileId: z.string().uuid(),
- eventTypeId: z.string().uuid(),
- revision: z.number().int(),
- draft: z
- .object({
- event: z
- .object({
- title: z.string(),
- slug: z.string(),
- description: z.string(),
- durationMinutes: z.number().int().gte(0).lte(65535),
- location: z.string(),
- googleMeet: z.boolean(),
- enabled: z.boolean(),
- mode: z.any().superRefine((x, ctx) => {
- const schemas = [
- z.literal('individual'),
- z.literal('collective'),
- z.literal('roundRobin'),
- ];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) =>
- result.error ? [...errors, result.error] : errors)(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
- hosts: z.array(z.string()),
- beforeMinutes: z.number().int().gte(0).lte(65535),
- afterMinutes: z.number().int().gte(0).lte(65535),
- noticeMinutes: z.number().int().gte(0).lte(65535),
- horizonDays: z.number().int().gte(0).lte(65535),
- intervalMinutes: z.number().int().gte(0).lte(65535),
- dailyLimit: z
- .union([z.number().int().gte(0).lte(65535), z.null()])
- .optional(),
- requiresConfirmation: z.boolean(),
- questions: z.array(
- z.object({
- id: z.string().uuid(),
- label: z.string(),
- required: z.boolean(),
- })
- ),
- })
- .strict(),
- schedule: z
- .object({
- name: z.string(),
- timeZone: z.string(),
- weekly: z.array(
- z.object({
- day: z.number().int().gte(0).lte(255),
- windows: z.array(
- z.object({ start: z.string(), end: z.string() })
- ),
- })
- ),
- overrides: z.array(
- z.object({
- date: z.string().date(),
- windows: z.array(
- z.object({ start: z.string(), end: z.string() })
- ),
- })
- ),
- })
- .strict(),
- })
- .strict(),
- url: z.string(),
+ title: z.string(),
+ slug: z.string(),
+ description: z.string(),
+ durationMinutes: z.number().int().gte(0).lte(65535),
+ location: z.string(),
+ googleMeet: z.boolean(),
+ enabled: z.boolean(),
+ mode: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('individual'),
+ z.literal('collective'),
+ z.literal('roundRobin'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
}),
+ hosts: z.array(z.string()),
+ beforeMinutes: z.number().int().gte(0).lte(65535),
+ afterMinutes: z.number().int().gte(0).lte(65535),
+ noticeMinutes: z.number().int().gte(0).lte(65535),
+ horizonDays: z.number().int().gte(0).lte(65535),
+ intervalMinutes: z.number().int().gte(0).lte(65535),
+ dailyLimit: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .optional(),
+ requiresConfirmation: z.boolean(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ label: z.string(),
+ required: z.boolean(),
+ })
+ ),
})
.strict(),
- ];
- 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',
- });
- }
- });
+ schedule: z
+ .object({
+ name: z.string(),
+ timeZone: z.string(),
+ weekly: z.array(
+ z.object({
+ day: z.number().int().gte(0).lte(255),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ overrides: z.array(
+ z.object({
+ date: z.string().date(),
+ windows: z.array(
+ z.object({ start: z.string(), end: z.string() })
+ ),
+ })
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ url: z.string(),
+});
export const CreateBot = z.object({
teamId: z.union([z.string().uuid(), z.null()]).optional(),
@@ -2740,6 +2714,7 @@ export const EditBookingLink = z
.strict(),
})
.strict(),
+ userConfirmation: z.string(),
})
.strict();
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 96ca4e12a2..0b7920cddf 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
@@ -4,6 +4,7 @@
import type { ResultError } from '@core/util/result';
import { err, ok, type Result } from 'neverthrow';
+import { bookingLinkHistory } from '../../booking-link-history';
import * as schemas from './schemas';
import type * as types from './types';
@@ -38,7 +39,7 @@ type ToolParserMap = {
};
CreateBookingLink: {
call: types.CreateBookingLink;
- response: types.UserToolResponseForBookingLinkResult;
+ response: types.BookingLinkResult;
};
CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
@@ -103,7 +104,7 @@ type ToolParserMap = {
};
EditBookingLink: {
call: types.EditBookingLink;
- response: types.UserToolResponseForBookingLinkResult;
+ response: types.BookingLinkResult;
};
EditDocument: {
call: types.EditDocument;
@@ -387,7 +388,7 @@ const toolParserMap = {
},
CreateBookingLink: {
call: schemas.CreateBookingLink,
- response: schemas.UserToolResponseForBookingLinkResult,
+ response: schemas.BookingLinkResult,
},
CreateBot: { call: schemas.CreateBot, response: schemas.CreateBotResponse },
CreateCalendarEvent: {
@@ -452,7 +453,7 @@ const toolParserMap = {
},
EditBookingLink: {
call: schemas.EditBookingLink,
- response: schemas.UserToolResponseForBookingLinkResult,
+ response: schemas.BookingLinkResult,
},
EditDocument: {
call: schemas.EditDocument,
@@ -777,7 +778,7 @@ type ToolDataMap = {
};
CreateBookingLink: {
call: types.CreateBookingLink;
- response: types.UserToolResponseForBookingLinkResult;
+ response: types.BookingLinkResult;
};
CreateBot: { call: types.CreateBot; response: types.CreateBotResponse };
CreateCalendarEvent: {
@@ -842,7 +843,7 @@ type ToolDataMap = {
};
EditBookingLink: {
call: types.EditBookingLink;
- response: types.UserToolResponseForBookingLinkResult;
+ response: types.BookingLinkResult;
};
EditDocument: {
call: types.EditDocument;
@@ -1114,7 +1115,9 @@ function deserializeTool<T extends NamedTool>(
]);
}
const parser = toolParserMap[tool.name as ToolName];
- const maybeToolCall = parser[direction].safeParse(tool.json);
+ const maybeToolCall = parser[direction].safeParse(
+ bookingLinkHistory(tool.name, direction, tool.json)
+ );
if (maybeToolCall.success) {
return ok({
id: tool.id,
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 62ee43c4f3..3ac99d9d8e 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
@@ -317,15 +317,6 @@ export type AgentSessionAuthor = 'user' | 'agent';
* Team host assignment policy.
*/
export type SchedulingMode = 'individual' | 'collective' | 'roundRobin';
-/**
- * User tools are pending until a user executes them
- */
-export type UserToolResponseForBookingLinkResult =
- | 'PendingUserExecution'
- | 'Rejected'
- | {
- UserAction: BookingLinkResult;
- };
/**
* The mutually exclusive time shape supplied to calendar tools.
*/
@@ -5154,14 +5145,19 @@ export interface SearchGotoAgentSession {
author: AgentSessionAuthor;
}
/**
- * Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+ * Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
*/
export interface CreateBookingLink {
/**
- * Existing Macro team ID, or null for a personal booking link.
+ * Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.
*/
teamId?: string | null;
draft: BookingLinkDraft;
+ /**
+ * The user's reply approving the specific proposal you already showed them, quoted verbatim.
+ * Never use their original request, paraphrase their reply, or invent approval.
+ */
+ userConfirmation: string;
}
/**
* Complete proposal reviewed and validated before saving.
@@ -6375,11 +6371,11 @@ export interface DisplayResultsResponse {
message: string;
}
/**
- * Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
+ * Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar.
*/
export interface EditBookingLink {
/**
- * Existing Macro team ID, or null for a personal booking link.
+ * Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.
*/
teamId?: string | null;
/**
@@ -6391,6 +6387,11 @@ export interface EditBookingLink {
*/
expectedRevision: number;
draft: BookingLinkDraft;
+ /**
+ * The user's reply approving the specific proposal you already showed them, quoted verbatim.
+ * Never use their original request, paraphrase their reply, or invent approval.
+ */
+ userConfirmation: string;
}
/**
* Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index 4240faa287..9e973cb2c3 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -429,7 +429,7 @@ fn every_eager_tool_exists() {
}
#[test]
-fn booking_link_mutations_only_defer_on_hosts_that_finish_reviews() {
+fn booking_link_mutations_execute_without_a_review_on_every_host() {
for host in [
AiHost::Chat,
AiHost::AgentSession,
@@ -440,10 +440,9 @@ fn booking_link_mutations_only_defer_on_hosts_that_finish_reviews() {
assert!(tools.tools.contains_key("ListBookingLinks"));
for name in ["CreateBookingLink", "EditBookingLink"] {
assert!(tools.tools.contains_key(name));
- assert_eq!(
- tools.user_tools.contains_key(name),
- matches!(host, AiHost::Chat | AiHost::AgentSession)
- );
+ assert!(!tools.user_tools.contains_key(name));
}
}
}
+
+mod booking_links;
diff --git a/crates/ai_tools/src/user_tool_review/test/booking_links.rs b/crates/ai_tools/src/test/booking_links.rs
similarity index 69%
rename from crates/ai_tools/src/user_tool_review/test/booking_links.rs
rename to crates/ai_tools/src/test/booking_links.rs
index 1cc1f0e2ba..72fecff9f2 100644
--- a/crates/ai_tools/src/user_tool_review/test/booking_links.rs
+++ b/crates/ai_tools/src/test/booking_links.rs
@@ -1,5 +1,12 @@
-//! Actual review -> edited tool execution -> PostgreSQL -> public booking HTTP API.
-use super::*;
+//! Confirmed tool execution -> PostgreSQL -> public booking HTTP API.
+use ai_toolset::RequestContext;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde_json::{Value, json};
+use std::sync::Arc;
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
use ai_toolset::ToolSet;
use calendar_scheduling::{
domain::{models::*, ports::*, service::Service},
@@ -73,57 +80,25 @@ fn args() -> Value {
"schedule":{"name":"Working hours", "timeZone":"UTC", "weekly":(0..7).map(|day| json!({"day":day, "windows":[{"start":"09:00", "end":"17:00"}]})).collect::<Vec<_>>(), "overrides":[]}
}})
}
-async fn review(
- context: Context,
- tool: &str,
- args: Value,
- outcome: ReviewOutcome,
-) -> FinishedUserTool {
- let tools = Arc::new(booking_link_toolset());
- let deferred = tools
- .try_tool_call(context.clone(), RequestContext::new(owner()), tool, &args)
+async fn execute(context: Context, tool: &str, args: Value) -> Result<Value, String> {
+ booking_link_toolset()
+ .try_tool_call(context, RequestContext::new(owner()), tool, &args)
.await
- .unwrap()
- .unwrap();
- assert_eq!(deferred, json!("PendingUserExecution"));
- let reviewer = Arc::new(Scripted {
- asked: Mutex::new(vec![]),
- answer: Ok(outcome),
- });
- user_tool_finisher(tools, context, owner(), reviewer, CancellationToken::new())(
- PendingUserTool {
- tool_name: tool.into(),
- tool_call_id: "booking-link-call".into(),
- args,
- },
- )
- .await
- .unwrap()
-}
-fn accept(args: Value) -> ReviewOutcome {
- ReviewOutcome::Accepted(BTreeMap::from([(
- DRAFT_FIELD.into(),
- Value::String(args.to_string()),
- )]))
-}
-fn saved(result: FinishedUserTool) -> Value {
- let FinishedUserTool::Result(value) = result else {
- panic!("expected saved link: {result:?}")
- };
- value["UserAction"].clone()
+ .map_err(|error| error.to_string())?
+ .map_err(|error| error.to_string())
}
#[sqlx::test(migrations = false)]
-async fn edited_review_is_saved_and_bookable_without_touching_other_links(pool: sqlx::PgPool) {
+async fn confirmed_booking_is_saved_and_bookable_without_touching_other_links(pool: sqlx::PgPool) {
sqlx::raw_sql("CREATE TABLE \"User\" (id text PRIMARY KEY); CREATE TABLE team (id uuid PRIMARY KEY); INSERT INTO \"User\" VALUES ('macro|[email protected]');").execute(&pool).await.unwrap();
sqlx::raw_sql(include_str!(
- "../../../../macro_db_client/migrations/20260918164303_calendar_scheduling.sql"
+ "../../../macro_db_client/migrations/20260918164303_calendar_scheduling.sql"
))
.execute(&pool)
.await
.unwrap();
sqlx::raw_sql(include_str!(
- "../../../../macro_db_client/migrations/20260918175703_scheduling_recovery.sql"
+ "../../../macro_db_client/migrations/20260918175703_scheduling_recovery.sql"
))
.execute(&pool)
.await
@@ -137,8 +112,16 @@ async fn edited_review_is_saved_and_bookable_without_touching_other_links(pool:
service: service.clone(),
public_origin: "https://booking.example.test".into(),
};
- for outcome in [ReviewOutcome::Declined, ReviewOutcome::Cancelled] {
- review(context.clone(), "CreateBookingLink", args(), outcome).await;
+ for confirmation in [None, Some(" ")] {
+ let mut unconfirmed = args();
+ if let Some(quote) = confirmation {
+ unconfirmed["userConfirmation"] = json!(quote);
+ }
+ assert!(
+ execute(context.clone(), "CreateBookingLink", unconfirmed)
+ .await
+ .is_err()
+ );
assert!(
service
.settings(owner().as_ref(), None)
@@ -148,18 +131,16 @@ async fn edited_review_is_saved_and_bookable_without_touching_other_links(pool:
.is_empty()
);
}
- let mut invalid = args();
+ let mut edited = args();
+ edited["userConfirmation"] = json!("Yes, create that booking link.");
+ edited["draft"]["event"]["title"] = json!("Reviewed title");
+ let mut invalid = edited.clone();
invalid["draft"]["event"]["durationMinutes"] = json!(0);
- assert!(matches!(
- review(
- context.clone(),
- "CreateBookingLink",
- args(),
- accept(invalid)
- )
- .await,
- FinishedUserTool::Error(_)
- ));
+ assert!(
+ execute(context.clone(), "CreateBookingLink", invalid)
+ .await
+ .is_err()
+ );
assert!(
service
.settings(owner().as_ref(), None)
@@ -168,65 +149,34 @@ async fn edited_review_is_saved_and_bookable_without_touching_other_links(pool:
.event_types
.is_empty()
);
- let mut edited = args();
- edited["draft"]["event"]["title"] = json!("Reviewed title");
- let first = saved(
- review(
- context.clone(),
- "CreateBookingLink",
- args(),
- accept(edited.clone()),
- )
- .await,
- );
+ let first = execute(context.clone(), "CreateBookingLink", edited.clone())
+ .await
+ .unwrap();
assert_eq!(first["draft"]["event"]["title"], "Reviewed title");
- let retry = saved(
- review(
- context.clone(),
- "CreateBookingLink",
- edited.clone(),
- accept(edited.clone()),
- )
- .await,
- );
+ let retry = execute(context.clone(), "CreateBookingLink", edited.clone())
+ .await
+ .unwrap();
assert_eq!(first, retry);
- let mut other = args();
+ let mut other = edited.clone();
other["draft"]["event"]["slug"] = json!("other");
- let second = saved(
- review(
- context.clone(),
- "CreateBookingLink",
- other.clone(),
- accept(other),
- )
- .await,
- );
+ let second = execute(context.clone(), "CreateBookingLink", other)
+ .await
+ .unwrap();
let before = service.settings(owner().as_ref(), None).await.unwrap();
- let edit = json!({"teamId":null, "eventTypeId":first["eventTypeId"], "expectedRevision":second["revision"], "draft":edited["draft"]});
+ let edit = json!({"teamId":null, "eventTypeId":first["eventTypeId"], "expectedRevision":second["revision"], "draft":edited["draft"], "userConfirmation":"Yes, change the duration to 45 minutes."});
let mut accepted = edit.clone();
accepted["draft"]["event"]["durationMinutes"] = json!(45);
- let updated = saved(
- review(
- context.clone(),
- "EditBookingLink",
- edit.clone(),
- accept(accepted),
- )
- .await,
- );
+ let updated = execute(context.clone(), "EditBookingLink", accepted)
+ .await
+ .unwrap();
assert_eq!(updated["eventTypeId"], first["eventTypeId"]);
let after = service.settings(owner().as_ref(), None).await.unwrap();
assert_eq!(before.event_types[1], after.event_types[1]);
- assert!(matches!(
- review(
- context.clone(),
- "EditBookingLink",
- edit.clone(),
- accept(edit)
- )
- .await,
- FinishedUserTool::Error(_)
- ));
+ assert!(
+ execute(context.clone(), "EditBookingLink", edit)
+ .await
+ .is_err()
+ );
let app: axum::Router = router(RouterState::new(
service.clone(),
MacroAuthorizationState::new(Arc::new(NoAuth)),
diff --git a/crates/ai_tools/src/user_tool_review/test.rs b/crates/ai_tools/src/user_tool_review/test.rs
index 0878ca9f61..01a40fa4f5 100644
--- a/crates/ai_tools/src/user_tool_review/test.rs
+++ b/crates/ai_tools/src/user_tool_review/test.rs
@@ -336,5 +336,3 @@ async fn a_tool_the_toolset_does_not_know_as_a_user_tool_is_left_alone() {
assert_eq!(finished, None);
assert!(reviewer.asked.lock().unwrap().is_empty());
}
-
-mod booking_links;
diff --git a/crates/calendar_scheduling/README.md b/crates/calendar_scheduling/README.md
index 70e6ef8e64..65bdc139fa 100644
--- a/crates/calendar_scheduling/README.md
+++ b/crates/calendar_scheduling/README.md
@@ -80,10 +80,13 @@ It does not deploy the backend or apply migrations to shared databases.
`ListBookingLinks` discovers personal links, current team IDs, reusable schedules and
full editable drafts. Pass a returned team ID to discover that team's links. Both
active and paused links include their shareable URL and profile revision.
-`CreateBookingLink` and `EditBookingLink` present one editable review in chat and
-agent sessions. The review reuses the normal booking options and availability
-controls; accepting executes the edited draft, while declining/cancelling does not
-write anything. Headless hosts register executable tools, not deferred user tools.
+`CreateBookingLink` and `EditBookingLink` execute directly in every host after
+conversational confirmation. The agent explains the complete proposal, waits for
+the user's approval, then passes that reply verbatim in required `userConfirmation`.
+Missing or blank confirmation is rejected before calling the scheduling service.
+As with confirmed email/calendar tools, the quote is not verified against conversation
+history. There is no booking review card, elicitation, or deferred user-tool result.
+The agent discovers internal identities through tools instead of asking users for IDs.
The scheduling service owns authorization and validates the complete draft. Edits
replace only the chosen event type; changed hours use a separate schedule to
diff --git a/crates/calendar_scheduling/src/inbound/toolset.rs b/crates/calendar_scheduling/src/inbound/toolset.rs
index 9ced9bfb1f..9ad653a77d 100644
--- a/crates/calendar_scheduling/src/inbound/toolset.rs
+++ b/crates/calendar_scheduling/src/inbound/toolset.rs
@@ -1,4 +1,4 @@
-//! Workflow-oriented booking links, with deferred review only on hosts that can finish it.
+//! Booking links saved directly after the user confirms the proposal in conversation.
use crate::domain::{
booking_links::{BookingLink, BookingLinks},
models::Error,
@@ -56,19 +56,31 @@ fn tool_error(error: Error) -> ToolCallError {
internal_error: anyhow::Error::new(error),
}
}
-/// Chat and agent-session tools: mutations await the user's actual review card.
+/// Booking tools execute after conversational confirmation; no host opens a review form.
pub fn booking_link_toolset<Scheduling: BookingLinks>()
-> AsyncToolCollection<BookingLinkToolContext<Scheduling>> {
AsyncToolCollection::new()
.add_tool::<ListBookingLinks, BookingLinkToolContext<Scheduling>>()
- .add_user_tool::<CreateBookingLink, BookingLinkToolContext<Scheduling>>()
- .add_user_tool::<EditBookingLink, BookingLinkToolContext<Scheduling>>()
+ .add_tool::<CreateBookingLink, BookingLinkToolContext<Scheduling>>()
+ .add_tool::<EditBookingLink, BookingLinkToolContext<Scheduling>>()
}
-/// Headless hosts execute real tools using their own confirmation policy, never a pending placeholder.
+/// Headless hosts use the same conversational-confirmation contract.
pub fn mcp_toolset<Scheduling: BookingLinks>()
-> AsyncToolCollection<BookingLinkToolContext<Scheduling>> {
- AsyncToolCollection::new()
- .add_tool::<ListBookingLinks, BookingLinkToolContext<Scheduling>>()
- .add_tool::<CreateBookingLink, BookingLinkToolContext<Scheduling>>()
- .add_tool::<EditBookingLink, BookingLinkToolContext<Scheduling>>()
+ booking_link_toolset()
}
+
+// Matches the confirmed email/calendar tools: require evidence of approval before
+// execution. This rejects missing/blank quotes, but does not verify conversation history.
+fn require_confirmation(confirmation: &str) -> Result<(), ToolCallError> {
+ if confirmation.trim().is_empty() {
+ return Err(ToolCallError {
+ description: "Quote the user's reply approving the booking details in userConfirmation. First explain the proposal in conversation, ask whether to proceed, and wait for their reply.".into(),
+ internal_error: anyhow::anyhow!("Booking link called without confirmation"),
+ });
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs
index cb64f8daf9..eb72b996b2 100644
--- a/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs
+++ b/crates/calendar_scheduling/src/inbound/toolset/create_booking_link.rs
@@ -12,13 +12,16 @@ use uuid::Uuid;
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[schemars(
title = "CreateBookingLink",
- description = "Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
+ description = "Create a reusable booking page, not a calendar meeting. First use ListBookingLinks to discover a suitable existing link or reuse availability. Supply a full draft with all seven weekdays (Sunday=0), IANA time zone, and real host IDs; personal links use the authenticated user and individual mode. For a team use a real team ID and collective or roundRobin mode. Set enabled only when the user wants to accept bookings. No invitations are sent by creating a link. Repeating an identical draft with the same slug reuses the saved link; a different draft at that slug conflicts. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
)]
pub struct CreateBookingLink {
- /// Existing Macro team ID, or null for a personal booking link.
+ /// Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.
pub team_id: Option<Uuid>,
- /// Full booking rules and availability for review. No other links are modified.
+ /// Full booking rules and availability approved in conversation. No other links are modified.
pub draft: BookingLinkDraft,
+ /// The user's reply approving the specific proposal you already showed them, quoted verbatim.
+ /// Never use their original request, paraphrase their reply, or invent approval.
+ pub user_confirmation: String,
}
impl ToolAnnotated for CreateBookingLink {
const ANNOTATIONS: ToolAnnotations =
@@ -32,6 +35,7 @@ impl<Scheduling: BookingLinks> AsyncTool<BookingLinkToolContext<Scheduling>> for
context: ServiceContext<BookingLinkToolContext<Scheduling>>,
request: RequestContext,
) -> ToolResult<Self::Output> {
+ require_confirmation(&self.user_confirmation)?;
let context = context.0;
let link = context
.service
diff --git a/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs
index b1d6f5d446..5d76ca8f95 100644
--- a/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs
+++ b/crates/calendar_scheduling/src/inbound/toolset/edit_booking_link.rs
@@ -12,17 +12,20 @@ use uuid::Uuid;
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[schemars(
title = "EditBookingLink",
- description = "Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and present a fresh review instead of overwriting concurrent edits. In chat and agent sessions this presents an editable review card: use it directly without an extra prose confirmation. Cancellation changes nothing. Headless clients apply their own confirmation policy before execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
+ description = "Edit exactly one existing booking link. First read it with ListBookingLinks, preserve all settings the user did not request changing, and pass its revision and full edited draft. Changed availability applies only to this link; other links and personal default hours remain unchanged. A stale revision fails: read again and confirm the updated proposal in conversation instead of overwriting concurrent edits. Create or edit booking links only after conversational confirmation, with no review card or interactive form. First explain all proposed details clearly in your reply: personal or team ownership, named hosts and who attends, meeting name, description, duration, location or Google Meet, time zone, weekly hours and date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit, guest questions and whether bookings are enabled. Ask whether to proceed and stop. Only in a later turn after the user approves that specific proposal, call this tool with their approving reply quoted verbatim in userConfirmation. The original request is not confirmation; never invent or paraphrase approval. Never ask the user for teamId, host IDs, schedule IDs, revisions or JSON: discover IDs with ListBookingLinks and ListTeamMembers. Default to personal ownership unless a team is requested, and clarify ambiguous choices by name. Return the saved URL after execution. Returns actual saved IDs, revision, full draft and shareable URL. Manual approval must be false; guest booking requires a connected, synced writable calendar."
)]
pub struct EditBookingLink {
- /// Existing Macro team ID, or null for a personal booking link.
+ /// Existing Macro team ID discovered through tools, never requested from the user. Use null for a personal booking link.
pub team_id: Option<Uuid>,
/// Existing link identity returned by ListBookingLinks.
pub event_type_id: Uuid,
/// Revision returned by ListBookingLinks; guards against concurrent settings changes.
pub expected_revision: i64,
- /// Full booking rules and availability for review. No other links are modified.
+ /// Full booking rules and availability approved in conversation. No other links are modified.
pub draft: BookingLinkDraft,
+ /// The user's reply approving the specific proposal you already showed them, quoted verbatim.
+ /// Never use their original request, paraphrase their reply, or invent approval.
+ pub user_confirmation: String,
}
impl ToolAnnotated for EditBookingLink {
const ANNOTATIONS: ToolAnnotations =
@@ -36,6 +39,7 @@ impl<Scheduling: BookingLinks> AsyncTool<BookingLinkToolContext<Scheduling>> for
context: ServiceContext<BookingLinkToolContext<Scheduling>>,
request: RequestContext,
) -> ToolResult<Self::Output> {
+ require_confirmation(&self.user_confirmation)?;
let context = context.0;
let link = context
.service
diff --git a/crates/calendar_scheduling/src/inbound/toolset/test.rs b/crates/calendar_scheduling/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..307532bda8
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/toolset/test.rs
@@ -0,0 +1,128 @@
+use super::*;
+use crate::domain::booking_links::{BookingLinkDraft, BookingLinkListing};
+use ai_toolset::{RequestContext, ToolSet};
+use serde_json::{Value, json};
+use std::sync::Mutex;
+use uuid::Uuid;
+
+#[derive(Default)]
+struct Scheduling {
+ writes: Mutex<Vec<(&'static str, String, Option<Uuid>, BookingLinkDraft)>>,
+}
+impl BookingLinks for Scheduling {
+ async fn list_links(
+ &self,
+ _: &str,
+ _: Option<Uuid>,
+ _: Option<&str>,
+ ) -> Result<BookingLinkListing, Error> {
+ unreachable!("mutation tests do not discover links")
+ }
+ async fn create_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ draft: BookingLinkDraft,
+ ) -> Result<BookingLink, Error> {
+ self.writes
+ .lock()
+ .unwrap()
+ .push(("create", user.into(), team, draft.clone()));
+ Ok(BookingLink {
+ profile_id: Uuid::nil(),
+ event_type_id: Uuid::nil(),
+ revision: 1,
+ draft,
+ })
+ }
+ async fn edit_link(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ event: Uuid,
+ revision: i64,
+ draft: BookingLinkDraft,
+ ) -> Result<BookingLink, Error> {
+ self.writes
+ .lock()
+ .unwrap()
+ .push(("edit", user.into(), team, draft.clone()));
+ Ok(BookingLink {
+ profile_id: Uuid::nil(),
+ event_type_id: event,
+ revision: revision + 1,
+ draft,
+ })
+ }
+}
+fn args() -> Value {
+ json!({"teamId": null, "draft": {
+ "event": {"title":"Intro", "slug":"intro", "description":"", "durationMinutes":30, "location":"Office", "googleMeet":false, "enabled":true, "mode":"individual", "hosts":["macro|[email protected]"], "beforeMinutes":0, "afterMinutes":0, "noticeMinutes":60, "horizonDays":30, "intervalMinutes":30, "dailyLimit":null, "requiresConfirmation":false, "questions":[]},
+ "schedule":{"name":"Working hours", "timeZone":"UTC", "weekly":(0..7).map(|day| json!({"day":day, "windows":[{"start":"09:00", "end":"17:00"}]})).collect::<Vec<_>>(), "overrides":[]}
+ }})
+}
+
+#[tokio::test]
+async fn mutations_require_confirmation_and_execute_without_elicitation() {
+ for tool in ["CreateBookingLink", "EditBookingLink"] {
+ let service = Arc::new(Scheduling::default());
+ let context = BookingLinkToolContext {
+ service: service.clone(),
+ public_origin: "https://macro.com".into(),
+ };
+ let tools = booking_link_toolset();
+ assert!(!tools.user_tools.contains_key(tool));
+ let mut args = args();
+ if tool == "EditBookingLink" {
+ args["eventTypeId"] = json!(Uuid::nil());
+ args["expectedRevision"] = json!(3);
+ }
+ for confirmation in [None, Some(""), Some(" \n\t")] {
+ if let Some(quote) = confirmation {
+ args["userConfirmation"] = json!(quote);
+ }
+ let response = tools
+ .try_tool_call(
+ context.clone(),
+ RequestContext::new(
+ serde_json::from_value(json!("macro|[email protected]")).unwrap(),
+ ),
+ tool,
+ &args,
+ )
+ .await;
+ assert!(
+ response.is_err() || response.unwrap().is_err(),
+ "{tool} must reject missing or blank approval"
+ );
+ assert!(service.writes.lock().unwrap().is_empty());
+ }
+ args["userConfirmation"] = json!("Yes, create the link with those details.");
+ let response = tools
+ .try_tool_call(
+ context,
+ RequestContext::new(
+ serde_json::from_value(json!("macro|[email protected]")).unwrap(),
+ ),
+ tool,
+ &args,
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ response["url"],
+ "https://macro.com/app/book/00000000-0000-0000-0000-000000000000/intro"
+ );
+ assert_eq!(response["draft"], args["draft"]);
+ assert_eq!(
+ response["revision"],
+ if tool == "EditBookingLink" { 4 } else { 1 }
+ );
+ let writes = service.writes.lock().unwrap();
+ assert_eq!(writes.len(), 1);
+ assert_eq!(writes[0].1, "macro|[email protected]");
+ assert_eq!(writes[0].2, None);
+ assert_eq!(serde_json::to_value(&writes[0].3).unwrap(), args["draft"]);
+ }
+}
diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rs
index 78e78f251c..554755be19 100644
--- a/crates/prompt/src/user_tools.rs
+++ b/crates/prompt/src/user_tools.rs
@@ -20,7 +20,21 @@ use crate::types::StaticPrompt;
static TITLE: &str = "User Tools";
-static INSTRUCTIONS: &str = r##"- User tools are tools that must be executed by a user on the frontend.
+static INSTRUCTIONS: &str = r##"- Booking links use conversational confirmation in every surface. First use `ListBookingLinks`
+ to find existing links and reusable availability. Resolve team and host identities with tools;
+ never ask for IDs, revisions or JSON. Default to personal ownership unless a team is requested.
+ Explain the complete proposal in readable prose: ownership and named hosts, who attends,
+ meeting name and description, duration, location or Google Meet, time zone, weekly hours and
+ date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit,
+ guest questions, and whether bookings are enabled. Group related settings so it is easy to
+ review. Ask whether to proceed, and end the turn. Only after the user's reply approving that
+ proposal, call `CreateBookingLink` or `EditBookingLink`, quoting the reply verbatim in
+ `userConfirmation`. Do not quote the original request or invent approval. These tools save
+ immediately, with no booking review form. Do not use `AskUser` or an elicitation for booking
+ details. For edits preserve unrequested settings, and re-read and reconfirm if the revision
+ conflicts. Return the saved URL. If the same proposal is already approved, do not ask again.
+
+- User tools are tools that must be executed by a user on the frontend.
A user tool will return "PendingUserExecution" until a user chooses to
accept / reject the tool.
@@ -45,7 +59,21 @@ or CreateConfirmedCalendarEvent, which are for surfaces without a composer.";
/// The user-tools prompt section for composer-capable chat hosts.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
-static SESSION_INSTRUCTIONS: &str = r##"- Before reaching for `SendEmail` or `CreateCalendarEvent`, look at where the newest prompt came
+static SESSION_INSTRUCTIONS: &str = r##"- Booking links use conversational confirmation in every surface. First use `ListBookingLinks`
+ to find existing links and reusable availability. Resolve team and host identities with tools;
+ never ask for IDs, revisions or JSON. Default to personal ownership unless a team is requested.
+ Explain the complete proposal in readable prose: ownership and named hosts, who attends,
+ meeting name and description, duration, location or Google Meet, time zone, weekly hours and
+ date exceptions, link name, buffers, minimum notice, booking window, slot interval, daily limit,
+ guest questions, and whether bookings are enabled. Group related settings so it is easy to
+ review. Ask whether to proceed, and end the turn. Only after the user's reply approving that
+ proposal, call `CreateBookingLink` or `EditBookingLink`, quoting the reply verbatim in
+ `userConfirmation`. Do not quote the original request or invent approval. These tools save
+ immediately, with no booking review form. Do not use `AskUser` or an elicitation for booking
+ details. For edits preserve unrequested settings, and re-read and reconfirm if the revision
+ conflicts. Return the saved URL. If the same proposal is already approved, do not ask again.
+
+- Before reaching for `SendEmail` or `CreateCalendarEvent`, look at where the newest prompt came
from. The context block names a conversation parent when that prompt was posted in a
channel or document thread instead of typed in the agent session view. It is decided per
prompt, not per session: the same session can be driven from both places, so check the
@@ -94,3 +122,6 @@ the review card be the confirmation, never asking for confirmation in prose firs
/// agent finishes user tools in the turn through a review elicitation.
pub static SESSION_PROMPT: StaticPrompt<'static> =
StaticPrompt::borrowed(TITLE, SESSION_INSTRUCTIONS, SESSION_INTENT);
+
+#[cfg(test)]
+mod test;
diff --git a/crates/prompt/src/user_tools/test.rs b/crates/prompt/src/user_tools/test.rs
new file mode 100644
index 0000000000..eb0209a890
--- /dev/null
+++ b/crates/prompt/src/user_tools/test.rs
@@ -0,0 +1,19 @@
+use super::*;
+
+#[test]
+fn booking_links_require_a_reply_to_the_proposal_in_chat_and_sessions() {
+ for instructions in [INSTRUCTIONS, SESSION_INSTRUCTIONS] {
+ for rule in [
+ "Booking links use conversational confirmation",
+ "never ask for IDs, revisions or JSON",
+ "Ask whether to proceed, and end the turn",
+ "Only after the user's reply approving",
+ "`userConfirmation`",
+ "Do not quote the original request or invent approval",
+ "Do not use `AskUser` or an elicitation",
+ "re-read and reconfirm",
+ ] {
+ assert!(instructions.contains(rule), "Missing booking rule: {rule}");
+ }
+ }
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 2d1775996a..43f1b4d587 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -1492,22 +1492,17 @@ Ask the AI to find or reuse an existing booking link before creating another.
shareable URLs (including paused links). It also supplies the revision used to
protect edits from concurrent settings changes.
-`CreateBookingLink` and `EditBookingLink` open the same native booking review form
-in chat and in an agent session's elicitation. Edit title, slug, duration, location
-or Google Meet, enabled state, weekly hours, time zone, date overrides, buffers,
-notice, booking window, daily limit, questions and team hosts directly in the
-card. Create/Save accepts the complete edited draft; no extra confirmation is
-required. Cancel declines without saving. Link creation itself sends no calendar
-invitations. Guests receive an invitation only when they book through the normal
-booking page.
-
-A successful result shows the actual saved URL and whether the link accepts
-bookings. Editing hours affects only that link, preserving other links and personal
-default availability. If another settings edit made the revision stale, ask the AI
-to read the latest link and propose the edit again rather than retrying the stale
-revision. A network/save error preserves the review for retry; repeating an
-identical successful create or edit does not create another link.
-
-For isolated UI checks, `/src/features/scheduling/browser-test/booking-ai.html`
-mounts the actual review controls with the agent elicitation sink and no remote
-writes. It includes create/edit modes and simulated save failures.
+Booking links are confirmed in conversation, with no special booking form. The AI
+first explains the proposed meeting details, ownership and named hosts, time zone,
+availability and date exceptions, booking rules, guest questions and whether the
+link accepts bookings. It asks whether to proceed and waits for your reply before
+calling `CreateBookingLink` or `EditBookingLink`. An initial request to create a
+link is not approval of the proposal. IDs and revisions are discovered through
+tools; you should never be asked to enter a team ID, host ID or JSON.
+
+A successful result returns the saved URL. Link creation itself sends no calendar
+invitations; guests receive an invitation when they book. Editing hours affects
+only that link. If another edit makes the revision stale, the AI reads the latest
+settings and confirms a fresh proposal. Identical retries reuse the saved link.
+Old pending booking review requests can be dismissed so the agent can resume with
+conversational confirmation.