Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): attach a Macro call to events the agent creates (#7259)
teo757f1bdec4f3
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex a67b7d8be6..4750dd4f19 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -2318,39 +2318,77 @@"crates/workspace-hack"],"calendar_events": [+ "crates/activity",+ "crates/agent","crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment","crates/bot_id","crates/bot_token","crates/broadcast","crates/calendar_events",+ "crates/call","crates/channel_sender",+ "crates/channels",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts","crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_mutation",+ "crates/filter_ast",+ "crates/frecency","crates/genai_telemetry","crates/harness_id","crates/harness_token",+ "crates/initiative","crates/invite_email",+ "crates/ip_extractor",+ "crates/item_filters","crates/kafka_util","crates/last_online_tracker","crates/macro_auth","crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_entrypoint","crates/macro_env","crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics","crates/macro_service_urls",+ "crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid","crates/mention_utils",+ "crates/messages",+ "crates/model","crates/model-entity","crates/model-error-response",+ "crates/model_file_type","crates/model_notifications","crates/model_owner","crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management","crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_sfs",+ "crates/non_empty","crates/notification","crates/notification_state",+ "crates/prompt",+ "crates/properties","crates/rate_limit","crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/system_properties","crates/workspace-hack"],"calendar_scheduling": [@@ -6706,47 +6744,79 @@"crates/workspace-hack"],"graphql_calendar": [+ "crates/activity",+ "crates/agent","crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment","crates/bot_id","crates/bot_token","crates/broadcast","crates/calendar_events",+ "crates/call","crates/channel_sender",+ "crates/channels",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts","crates/cowlike",+ "crates/database_env_vars","crates/document_sub_type",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_mutation","crates/filter_ast",+ "crates/frecency","crates/genai_telemetry","crates/graphql_calendar","crates/graphql_common","crates/harness_id","crates/harness_token",+ "crates/initiative","crates/invite_email",+ "crates/ip_extractor","crates/item_filters","crates/kafka_util","crates/last_online_tracker","crates/macro_auth","crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_entrypoint","crates/macro_env","crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics","crates/macro_service_urls",+ "crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid","crates/mention_utils",+ "crates/messages",+ "crates/model","crates/model-entity","crates/model-error-response","crates/model_file_type","crates/model_notifications","crates/model_owner","crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management","crates/models_pagination",+ "crates/models_permissions","crates/models_properties",+ "crates/models_sfs","crates/non_empty","crates/notification","crates/notification_state",+ "crates/prompt",+ "crates/properties","crates/rate_limit","crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/system_properties","crates/workspace-hack"],"graphql_channel": [diff --git a/Cargo.lock b/Cargo.lockindex 34af210470..afac650d14 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3551,6 +3551,7 @@ dependencies = ["async-trait","aws-sdk-sqs","axum",+ "call","chrono","chrono-tz","futures",diff --git a/apps/docs/AI/mcp/tools/create-calendar-event.mdx b/apps/docs/AI/mcp/tools/create-calendar-event.mdxindex 2f3b72685e..b34a2a4a08 100644--- a/apps/docs/AI/mcp/tools/create-calendar-event.mdx+++ b/apps/docs/AI/mcp/tools/create-calendar-event.mdx@@ -11,7 +11,9 @@ Prepare an event on the user's calendar, inviting any listed attendees through GThe event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected.-Set `eventType` to "out_of_office" to mark the user as out of office (e.g. "mark me out of office Thursday"). Out-of-office events must land on the user's primary calendar (omit `calendarId`), must be timed rather than all-day, and take no attendees or Google Meet (leave `addGoogleMeet` false); use `outOfOffice` to control whether conflicting meetings are auto-declined. The type cannot be changed afterward.+For video conferencing pick at most one of `addMacroCall` (a Macro meeting link, the default choice for a Macro user's meeting) or `addGoogleMeet` (a Google Meet conference). A Macro call is created for the user, scheduled to the event's times, and its join link is appended to the event's description so every attendee's invitation carries it; it also becomes the event's `location` unless a physical `location` was supplied. The returned event's `macroCallUrl` holds the link.++Set `eventType` to "out_of_office" to mark the user as out of office (e.g. "mark me out of office Thursday"). Out-of-office events must land on the user's primary calendar (omit `calendarId`), must be timed rather than all-day, and take no attendees or video conferencing (leave `addMacroCall` and `addGoogleMeet` false); use `outOfOffice` to control whether conflicting meetings are auto-declined. The type cannot be changed afterward.## Parameters@@ -25,6 +27,7 @@ Set `eventType` to "out_of_office" to mark the user as out of office (e.g. "mark| `recurrenceLines` | string[] | No | Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE"]. Omit for a one-off event. || `calendarId` | string | No | Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar. || `reminders` | EventRemindersInput | No | Reminder configuration for the event. Omit to use the selected calendar's defaults. |-| `addGoogleMeet` | boolean | No | Attach a freshly generated Google Meet video conference to the event. |+| `addMacroCall` | boolean | No | Attach a freshly created Macro call to the event: a Macro meeting link scheduled to the event's times, written into the event's location and description. Mutually exclusive with `addGoogleMeet`. |+| `addGoogleMeet` | boolean | No | Attach a freshly generated Google Meet video conference to the event. Mutually exclusive with `addMacroCall`. || `eventType` | `"default"` \| `"out_of_office"` | No | The kind of event a create tool call makes. || `outOfOffice` | OutOfOfficeInput | No | Out-of-office decline behavior, used only when eventType is "out_of_office". Omit to just block the time; set `autoDeclineMode` to "decline_all" or "decline_new_only" to have Google decline conflicting meetings, optionally with a `declineMessage`. |diff --git a/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdx b/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdxindex 9940a85a82..fc2433b325 100644--- a/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdx+++ b/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdx@@ -6,7 +6,7 @@ description: >-# CreateConfirmedCalendarEvent-Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.+Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet or Macro call, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.## Parameters@@ -20,7 +20,8 @@ Create a calendar event immediately, with no review card or composer. Only for a| `recurrenceLines` | string[] | No | Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE"]. Omit for a one-off event. || `calendarId` | string | No | Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar. || `reminders` | EventRemindersInput | No | Reminder configuration for the event. Omit to use the selected calendar's defaults. |-| `addGoogleMeet` | boolean | No | Attach a freshly generated Google Meet video conference to the event. |+| `addMacroCall` | boolean | No | Attach a freshly created Macro call to the event: a Macro meeting link scheduled to the event's times, written into the event's location and description. Mutually exclusive with `addGoogleMeet`. |+| `addGoogleMeet` | boolean | No | Attach a freshly generated Google Meet video conference to the event. Mutually exclusive with `addMacroCall`. || `eventType` | `"default"` \| `"out_of_office"` | No | The kind of event a create tool call makes. || `outOfOffice` | OutOfOfficeInput | No | Out-of-office decline behavior, used only when eventType is "out_of_office". Omit to just block the time; set `autoDeclineMode` to "decline_all" or "decline_new_only" to have Google decline conflicting meetings, optionally with a `declineMessage`. || `userConfirmation` | string | Yes | The user's own message approving this specific event, quoted verbatim - for example their "yes, go ahead" in reply to the event you wrote out for them. It is a reply to your draft, never the earlier request that asked you to schedule something: if the user has not yet seen this event, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself. |diff --git a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsxindex 6e5f0c9579..e9805e55a5 100644--- a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx@@ -90,7 +90,7 @@ const EventDetails = (props: {</div></Tool.ListItem></button>- <Show when={props.event.conferenceUrl}>+ <Show when={props.event.macroCallUrl ?? props.event.conferenceUrl}>{(url) => (<Tool.ListItem icon={<VideoCamera class="size-4" />}><adiff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsxindex 0522706eb7..e03b7dd6b4 100644--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.test.tsx@@ -3,7 +3,7 @@ import type { VisibleCalendar } from '@queries/calendar/calendars';import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';import type { Link } from '@service-email/generated/schemas';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { For, type JSX } from 'solid-js';+import { createSignal, For, type JSX } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -15,6 +15,10 @@ const mocks = vi.hoisted(() => ({refetchLinks: vi.fn(),startAddInbox: vi.fn(),execute: vi.fn(),+ quickCalls: () => ({ loading: false, enabled: true }),+}));+vi.mock('@app/features/meetings/use-quick-calls-flag', () => ({+ useQuickCallsFlag: () => () => mocks.quickCalls(),}));vi.mock('@queries/calendar/calendars', () => ({useVisibleCalendarsQuery: () => ({@@ -62,6 +66,18 @@ vi.mock('@app/features/calendar/components/composer/EventForm', () => ({{(option) => <option value={option.id}>{option.label}</option>}</For></select>+ <output aria-label="Macro calls enabled">+ {String(props.macroCallsEnabled)}+ </output>+ <output aria-label="Conference">+ {props.controller.state().conference}+ </output>+ <button+ type="button"+ onClick={() => props.controller.setField('conference', 'macro')}+ >+ Pick Macro call+ </button><buttondisabled={!props.controller.canSave() || props.disabled || props.pending@@ -101,7 +117,10 @@ const calendar = (id: string): VisibleCalendar => ({defaultReminders: [],});-function showDraft(calendarId?: string) {+function showDraft(+ calendarId?: string,+ overrides: Partial<CreateCalendarEvent> = {}+) {const draft = {title: 'Customer demo',calendarId,@@ -110,6 +129,7 @@ function showDraft(calendarId?: string) {startsAt: '2030-01-01T12:00:00Z',endsAt: '2030-01-01T13:00:00Z',},+ ...overrides,} as CreateCalendarEvent;return render(() => (<CalendarDraftComposer@@ -130,6 +150,7 @@ beforeEach(() => {vi.clearAllMocks();mocks.execute.mockResolvedValue(true);mocks.startAddInbox.mockResolvedValue(undefined);+ mocks.quickCalls = () => ({ loading: false, enabled: true });mocks.calendarError = false;mocks.linksError = false;mocks.links = [link('personal'), link('work')];@@ -244,3 +265,43 @@ describe('AI calendar draft account selection', () => {});});++describe('AI calendar draft Macro calls', () => {+ it('offers Macro calls under the quick-calls flag', () => {+ const [flag, setFlag] = createSignal({ loading: false, enabled: false });+ mocks.quickCalls = flag;+ showDraft();+ expect(screen.getByLabelText('Macro calls enabled').textContent).toBe(+ 'false'+ );+ setFlag({ loading: false, enabled: true });+ expect(screen.getByLabelText('Macro calls enabled').textContent).toBe(+ 'true'+ );+ });++ it('opens on the conferencing the agent drafted', () => {+ showDraft(undefined, { addMacroCall: true });+ expect(screen.getByLabelText('Conference').textContent).toBe('macro');+ });++ it('executes the tool with addMacroCall when the user picks a Macro call', async () => {+ showDraft(undefined, {+ attendees: [{ email: '[email protected]' }],+ addGoogleMeet: false,+ });+ expect(screen.getByLabelText('Conference').textContent).toBe('none');+ await fireEvent.click(+ screen.getByRole('button', { name: 'Pick Macro call' })+ );+ expect(screen.getByLabelText('Conference').textContent).toBe('macro');+ await fireEvent.click(screen.getByRole('button', { name: 'Create event' }));+ expect(mocks.execute).toHaveBeenCalledWith(+ expect.objectContaining({+ addMacroCall: true,+ addGoogleMeet: false,+ attendees: [{ email: '[email protected]' }],+ })+ );+ });+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsxindex abcb059537..b4c287759a 100644--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx@@ -16,6 +16,7 @@ import {calendarDisplayLabel,spansMultipleInboxes,} from '@app/features/calendar/utils/calendar-label';+import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';import { useUserId } from '@core/context/user';import { useAddInboxFlow } from '@core/email-link';import { calendarConsentScopes } from '@core/email-link/consent';@@ -116,6 +117,10 @@ function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {requestedInbox()?.needs_reauth ||requestedInbox()?.needs_calendar_permission;const contacts = useContacts();+ // The tool mints the Macro call when it executes, so the composer offers the+ // choice under the same flag as the calendar's own event composer.+ const quickCalls = useQuickCallsFlag();+ const macroCallsEnabled = () => quickCalls().enabled && !quickCalls().loading;const [operation, setOperation] = createSignal<'create' | 'reject'>();let finalized = false;@@ -270,7 +275,7 @@ function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {</Show><EventFormcontroller={controller}- macroCallsEnabled={false}+ macroCallsEnabled={macroCallsEnabled()}class="min-w-0"disabled={finalized || !props.sink.canAct() || operation() === 'reject'diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.test.ts b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.test.tsindex b86d0fdc28..887ae775f6 100644--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.test.ts+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.test.ts@@ -45,6 +45,17 @@ describe('createCalendarEventToEditorInitialValues', () => {expect(values.conference).toBe('none');});+ it('maps the requested conferencing onto the editor choice', () => {+ expect(+ createCalendarEventToEditorInitialValues(event({ addMacroCall: true }))+ .conference+ ).toBe('macro');+ expect(+ createCalendarEventToEditorInitialValues(event({ addGoogleMeet: true }))+ .conference+ ).toBe('google_meet');+ });+it('maps the tool decline modes onto the editor names', () => {const values = createCalendarEventToEditorInitialValues(event({@@ -131,4 +142,42 @@ describe('editorSubmitValuesToCreateCalendarEvent', () => {expect(merged.eventType).toBeUndefined();expect(merged.outOfOffice).toBeUndefined();});++ it('turns the conferencing choice into exactly one tool flag', () => {+ const macro = editorSubmitValuesToCreateCalendarEvent(+ submitValues({ conferenceChoice: 'macro' }),+ event({ addGoogleMeet: true })+ );+ expect(macro.addMacroCall).toBe(true);+ expect(macro.addGoogleMeet).toBe(false);++ const meet = editorSubmitValuesToCreateCalendarEvent(+ submitValues({+ conferenceChoice: 'google_meet',+ conference: 'google_meet',+ }),+ event({ addMacroCall: true })+ );+ expect(meet.addMacroCall).toBe(false);+ expect(meet.addGoogleMeet).toBe(true);++ const none = editorSubmitValuesToCreateCalendarEvent(+ submitValues({ conferenceChoice: 'none' }),+ event({ addMacroCall: true })+ );+ expect(none.addMacroCall).toBe(false);+ expect(none.addGoogleMeet).toBe(false);+ });++ it('drops the Macro call from an out-of-office event', () => {+ const merged = editorSubmitValuesToCreateCalendarEvent(+ submitValues({+ conferenceChoice: 'macro',+ outOfOffice: { autoDeclineMode: 'decline_none' },+ }),+ event({ addMacroCall: true })+ );+ expect(merged.addMacroCall).toBe(false);+ expect(merged.addGoogleMeet).toBe(false);+ });});diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.tsindex 779b16d6ef..8673de81c8 100644--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts@@ -66,9 +66,11 @@ export function createCalendarEventToEditorInitialValues(.join(', '),location: event.location ?? '',description: event.description ?? '',- conference: event.addGoogleMeet- ? ('google_meet' as const)- : ('none' as const),+ conference: event.addMacroCall+ ? ('macro' as const)+ : event.addGoogleMeet+ ? ('google_meet' as const)+ : ('none' as const),reminders: cloneReminders(event.reminders),eventType: isOutOfOffice ? ('out_of_office' as const) : undefined,outOfOffice: isOutOfOffice@@ -158,11 +160,11 @@ export function editorSubmitValuesToCreateCalendarEvent(attendees: attendees(values.guestEmails, original.attendees),recurrenceLines: values.recurrenceLines ?? original.recurrenceLines ?? [],calendarId: values.calendarId,- addGoogleMeet: outOfOffice- ? false- : values.conference === undefined- ? original.addGoogleMeet- : values.conference === 'google_meet',+ // `conferenceChoice` is the user's current pick, including the+ // client-recognized Macro call the provider-level `conference` never+ // carries; an out-of-office event takes no conferencing at all.+ addMacroCall: !outOfOffice && values.conferenceChoice === 'macro',+ addGoogleMeet: !outOfOffice && values.conferenceChoice === 'google_meet',reminders: cloneReminders(values.reminders ?? original.reminders),eventType: outOfOffice? 'out_of_office'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.tsindex 785fccffac..9fd65a868b 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@@ -1856,6 +1856,7 @@ export const CreateCalendarEvent = z.object({z.null(),]).optional(),+ addMacroCall: z.boolean().optional(),addGoogleMeet: z.boolean().optional(),eventType: z.any()@@ -1947,6 +1948,7 @@ export const UserToolResponseForToolCalendarEvent = zattendeeCount: z.number().int().gte(0),organizerEmail: z.union([z.string(), z.null()]).optional(),conferenceUrl: z.union([z.string(), z.null()]).optional(),+ macroCallUrl: z.union([z.string(), z.null()]).optional(),isReadOnly: z.boolean(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),}),@@ -2070,6 +2072,7 @@ export const CreateConfirmedCalendarEvent = z.object({z.null(),]).optional(),+ addMacroCall: z.boolean().optional(),addGoogleMeet: z.boolean().optional(),eventType: z.any()@@ -2154,6 +2157,7 @@ export const ToolCalendarEvent = z.object({attendeeCount: z.number().int().gte(0),organizerEmail: z.union([z.string(), z.null()]).optional(),conferenceUrl: z.union([z.string(), z.null()]).optional(),+ macroCallUrl: z.union([z.string(), z.null()]).optional(),isReadOnly: z.boolean(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),});diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex d39eb9ff92..d92ec371a6 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@@ -6193,7 +6193,9 @@ export interface BotWebhook {** The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected.*- * Set `eventType` to "out_of_office" to mark the user as out of office (e.g. "mark me out of office Thursday"). Out-of-office events must land on the user's primary calendar (omit `calendarId`), must be timed rather than all-day, and take no attendees or Google Meet (leave `addGoogleMeet` false); use `outOfOffice` to control whether conflicting meetings are auto-declined. The type cannot be changed afterward.+ * For video conferencing pick at most one of `addMacroCall` (a Macro meeting link, the default choice for a Macro user's meeting) or `addGoogleMeet` (a Google Meet conference). A Macro call is created for the user, scheduled to the event's times, and its join link is appended to the event's description so every attendee's invitation carries it; it also becomes the event's `location` unless a physical `location` was supplied. The returned event's `macroCallUrl` holds the link.+ *+ * Set `eventType` to "out_of_office" to mark the user as out of office (e.g. "mark me out of office Thursday"). Out-of-office events must land on the user's primary calendar (omit `calendarId`), must be timed rather than all-day, and take no attendees or video conferencing (leave `addMacroCall` and `addGoogleMeet` false); use `outOfOffice` to control whether conflicting meetings are auto-declined. The type cannot be changed afterward.*/export interface CreateCalendarEvent {/**@@ -6226,7 +6228,11 @@ export interface CreateCalendarEvent {*/reminders?: EventRemindersInput | null;/**- * Attach a freshly generated Google Meet video conference to the event.+ * Attach a freshly created Macro call to the event: a Macro meeting link scheduled to the event's times, written into the event's location and description. Mutually exclusive with `addGoogleMeet`.+ */+ addMacroCall?: boolean;+ /**+ * Attach a freshly generated Google Meet video conference to the event. Mutually exclusive with `addMacroCall`.*/addGoogleMeet?: boolean;eventType?: CalendarEventTypeInput;@@ -6354,6 +6360,11 @@ export interface ToolCalendarEvent {* Conference join URL, when a conference is attached.*/conferenceUrl?: string | null;+ /**+ * Join URL of the Macro call created with the event, when+ * CreateCalendarEvent was asked for one.+ */+ macroCallUrl?: string | null;/*** Whether the user's calendar prohibits modifying this event.*/@@ -6421,7 +6432,7 @@ export interface CreateChannelResponse {summary: string;}/**- * Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.+ * Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet or Macro call, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.*/export interface CreateConfirmedCalendarEvent {/**@@ -6454,7 +6465,11 @@ export interface CreateConfirmedCalendarEvent {*/reminders?: EventRemindersInput | null;/**- * Attach a freshly generated Google Meet video conference to the event.+ * Attach a freshly created Macro call to the event: a Macro meeting link scheduled to the event's times, written into the event's location and description. Mutually exclusive with `addGoogleMeet`.+ */+ addMacroCall?: boolean;+ /**+ * Attach a freshly generated Google Meet video conference to the event. Mutually exclusive with `addMacroCall`.*/addGoogleMeet?: boolean;eventType?: CalendarEventTypeInput;diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex 5e2cf0194d..d75d185937 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -31,7 +31,7 @@ axum = { workspace = true, features = ["macros"] }aws-sdk-sqs.workspace = truebots = { path = "../bots", default-features = false, features = ["ai_tools", "outbound"] }calendar_scheduling = { path = "../calendar_scheduling", features = ["ai_tools", "postgres", "calendar"] }-calendar_events = { path = "../calendar_events", features = ["ai_tools", "mutation-client", "postgres"] }+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"] }channels = { path = "../channels", features = ["ai_tools", "outbound"] }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex d8b8438658..7fd5369ba6 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -43,8 +43,8 @@ use lexical_client::LexicalClient;use macro_env::Environment;use macro_env_var::{env_var, maybe_env_var};use macro_service_urls::{- AiEditingWorkerUrl, CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl,- EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,+ AiEditingWorkerUrl, AppServiceUrl, CalendarServiceUrl, ConnectionGatewayUrl,+ DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,};use notification::domain::service::{NotificationReaderService, PlatformArnConfig};use notification::outbound::queue::SqsQueue;@@ -419,6 +419,8 @@ pub async fn build_tool_service_context_from_env(pool.clone(),calendar_service_url,env.internal_api_key.to_string(),+ call_tool_context.service.clone(),+ AppServiceUrl::new()?,);let notification_reader_service = NotificationReaderService {diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 5ab3de8ce6..5b9b709a89 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -448,9 +448,18 @@ pub type ToolCalendarReadService = calendar_events::domain::service::CalendarSerpub type ToolCalendarMutationService =calendar_events::outbound::calendar_service_mutations::CalendarServiceMutations;+/// Type alias for the meeting-link provider used by AI tools. Macro calls+/// attached to events are minted through the same call service the call+/// tools run on, owned by the requesting user.+pub type ToolCalendarMeetingLinks =+ calendar_events::outbound::call_meeting_links::CallServiceMeetingLinks<ToolCallService>;+/// Type alias for the calendar AI tool context.-pub type ToolCalendarToolContext =- CalendarToolContext<ToolCalendarMutationService, ToolCalendarReadService>;+pub type ToolCalendarToolContext = CalendarToolContext<+ ToolCalendarMutationService,+ ToolCalendarReadService,+ ToolCalendarMeetingLinks,+>;/// Source-scoped team calendar domain service for read-only AI availability.pub type ToolTeamCalendarService = calendar_events::domain::team::CalendarTeamServiceImpl<@@ -475,11 +484,15 @@ pub fn build_team_calendar_tool_context(/// Build the calendar AI tool context: reads query the local occurrence/// projections from `pool`; mutations call the calendar service at-/// `calendar_service_url` with the shared internal API key.+/// `calendar_service_url` with the shared internal API key; Macro calls+/// attached to new events are minted through `call_service` and linked on+/// `app_url`, the browser origin users open meetings on.pub fn build_calendar_tool_context(pool: sqlx::PgPool,calendar_service_url: macro_service_urls::CalendarServiceUrl,internal_api_key: String,+ call_service: Arc<ToolCallService>,+ app_url: macro_service_urls::AppServiceUrl,) -> ToolCalendarToolContext {CalendarToolContext::new(Arc::new(@@ -491,6 +504,12 @@ pub fn build_calendar_tool_context(Arc::new(calendar_events::domain::service::CalendarService::new(calendar_events::outbound::pg::PgCalendarRepository::new(pool),)),+ Arc::new(+ calendar_events::outbound::call_meeting_links::CallServiceMeetingLinks::new(+ call_service,+ app_url.as_str(),+ ),+ ),)}diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.tomlindex 666fe92c91..9f2deb192f 100644--- a/crates/calendar_events/Cargo.toml+++ b/crates/calendar_events/Cargo.toml@@ -8,6 +8,9 @@ version = "0.1.0"default = []# The AI toolset adapter exposing calendar CRUD to agents.ai_tools = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]+# The meeting-link adapter that mints Macro calls through the call domain+# service, for hosts that compose both calendars and calls.+call-meetings = ["dep:call", "dep:macro_user_id"]# The reminder dispatch queue worker. Transport-agnostic: it drives the# domain through the dispatch ports.dispatch = ["dep:tokio", "dep:tokio-util"]@@ -34,6 +37,9 @@ anyhow = { workspace = true, optional = true }async-trait = { workspace = true, optional = true }aws-sdk-sqs = { workspace = true, optional = true }axum = { workspace = true, optional = true }+call = { path = "../call", default-features = false, features = [+ "ports",+], optional = true }chrono = { workspace = true }chrono-tz = { workspace = true }futures = { workspace = true }diff --git a/crates/calendar_events/src/domain/meeting_links.rs b/crates/calendar_events/src/domain/meeting_links.rsnew file mode 100644index 0000000000..682a67179b--- /dev/null+++ b/crates/calendar_events/src/domain/meeting_links.rs@@ -0,0 +1,210 @@+//! Macro meeting links carried by calendar events.+//!+//! A Macro call is not provider conferencing: Google knows nothing about it,+//! so the link travels in the event's ordinary location and description+//! fields, in the exact shape the calendar UI recognizes and can later+//! strip or replace. This module owns that shape and the create flow that+//! mints a meeting and writes the event carrying it.++use chrono::{DateTime, Utc};+use uuid::Uuid;++use super::{+ models::{CalendarEvent, CalendarEventDraft, EventTime},+ ports::{CalendarMutationError, CalendarMutationService, MeetingLinkProvider},+};++/// Inputs for minting a Macro meeting to accompany a calendar event.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct MeetingLinkRequest {+ /// Display title, normally the event title. Adapters trim it to the+ /// meeting provider's limits and fall back to its default when blank.+ pub title: String,+ /// Scheduled start, or `None` for an event without clock times.+ pub scheduled_start: Option<DateTime<Utc>>,+ /// Scheduled end, or `None` for an event without clock times.+ pub scheduled_end: Option<DateTime<Utc>>,+}++impl MeetingLinkRequest {+ /// The meeting a draft event should carry: same title, and the same+ /// clock times when the event has them. All-day events leave the+ /// meeting unscheduled, exactly as the calendar UI does.+ pub fn for_draft(draft: &CalendarEventDraft) -> Self {+ let (scheduled_start, scheduled_end) = match &draft.time {+ EventTime::Timed {+ starts_at, ends_at, ..+ } => (Some(*starts_at), Some(*ends_at)),+ EventTime::AllDay { .. } => (None, None),+ };+ Self {+ title: draft.title.clone(),+ scheduled_start,+ scheduled_end,+ }+ }+}++/// A minted Macro meeting invitation.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct MeetingLink {+ /// Persistent meeting identifier, used to cancel the meeting again.+ pub id: Uuid,+ /// Browser URL anyone invited can open to join the call.+ pub url: String,+}++/// Failures minting or cancelling a Macro meeting link.+#[derive(Debug, thiserror::Error)]+pub enum MeetingLinkError {+ /// The meeting provider rejected the request as malformed.+ #[error("invalid meeting link request: {0}")]+ InvalidInput(String),+ /// The host cannot mint meeting links at all.+ #[error("Macro meeting links are not available in this host")]+ Unavailable,+ /// The meeting provider failed; the calendar event was not written.+ #[error("meeting link provider failed: {0}")]+ Failed(String),+}++/// A created event together with the Macro call it carries.+#[derive(Clone, Debug)]+pub struct EventWithMacroCall {+ /// The event as the provider echoed it back.+ pub event: CalendarEvent,+ /// The meeting written into the event's description and location.+ pub meeting_link: MeetingLink,+}++/// Failures creating an event that carries a Macro call.+#[derive(Debug, thiserror::Error)]+pub enum CreateEventWithMacroCallError {+ /// The calendar write failed. A meeting minted for it was cancelled on a+ /// best-effort basis unless the event may have reached the provider.+ #[error(transparent)]+ Calendar(#[from] CalendarMutationError),+ /// The meeting link could not be minted; nothing was written to the+ /// calendar.+ #[error("could not create the Macro call for the event: {0}")]+ MeetingLink(#[from] MeetingLinkError),+}++/// Text prefixing the generated join line. The calendar UI matches on it+/// to recognize the paragraph as generated rather than user-written.+const JOIN_LINE_LABEL: &str = "Join Macro call";++/// Write a meeting link into an event's location and description.+///+/// The description gains a trailing paragraph naming the call; the location+/// becomes the link only when the user supplied no physical location, so a+/// room is never overwritten. Both mirror the calendar UI's own attachment,+/// which is what lets it later find, strip, or replace the link.+pub fn attach_macro_call(+ description: Option<&str>,+ location: Option<&str>,+ url: &str,+) -> (String, String) {+ let description = description.unwrap_or_default();+ let separator = if description.is_empty() { "" } else { "\n" };+ let description =+ format!("{description}{separator}<p>{JOIN_LINE_LABEL}: <a href=\"{url}\">{url}</a></p>");+ let location = match location.map(str::trim) {+ Some(location) if !location.is_empty() => location.to_string(),+ _ => url.to_string(),+ };+ (description, location)+}++/// Create an event that carries a Macro call.+///+/// The meeting is minted first so the single invitation attendees receive+/// already names the call, instead of an invitation followed by an update.+/// A calendar write known to have failed before reaching the provider+/// cancels the fresh meeting on a best-effort basis so it does not linger+/// in the user's meeting list; an outcome that may have left the event (and+/// its link) at the provider keeps the meeting alive.+#[tracing::instrument(skip_all, err)]+pub async fn create_event_with_macro_call<M, L>(+ mutations: &M,+ meeting_links: &L,+ requester_id: &str,+ email_link_id: Option<Uuid>,+ calendar_id: Option<Uuid>,+ mut draft: CalendarEventDraft,+) -> Result<EventWithMacroCall, CreateEventWithMacroCallError>+where+ M: CalendarMutationService,+ L: MeetingLinkProvider,+{+ if draft.out_of_office.is_some() {+ return Err(CalendarMutationError::InvalidInput(+ "out-of-office events cannot have a Macro call".to_string(),+ )+ .into());+ }+ if draft.conference.is_some() {+ return Err(CalendarMutationError::InvalidInput(+ "an event carries either a Macro call or provider conferencing, not both".to_string(),+ )+ .into());+ }++ let link = meeting_links+ .create_meeting_link(requester_id, MeetingLinkRequest::for_draft(&draft))+ .await?;+ let (description, location) = attach_macro_call(+ draft.description.as_deref(),+ draft.location.as_deref(),+ &link.url,+ );+ draft.description = Some(description);+ draft.location = Some(location);++ match mutations+ .create_event(requester_id, email_link_id, calendar_id, draft)+ .await+ {+ Ok(event) => Ok(EventWithMacroCall {+ event,+ meeting_link: link,+ }),+ Err(error) => {+ if event_may_carry_link(&error) {+ tracing::warn!(+ error = ?error,+ meeting_id = %link.id,+ "keeping the meeting: the event carrying its link may have been written"+ );+ } else if let Err(cancel_error) = meeting_links+ .cancel_meeting_link(requester_id, link.id)+ .await+ {+ tracing::warn!(+ error = ?cancel_error,+ meeting_id = %link.id,+ "failed to cancel the meeting minted for an event that was not created"+ );+ }+ Err(error.into())+ }+ }+}++/// Whether a failed create may still have left an event at the provider.+///+/// `PersistFailed` means the provider accepted the event and only Macro's+/// copy lagged; `Retryable` covers transport failures whose delivery is+/// unknown, including a timeout after the write landed. Cancelling the+/// meeting in either case would strand attendees on a dead link, so an+/// unused meeting is the lesser cost. Every other variant is decided before+/// the provider write.+fn event_may_carry_link(error: &CalendarMutationError) -> bool {+ matches!(+ error,+ CalendarMutationError::PersistFailed(_) | CalendarMutationError::Retryable(_)+ )+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/meeting_links/test.rs b/crates/calendar_events/src/domain/meeting_links/test.rsnew file mode 100644index 0000000000..fd63af83e9--- /dev/null+++ b/crates/calendar_events/src/domain/meeting_links/test.rs@@ -0,0 +1,416 @@+use std::sync::Mutex;++use chrono::{NaiveDate, TimeZone, Utc};++use super::*;+use crate::domain::models::{+ AttendeeResponseStatus, CalendarEventPatch, ConferenceChange, EventReminders, EventStatus,+ EventTransparency, EventType, EventVisibility, OutOfOfficeProperties, VisibleCalendar,+};+use crate::domain::ports::{+ CalendarDeletionScope, CalendarRsvpScope, CalendarUpdateScope, UnavailableMeetingLinks,+};++const URL: &str = "https://macro.com/app/meet/join/0123456789abcdef0123456789abcdef";++fn sample_event() -> CalendarEvent {+ CalendarEvent {+ id: Uuid::from_u128(7),+ owner_id: "macro|[email protected]".to_string(),+ ical_uid: "uid-1".to_string(),+ calendar_id: Some(Uuid::from_u128(9)),+ sources: Vec::new(),+ title: "Standup".to_string(),+ description: None,+ location: None,+ status: EventStatus::Confirmed,+ visibility: EventVisibility::Default,+ transparency: EventTransparency::Opaque,+ event_type: EventType::Default,+ time: timed(),+ recurrence_lines: Vec::new(),+ organizer_email: None,+ organizer_name: None,+ creator_email: None,+ creator_name: None,+ conference_url: None,+ conference_provider: None,+ sequence: 0,+ is_read_only: false,+ attendees: Vec::new(),+ reminders: EventReminders::default(),+ created_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),+ updated_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),+ }+}++fn timed() -> EventTime {+ EventTime::Timed {+ starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),+ ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),+ time_zone: Some("America/New_York".to_string()),+ }+}++fn draft() -> CalendarEventDraft {+ CalendarEventDraft {+ idempotency_key: None,+ title: "Design review".to_string(),+ description: None,+ location: None,+ time: timed(),+ attendees: Vec::new(),+ recurrence_lines: Vec::new(),+ visibility: None,+ transparency: None,+ reminders: None,+ conference: None,+ out_of_office: None,+ }+}++#[derive(Default)]+struct FakeMutations {+ created: Mutex<Vec<CalendarEventDraft>>,+ create_error: Mutex<Option<CalendarMutationError>>,+}++impl FakeMutations {+ fn failing_with(error: CalendarMutationError) -> Self {+ Self {+ create_error: Mutex::new(Some(error)),+ ..Self::default()+ }+ }+}++impl CalendarMutationService for FakeMutations {+ async fn create_event(+ &self,+ _requester_id: &str,+ _email_link_id: Option<Uuid>,+ _calendar_id: Option<Uuid>,+ draft: CalendarEventDraft,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ if let Some(error) = self.create_error.lock().unwrap().take() {+ return Err(error);+ }+ self.created.lock().unwrap().push(draft);+ Ok(sample_event())+ }++ async fn list_visible_calendars(+ &self,+ _requester_id: &str,+ ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {+ unreachable!("creating with a Macro call lists no calendars")+ }++ async fn update_event(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ _calendar_id: Option<Uuid>,+ _patch: CalendarEventPatch,+ _scope: CalendarUpdateScope,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ unreachable!("the link is written with the create, never as a follow-up patch")+ }++ async fn delete_event(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ _calendar_id: Option<Uuid>,+ _scope: CalendarDeletionScope,+ ) -> Result<(), CalendarMutationError> {+ unreachable!("creating with a Macro call deletes nothing")+ }++ async fn respond_to_event(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ _calendar_id: Option<Uuid>,+ _response: AttendeeResponseStatus,+ _scope: CalendarRsvpScope,+ _responding_email: Option<String>,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ unreachable!("creating with a Macro call answers no invitation")+ }++ async fn disconnect_calendar(+ &self,+ _requester_id: &str,+ _email_link_id: Uuid,+ ) -> Result<(), CalendarMutationError> {+ unreachable!("creating with a Macro call disconnects nothing")+ }+}++#[derive(Default)]+struct FakeMeetingLinks {+ requests: Mutex<Vec<(String, MeetingLinkRequest)>>,+ cancelled: Mutex<Vec<(String, Uuid)>>,+ fail_create: bool,+}++impl MeetingLinkProvider for FakeMeetingLinks {+ async fn create_meeting_link(+ &self,+ requester_id: &str,+ request: MeetingLinkRequest,+ ) -> Result<MeetingLink, MeetingLinkError> {+ if self.fail_create {+ return Err(MeetingLinkError::Failed("call service down".to_string()));+ }+ self.requests+ .lock()+ .unwrap()+ .push((requester_id.to_string(), request));+ Ok(MeetingLink {+ id: Uuid::from_u128(42),+ url: URL.to_string(),+ })+ }++ async fn cancel_meeting_link(+ &self,+ requester_id: &str,+ meeting_id: Uuid,+ ) -> Result<(), MeetingLinkError> {+ self.cancelled+ .lock()+ .unwrap()+ .push((requester_id.to_string(), meeting_id));+ Ok(())+ }+}++#[test]+fn attaching_fills_an_empty_location_and_appends_a_join_paragraph() {+ let (description, location) = attach_macro_call(None, None, URL);+ assert_eq!(+ description,+ format!("<p>Join Macro call: <a href=\"{URL}\">{URL}</a></p>")+ );+ assert_eq!(location, URL);+}++#[test]+fn attaching_keeps_user_text_and_a_physical_location() {+ let (description, location) = attach_macro_call(Some("<p>Agenda</p>"), Some(" Room 4 "), URL);+ assert_eq!(+ description,+ format!("<p>Agenda</p>\n<p>Join Macro call: <a href=\"{URL}\">{URL}</a></p>")+ );+ assert_eq!(location, "Room 4");+}++#[test]+fn a_blank_location_counts_as_absent() {+ let (_, location) = attach_macro_call(None, Some(" "), URL);+ assert_eq!(location, URL);+}++#[test]+fn a_timed_draft_schedules_the_meeting_and_an_all_day_draft_does_not() {+ let timed = MeetingLinkRequest::for_draft(&draft());+ assert_eq!(timed.title, "Design review");+ assert_eq!(+ timed.scheduled_start,+ Some(Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap())+ );+ assert_eq!(+ timed.scheduled_end,+ Some(Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap())+ );++ let all_day = MeetingLinkRequest::for_draft(&CalendarEventDraft {+ time: EventTime::AllDay {+ start_date: NaiveDate::from_ymd_opt(2026, 8, 20).unwrap(),+ end_date: NaiveDate::from_ymd_opt(2026, 8, 21).unwrap(),+ },+ ..draft()+ });+ assert_eq!(all_day.scheduled_start, None);+ assert_eq!(all_day.scheduled_end, None);+}++#[tokio::test]+async fn the_meeting_is_minted_as_the_requester_and_written_into_the_draft() {+ let mutations = FakeMutations::default();+ let links = FakeMeetingLinks::default();+ let calendar_id = Uuid::from_u128(3);++ let created = create_event_with_macro_call(+ &mutations,+ &links,+ "macro|[email protected]",+ None,+ Some(calendar_id),+ CalendarEventDraft {+ description: Some("<p>Agenda</p>".to_string()),+ ..draft()+ },+ )+ .await+ .unwrap();+ assert_eq!(created.event.id, Uuid::from_u128(7));+ assert_eq!(created.meeting_link.url, URL);++ let requests = links.requests.lock().unwrap();+ let (requester, request) = requests.first().expect("one meeting minted");+ assert_eq!(requester, "macro|[email protected]");+ assert_eq!(request.title, "Design review");+ assert!(request.scheduled_start.is_some());++ let created = mutations.created.lock().unwrap();+ let written = created.first().expect("one event created");+ assert_eq!(written.location.as_deref(), Some(URL));+ assert_eq!(+ written.description.as_deref(),+ Some(+ format!("<p>Agenda</p>\n<p>Join Macro call: <a href=\"{URL}\">{URL}</a></p>").as_str()+ )+ );+ assert_eq!(written.conference, None);+ assert!(links.cancelled.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_calendar_write_refused_before_the_provider_cancels_the_fresh_meeting() {+ for refused in [+ CalendarMutationError::NoWritableCalendar,+ CalendarMutationError::ReadOnly,+ CalendarMutationError::InvalidInput("bad".to_string()),+ CalendarMutationError::ReauthRequired("expired".to_string()),+ CalendarMutationError::ProviderRejected("nope".to_string()),+ ] {+ let mutations = FakeMutations::failing_with(refused);+ let links = FakeMeetingLinks::default();++ let error = create_event_with_macro_call(+ &mutations,+ &links,+ "macro|[email protected]",+ None,+ None,+ draft(),+ )+ .await+ .unwrap_err();+ assert!(matches!(error, CreateEventWithMacroCallError::Calendar(_)));+ assert_eq!(+ *links.cancelled.lock().unwrap(),+ vec![("macro|[email protected]".to_string(), Uuid::from_u128(42))]+ );+ }+}++/// `PersistFailed` means Google already holds the event with its link, and a+/// transport failure may mean the same; revoking the meeting would strand+/// every attendee on a dead link.+#[tokio::test]+async fn an_event_that_may_have_reached_the_provider_keeps_its_meeting() {+ for ambiguous in [+ CalendarMutationError::PersistFailed("db down".to_string()),+ CalendarMutationError::Retryable("timeout".to_string()),+ ] {+ let mutations = FakeMutations::failing_with(ambiguous);+ let links = FakeMeetingLinks::default();++ let error = create_event_with_macro_call(+ &mutations,+ &links,+ "macro|[email protected]",+ None,+ None,+ draft(),+ )+ .await+ .unwrap_err();+ assert!(matches!(error, CreateEventWithMacroCallError::Calendar(_)));+ assert!(links.cancelled.lock().unwrap().is_empty());+ }+}++#[tokio::test]+async fn a_failed_meeting_writes_nothing_to_the_calendar() {+ let mutations = FakeMutations::default();+ let links = FakeMeetingLinks {+ fail_create: true,+ ..FakeMeetingLinks::default()+ };++ let error = create_event_with_macro_call(+ &mutations,+ &links,+ "macro|[email protected]",+ None,+ None,+ draft(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::Failed(_))+ ));+ assert!(mutations.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn out_of_office_and_provider_conferencing_are_refused_before_minting() {+ let mutations = FakeMutations::default();+ let links = FakeMeetingLinks::default();++ for draft in [+ CalendarEventDraft {+ out_of_office: Some(OutOfOfficeProperties::default()),+ ..draft()+ },+ CalendarEventDraft {+ conference: Some(ConferenceChange::GoogleMeet),+ ..draft()+ },+ ] {+ let error = create_event_with_macro_call(+ &mutations,+ &links,+ "macro|[email protected]",+ None,+ None,+ draft,+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ CreateEventWithMacroCallError::Calendar(CalendarMutationError::InvalidInput(_))+ ));+ }+ assert!(links.requests.lock().unwrap().is_empty());+ assert!(mutations.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn an_unwired_host_refuses_the_call_without_touching_the_calendar() {+ let mutations = FakeMutations::default();++ let error = create_event_with_macro_call(+ &mutations,+ &UnavailableMeetingLinks,+ "macro|[email protected]",+ None,+ None,+ draft(),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::Unavailable)+ ));+ assert!(mutations.created.lock().unwrap().is_empty());+}diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rsindex 261f3546af..7f3cfeb8c7 100644--- a/crates/calendar_events/src/domain/mod.rs+++ b/crates/calendar_events/src/domain/mod.rs@@ -8,6 +8,8 @@ pub mod acting;pub mod changes;/// Kafka event models for the calendar topic.pub mod events;+/// Macro meeting links carried by calendar events.+pub mod meeting_links;/// Domain models.pub mod models;/// User-initiated calendar mutation policy.diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 97bb219b50..631bc5a7b6 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -6,6 +6,7 @@ use chrono::{DateTime, Utc};use rootcause::Report;use uuid::Uuid;+use super::meeting_links::{MeetingLink, MeetingLinkError, MeetingLinkRequest};use super::models::{ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee,CalendarBackfillClaim, CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome,@@ -723,6 +724,52 @@ pub trait CalendarMutationService: Send + Sync + 'static {) -> impl Future<Output = Result<(), CalendarMutationError>> + Send;}+/// Outbound port minting Macro meetings for calendar events.+///+/// Implementations act as the requester: the meeting is owned by the user+/// whose event carries it, so only they can later edit or cancel it.+pub trait MeetingLinkProvider: Send + Sync + 'static {+ /// Mint a meeting the requester owns and return its join link.+ fn create_meeting_link(+ &self,+ requester_id: &str,+ request: MeetingLinkRequest,+ ) -> impl Future<Output = Result<MeetingLink, MeetingLinkError>> + Send;++ /// Cancel a meeting the requester owns. Used to roll back a meeting+ /// whose event never got written.+ fn cancel_meeting_link(+ &self,+ requester_id: &str,+ meeting_id: Uuid,+ ) -> impl Future<Output = Result<(), MeetingLinkError>> + Send;+}++/// Unwired meeting-link port for hosts that expose calendar operations but+/// have no call service. Every method fails with+/// [`MeetingLinkError::Unavailable`], so an event asking for a Macro call+/// is refused before anything reaches the calendar.+#[derive(Clone, Copy, Debug, Default)]+pub struct UnavailableMeetingLinks;++impl MeetingLinkProvider for UnavailableMeetingLinks {+ async fn create_meeting_link(+ &self,+ _requester_id: &str,+ _request: MeetingLinkRequest,+ ) -> Result<MeetingLink, MeetingLinkError> {+ Err(MeetingLinkError::Unavailable)+ }++ async fn cancel_meeting_link(+ &self,+ _requester_id: &str,+ _meeting_id: Uuid,+ ) -> Result<(), MeetingLinkError> {+ Err(MeetingLinkError::Unavailable)+ }+}+/// Use-case failures surfaced by calendar mutations.#[derive(Debug, thiserror::Error)]pub enum CalendarMutationError {diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rsindex 065a883617..e113e2e302 100644--- a/crates/calendar_events/src/inbound/toolset.rs+++ b/crates/calendar_events/src/inbound/toolset.rs@@ -24,11 +24,15 @@ use schemars::JsonSchema;use serde::{Deserialize, Serialize};use crate::domain::{+ meeting_links::{CreateEventWithMacroCallError, EventWithMacroCall, MeetingLinkError},models::{CalendarAttendeeInput, CalendarEvent, EventReminderOverride, EventReminders, EventTime,OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,},- ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService},+ ports::{+ CalendarMutationError, CalendarMutationService, CalendarOccurrenceService,+ MeetingLinkProvider,+ },};pub use create_calendar_event::CreateCalendarEvent;@@ -45,54 +49,63 @@ pub use update_calendar_event::{};/// Service context for calendar AI tools.-pub struct CalendarToolContext<M, O>+pub struct CalendarToolContext<M, O, L>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{/// Write path: user-initiated mutations, written through to the provider.pub mutations: Arc<M>,/// Read path: bounded occurrence viewport queries.pub occurrences: Arc<O>,+ /// Macro meetings minted for events that carry a Macro call.+ pub meeting_links: Arc<L>,}-impl<M, O> Clone for CalendarToolContext<M, O>+impl<M, O, L> Clone for CalendarToolContext<M, O, L>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{fn clone(&self) -> Self {Self {mutations: Arc::clone(&self.mutations),occurrences: Arc::clone(&self.occurrences),+ meeting_links: Arc::clone(&self.meeting_links),}}}-impl<M, O> CalendarToolContext<M, O>+impl<M, O, L> CalendarToolContext<M, O, L>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{- /// Create a calendar tool context from its two ports.- pub fn new(mutations: Arc<M>, occurrences: Arc<O>) -> Self {+ /// Create a calendar tool context from its ports. Hosts without a call+ /// service pass [`crate::domain::ports::UnavailableMeetingLinks`].+ pub fn new(mutations: Arc<M>, occurrences: Arc<O>, meeting_links: Arc<L>) -> Self {Self {mutations,occurrences,+ meeting_links,}}}-fn shared_calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>+fn shared_calendar_toolset<M, O, L>() -> AsyncToolCollection<CalendarToolContext<M, O, L>>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{AsyncToolCollection::new()- .add_tool::<ListCalendarEvents, CalendarToolContext<M, O>>()- .add_tool::<ListCalendars, CalendarToolContext<M, O>>()- .add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O>>()- .add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O>>()+ .add_tool::<ListCalendarEvents, CalendarToolContext<M, O, L>>()+ .add_tool::<ListCalendars, CalendarToolContext<M, O, L>>()+ .add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O, L>>()+ .add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O, L>>()}/// The full calendar toolset, for hosts that finish user tools: the deferring@@ -101,14 +114,15 @@ where/// already gave in conversation. Both are always registered; the prompt/// decides which fits the surface the prompt came from. Reads, updates, and/// deletions execute in the agent loop.-pub fn calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>+pub fn calendar_toolset<M, O, L>() -> AsyncToolCollection<CalendarToolContext<M, O, L>>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{shared_calendar_toolset()- .add_user_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()- .add_tool::<CreateConfirmedCalendarEvent, CalendarToolContext<M, O>>()+ .add_user_tool::<CreateCalendarEvent, CalendarToolContext<M, O, L>>()+ .add_tool::<CreateConfirmedCalendarEvent, CalendarToolContext<M, O, L>>()}/// Create the calendar toolset for hosts without a composer — the MCP server@@ -119,12 +133,13 @@ where/// which only the chat frontend can finish. `CreateConfirmedCalendarEvent`/// is left out: it is for the in-process agent's conversation turns, and/// here the plain tool already creates directly.-pub fn mcp_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>+pub fn mcp_toolset<M, O, L>() -> AsyncToolCollection<CalendarToolContext<M, O, L>>whereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{- shared_calendar_toolset().add_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()+ shared_calendar_toolset().add_tool::<CreateCalendarEvent, CalendarToolContext<M, O, L>>()}/// The mutually exclusive time shape supplied to calendar tools.@@ -347,6 +362,9 @@ pub struct ToolCalendarEvent {pub organizer_email: Option<String>,/// Conference join URL, when a conference is attached.pub conference_url: Option<String>,+ /// Join URL of the Macro call created with the event, when+ /// CreateCalendarEvent was asked for one.+ pub macro_call_url: Option<String>,/// Whether the user's calendar prohibits modifying this event.pub is_read_only: bool,/// Calendar the event belongs to, when known.@@ -420,10 +438,18 @@ impl ToolCalendarEvent {attendee_count: event.attendees.len(),organizer_email: event.organizer_email.clone(),conference_url: event.conference_url.clone(),+ macro_call_url: None,is_read_only: event.is_read_only,calendar_id: event.calendar_id,}}++ fn from_event_with_macro_call(created: &EventWithMacroCall) -> Self {+ Self {+ macro_call_url: Some(created.meeting_link.url.clone()),+ ..Self::from_event(&created.event)+ }+ }}/// Map a domain mutation failure to an agent-readable tool error.@@ -474,3 +500,35 @@ fn mutation_tool_error(action: &str, error: CalendarMutationError) -> ToolCallErinternal_error: error.into(),}}++/// Map a failure creating an event with a Macro call to an agent-readable+/// tool error. Calendar failures read exactly like a plain create; meeting+/// failures say that nothing reached the calendar.+fn macro_call_create_tool_error(error: CreateEventWithMacroCallError) -> ToolCallError {+ match error {+ CreateEventWithMacroCallError::Calendar(error) => {+ mutation_tool_error("create the calendar event", error)+ }+ CreateEventWithMacroCallError::MeetingLink(error) => {+ let description = match &error {+ MeetingLinkError::InvalidInput(message) => {+ format!("The Macro call could not be created: {message}")+ }+ MeetingLinkError::Unavailable => {+ "Macro calls cannot be created from here. Retry with `addMacroCall` false, \+ or use `addGoogleMeet` for video conferencing."+ .to_string()+ }+ MeetingLinkError::Failed(_) => {+ "The Macro call could not be created right now. Nothing was added to the \+ calendar; try again shortly."+ .to_string()+ }+ };+ ToolCallError {+ description: format!("Failed to create the calendar event: {description}"),+ internal_error: error.into(),+ }+ }+ }+}diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rsindex 1743871970..a8ba1bef62 100644--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs@@ -11,11 +11,13 @@ use serde::Deserialize;use super::{AttendeeInput, CalendarEventTypeInput, CalendarToolContext, EventRemindersInput,- EventTimeInput, OutOfOfficeInput, ToolCalendarEvent, mutation_tool_error,+ EventTimeInput, OutOfOfficeInput, ToolCalendarEvent, macro_call_create_tool_error,+ mutation_tool_error,};use crate::domain::{+ meeting_links::create_event_with_macro_call,models::{CalendarEventDraft, ConferenceChange},- ports::{CalendarMutationService, CalendarOccurrenceService},+ ports::{CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider},};/// Create a calendar event.@@ -39,11 +41,18 @@ targets another one. For recurring events pass RFC 5545 lines in `recurrenceLine[\"RRULE:FREQ=WEEKLY;BYDAY=MO\"]. Returns the created event with its `eventId` for later \updates or deletion. Fails if the user has no writable calendar connected.\n\\n\+For video conferencing pick at most one of `addMacroCall` (a Macro meeting link, the \+default choice for a Macro user's meeting) or `addGoogleMeet` (a Google Meet conference). \+A Macro call is created for the user, scheduled to the event's times, and its join link is \+appended to the event's description so every attendee's invitation carries it; it also \+becomes the event's `location` unless a physical `location` was supplied. The returned \+event's `macroCallUrl` holds the link.\n\+\n\Set `eventType` to \"out_of_office\" to mark the user as out of office (e.g. \"mark me out \of office Thursday\"). Out-of-office events must land on the user's primary calendar (omit \-`calendarId`), must be timed rather than all-day, and take no attendees or Google Meet \-(leave `addGoogleMeet` false); use `outOfOffice` to control whether conflicting meetings \-are auto-declined. The type cannot be changed afterward."+`calendarId`), must be timed rather than all-day, and take no attendees or video \+conferencing (leave `addMacroCall` and `addGoogleMeet` false); use `outOfOffice` to control \+whether conflicting meetings are auto-declined. The type cannot be changed afterward.")]pub struct CreateCalendarEvent {/// Display title.@@ -99,9 +108,19 @@ pub struct CreateCalendarEvent {#[serde(default)]pub reminders: Option<EventRemindersInput>,+ /// Whether to attach a Macro meeting link.+ #[schemars(+ description = "Attach a freshly created Macro call to the event: a Macro meeting link \+ scheduled to the event's times, written into the event's location and \+ description. Mutually exclusive with `addGoogleMeet`."+ )]+ #[serde(default)]+ pub add_macro_call: bool,+/// Whether to attach a Google Meet conference.#[schemars(- description = "Attach a freshly generated Google Meet video conference to the event."+ description = "Attach a freshly generated Google Meet video conference to the event. \+ Mutually exclusive with `addMacroCall`.")]#[serde(default)]pub add_google_meet: bool,@@ -132,26 +151,40 @@ impl ToolAnnotated for CreateCalendarEvent {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for CreateCalendarEvent+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for CreateCalendarEventwhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = ToolCalendarEvent;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(calendar_id=?self.calendar_id,attendee_count = self.attendees.len(),+ add_macro_call = self.add_macro_call,add_google_meet = self.add_google_meet,"Create calendar event");+ if self.add_macro_call && self.add_google_meet {+ return Err(ToolCallError {+ description: "`addMacroCall` and `addGoogleMeet` are mutually exclusive; pick \+ one kind of video conferencing."+ .to_string(),+ internal_error: anyhow::Error::from_boxed(+ rootcause::report!("both Macro call and Google Meet requested")+ .into_boxed_error(),+ ),+ });+ }+let requester_id = request_context.user_id.to_string();let out_of_office = match self.event_type {CalendarEventTypeInput::Default => {@@ -187,6 +220,20 @@ whereout_of_office,};+ if self.add_macro_call {+ let created = create_event_with_macro_call(+ &*service_context.mutations,+ &*service_context.meeting_links,+ &requester_id,+ None,+ self.calendar_id,+ draft,+ )+ .await+ .map_err(macro_call_create_tool_error)?;+ return Ok(ToolCalendarEvent::from_event_with_macro_call(&created));+ }+let event = service_context.mutations.create_event(&requester_id, None, self.calendar_id, draft)diff --git a/crates/calendar_events/src/inbound/toolset/create_confirmed_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_confirmed_calendar_event.rsindex b0cb312b11..f1408e54bb 100644--- a/crates/calendar_events/src/inbound/toolset/create_confirmed_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/create_confirmed_calendar_event.rs@@ -33,7 +33,9 @@ use serde::Deserialize;use super::create_calendar_event::CreateCalendarEvent;use super::{CalendarToolContext, ToolCalendarEvent};-use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};+use crate::domain::ports::{+ CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider,+};/// Create a calendar event the user has already approved in conversation.///@@ -43,7 +45,7 @@ use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};#[derive(Debug, Deserialize, JsonSchema, Clone)]#[schemars(title = "CreateConfirmedCalendarEvent",- description = "Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations."+ description = "Create a calendar event immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The event is always shown before it is created, even when the user's request already spelled the whole thing out: in one turn write it into the thread - title, date and time with its time zone, duration, guests, location, Google Meet or Macro call, recurrence - ask whether to create it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific event, quoting that reply verbatim in userConfirmation. Being asked to schedule something is a request to draft the event, never approval to create it, so a userConfirmation quoting the request that asked you to set it up - rather than the reply approving the event you wrote out - is wrong. Never call it in the agent session view or in chat: use CreateCalendarEvent there, whose review card or composer is the confirmation. Takes the same fields as CreateCalendarEvent; the event is written to Google Calendar at once and any attendees receive invitations.")]#[serde(rename_all = "camelCase")]pub struct CreateConfirmedCalendarEvent {@@ -63,17 +65,18 @@ impl ToolAnnotated for CreateConfirmedCalendarEvent {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for CreateConfirmedCalendarEvent+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for CreateConfirmedCalendarEventwhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = ToolCalendarEvent;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {// The schema makes the field required, so a call gets here with one;diff --git a/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rsindex 964266e054..52158b5922 100644--- a/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs@@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};use super::{CalendarToolContext, mutation_tool_error};use crate::domain::ports::{- CalendarDeletionScope, CalendarMutationService, CalendarOccurrenceService,+ CalendarDeletionScope, CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider,};/// How much of a recurring series a deletion removes.@@ -89,17 +89,18 @@ impl ToolAnnotated for DeleteCalendarEvent {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for DeleteCalendarEvent+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for DeleteCalendarEventwhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = DeleteCalendarEventResponse;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(params=?self, "Delete calendar event");diff --git a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rsindex 1fbf9a5cd2..6eb792f8e4 100644--- a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs+++ b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};use super::{CalendarToolContext, ToolEventAttendee, description_preview, time_fields};use crate::domain::{models::{CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceListing, OccurrenceRange},- ports::{CalendarMutationService, CalendarOccurrenceService},+ ports::{CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider},service::CalendarValidationError,};@@ -140,17 +140,18 @@ impl ToolAnnotated for ListCalendarEvents {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for ListCalendarEvents+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for ListCalendarEventswhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = ListCalendarEventsResponse;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(params=?self, "List calendar events");diff --git a/crates/calendar_events/src/inbound/toolset/list_calendars.rs b/crates/calendar_events/src/inbound/toolset/list_calendars.rsindex ce8a71cc13..cf9c086ad2 100644--- a/crates/calendar_events/src/inbound/toolset/list_calendars.rs+++ b/crates/calendar_events/src/inbound/toolset/list_calendars.rs@@ -8,7 +8,9 @@ use schemars::JsonSchema;use serde::{Deserialize, Serialize};use super::{CalendarToolContext, mutation_tool_error};-use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};+use crate::domain::ports::{+ CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider,+};/// A calendar surfaced to the AI.#[derive(Debug, Serialize, JsonSchema)]@@ -59,17 +61,18 @@ impl ToolAnnotated for ListCalendars {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for ListCalendars+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for ListCalendarswhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = ListCalendarsToolResponse;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!("List calendars");diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rsindex f5a5c86539..b25b15775a 100644--- a/crates/calendar_events/src/inbound/toolset/test.rs+++ b/crates/calendar_events/src/inbound/toolset/test.rs@@ -7,6 +7,7 @@ use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;use super::*;+use crate::domain::meeting_links::{MeetingLink, MeetingLinkError, MeetingLinkRequest};use crate::domain::models::{AttendeeResponseStatus, CalendarAttendee, CalendarEventDraft, CalendarEventPatch,CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminderOverride,@@ -15,7 +16,7 @@ use crate::domain::models::{};use crate::domain::ports::{CalendarDeletionScope, CalendarMutationError, CalendarMutationService,- CalendarOccurrenceService, CalendarRsvpScope, CalendarUpdateScope,+ CalendarOccurrenceService, CalendarRsvpScope, CalendarUpdateScope, MeetingLinkProvider,};#[test]@@ -303,16 +304,69 @@ impl CalendarOccurrenceService for MockOccurrences {}}+const MEETING_URL: &str = "https://macro.com/app/meet/join/0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";++#[derive(Default)]+struct MockMeetingLinks {+ requests: Mutex<Vec<MeetingLinkRequest>>,+ cancelled: Mutex<Vec<Uuid>>,+ create_error: Mutex<Option<MeetingLinkError>>,+}++impl MeetingLinkProvider for MockMeetingLinks {+ async fn create_meeting_link(+ &self,+ _requester_id: &str,+ request: MeetingLinkRequest,+ ) -> Result<MeetingLink, MeetingLinkError> {+ if let Some(error) = self.create_error.lock().unwrap().take() {+ return Err(error);+ }+ self.requests.lock().unwrap().push(request);+ Ok(MeetingLink {+ id: Uuid::from_u128(42),+ url: MEETING_URL.to_string(),+ })+ }++ async fn cancel_meeting_link(+ &self,+ _requester_id: &str,+ meeting_id: Uuid,+ ) -> Result<(), MeetingLinkError> {+ self.cancelled.lock().unwrap().push(meeting_id);+ Ok(())+ }+}++type MockContext = CalendarToolContext<MockMutations, MockOccurrences, MockMeetingLinks>;+fn context(mutations: MockMutations,occurrences: MockOccurrences,+) -> (std::sync::Arc<MockMutations>, ServiceContext<MockContext>) {+ let (mutations, _, context) =+ context_with_meeting_links(mutations, occurrences, MockMeetingLinks::default());+ (mutations, context)+}++fn context_with_meeting_links(+ mutations: MockMutations,+ occurrences: MockOccurrences,+ meeting_links: MockMeetingLinks,) -> (std::sync::Arc<MockMutations>,- ServiceContext<CalendarToolContext<MockMutations, MockOccurrences>>,+ std::sync::Arc<MockMeetingLinks>,+ ServiceContext<MockContext>,) {let mutations = std::sync::Arc::new(mutations);- let context = CalendarToolContext::new(mutations.clone(), std::sync::Arc::new(occurrences));- (mutations, ServiceContext(context))+ let meeting_links = std::sync::Arc::new(meeting_links);+ let context = CalendarToolContext::new(+ mutations.clone(),+ std::sync::Arc::new(occurrences),+ meeting_links.clone(),+ );+ (mutations, meeting_links, ServiceContext(context))}fn request_context() -> RequestContext {@@ -505,6 +559,7 @@ async fn create_converts_input_into_a_domain_draft() {minutes: 15,}],}),+ add_macro_call: false,add_google_meet: true,event_type: CalendarEventTypeInput::Default,out_of_office: None,@@ -554,6 +609,7 @@ async fn create_maps_out_of_office_input_into_the_draft() {recurrence_lines: Vec::new(),calendar_id: None,reminders: None,+ add_macro_call: false,add_google_meet: false,event_type: CalendarEventTypeInput::OutOfOffice,out_of_office: Some(OutOfOfficeInput {@@ -593,6 +649,7 @@ async fn create_rejects_out_of_office_settings_on_a_default_event() {recurrence_lines: Vec::new(),calendar_id: None,reminders: None,+ add_macro_call: false,add_google_meet: false,event_type: CalendarEventTypeInput::Default,out_of_office: Some(OutOfOfficeInput::default()),@@ -622,6 +679,7 @@ async fn create_surfaces_missing_calendar_as_an_actionable_error() {recurrence_lines: Vec::new(),calendar_id: None,reminders: None,+ add_macro_call: false,add_google_meet: false,event_type: CalendarEventTypeInput::Default,out_of_office: None,@@ -636,6 +694,176 @@ async fn create_surfaces_missing_calendar_as_an_actionable_error() {);}+fn macro_call_tool() -> CreateCalendarEvent {+ CreateCalendarEvent {+ title: "Design review".to_string(),+ time: EventTimeInput::Timed {+ starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),+ ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),+ time_zone: Some("America/New_York".to_string()),+ },+ description: Some("<p>Agenda</p>".to_string()),+ location: None,+ attendees: vec![AttendeeInput {+ email: "[email protected]".to_string(),+ is_optional: false,+ }],+ recurrence_lines: Vec::new(),+ calendar_id: Some(Uuid::from_u128(3)),+ reminders: None,+ add_macro_call: true,+ add_google_meet: false,+ event_type: CalendarEventTypeInput::Default,+ out_of_office: None,+ }+}++#[tokio::test]+async fn create_with_a_macro_call_mints_a_meeting_and_writes_its_link_into_the_event() {+ let (mutations, meeting_links, context) = context_with_meeting_links(+ MockMutations::default(),+ empty_occurrences(),+ MockMeetingLinks::default(),+ );++ let response = macro_call_tool()+ .call(context, request_context())+ .await+ .unwrap();+ assert_eq!(response.event_id, Uuid::from_u128(7));+ assert_eq!(response.macro_call_url.as_deref(), Some(MEETING_URL));++ let requests = meeting_links.requests.lock().unwrap();+ let request = requests.first().expect("one meeting minted");+ assert_eq!(request.title, "Design review");+ assert_eq!(+ request.scheduled_start,+ Some(Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap())+ );+ assert_eq!(+ request.scheduled_end,+ Some(Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap())+ );++ let created = mutations.created.lock().unwrap();+ let (_, target_calendar, draft) = created.first().expect("one create call");+ assert_eq!(*target_calendar, Some(Uuid::from_u128(3)));+ assert_eq!(draft.location.as_deref(), Some(MEETING_URL));+ assert_eq!(+ draft.description.as_deref(),+ Some(+ format!(+ "<p>Agenda</p>\n<p>Join Macro call: <a href=\"{MEETING_URL}\">{MEETING_URL}</a></p>"+ )+ .as_str()+ )+ );+ assert_eq!(draft.conference, None);+ assert_eq!(draft.attendees.len(), 1);+ assert!(meeting_links.cancelled.lock().unwrap().is_empty());+}++#[tokio::test]+async fn mcp_toolset_accepts_add_macro_call() {+ let (mutations, meeting_links, context) = context_with_meeting_links(+ MockMutations::default(),+ empty_occurrences(),+ MockMeetingLinks::default(),+ );+ let mut args = create_tool_args();+ args["addMacroCall"] = serde_json::json!(true);++ let event = mcp_toolset()+ .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)+ .await+ .unwrap()+ .unwrap();++ assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());+ assert_eq!(event["macroCallUrl"], MEETING_URL);+ assert_eq!(meeting_links.requests.lock().unwrap().len(), 1);+ assert_eq!(mutations.created.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn create_refuses_both_a_macro_call_and_a_google_meet() {+ let (mutations, meeting_links, context) = context_with_meeting_links(+ MockMutations::default(),+ empty_occurrences(),+ MockMeetingLinks::default(),+ );++ let error = CreateCalendarEvent {+ add_google_meet: true,+ ..macro_call_tool()+ }+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(+ error.description.contains("mutually exclusive"),+ "unexpected description: {}",+ error.description+ );+ assert!(meeting_links.requests.lock().unwrap().is_empty());+ assert!(mutations.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn create_with_a_macro_call_rolls_the_meeting_back_when_the_calendar_write_fails() {+ let (mutations, meeting_links, context) = context_with_meeting_links(+ MockMutations {+ create_error: Mutex::new(Some(CalendarMutationError::NoWritableCalendar)),+ ..Default::default()+ },+ empty_occurrences(),+ MockMeetingLinks::default(),+ );++ let error = macro_call_tool()+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(+ error+ .description+ .contains("not connected a Google Calendar"),+ "unexpected description: {}",+ error.description+ );+ assert_eq!(+ *meeting_links.cancelled.lock().unwrap(),+ vec![Uuid::from_u128(42)]+ );+ assert!(mutations.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn create_with_a_macro_call_explains_an_unwired_host() {+ let (mutations, _, context) = context_with_meeting_links(+ MockMutations::default(),+ empty_occurrences(),+ MockMeetingLinks {+ create_error: Mutex::new(Some(MeetingLinkError::Unavailable)),+ ..Default::default()+ },+ );++ let error = macro_call_tool()+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(+ error.description.contains("addGoogleMeet"),+ "unexpected description: {}",+ error.description+ );+ assert!(mutations.created.lock().unwrap().is_empty());+}+#[tokio::test]async fn update_converts_input_into_a_domain_patch() {let (mutations, context) = context(MockMutations::default(), empty_occurrences());diff --git a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rsindex 21aac7c999..d9d6309fe1 100644--- a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs@@ -17,6 +17,7 @@ use crate::domain::{models::{AttendeeResponseStatus, CalendarEventPatch, ConferenceChange},ports::{CalendarMutationService, CalendarOccurrenceService, CalendarRsvpScope, CalendarUpdateScope,+ MeetingLinkProvider,},};@@ -221,17 +222,18 @@ impl ToolAnnotated for UpdateCalendarEvent {}#[async_trait]-impl<M, O> AsyncTool<CalendarToolContext<M, O>> for UpdateCalendarEvent+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for UpdateCalendarEventwhereM: CalendarMutationService,O: CalendarOccurrenceService,+ L: MeetingLinkProvider,{type Output = ToolCalendarEvent;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<CalendarToolContext<M, O>>,+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(diff --git a/crates/calendar_events/src/lib.rs b/crates/calendar_events/src/lib.rsindex 46e99af9c5..c8c312a412 100644--- a/crates/calendar_events/src/lib.rs+++ b/crates/calendar_events/src/lib.rs@@ -16,6 +16,7 @@ pub mod inbound;feature = "postgres",feature = "dispatch-sqs",feature = "notify",- feature = "mutation-client"+ feature = "mutation-client",+ feature = "call-meetings"))]pub mod outbound;diff --git a/crates/calendar_events/src/outbound/call_meeting_links.rs b/crates/calendar_events/src/outbound/call_meeting_links.rsnew file mode 100644index 0000000000..03f9fd18bc--- /dev/null+++ b/crates/calendar_events/src/outbound/call_meeting_links.rs@@ -0,0 +1,118 @@+//! Meeting-link adapter over the call domain service.+//!+//! Mints standalone Macro meetings owned by the requester, the same ones the+//! calendar UI creates through `POST /call/meetings`, and renders the join+//! URL the frontend recognizes as a Macro call.++use std::sync::Arc;++use call::domain::meetings::{CreateMeetingRequest, MAX_MEETING_TITLE_CHARS};+use call::domain::models::CallError;+use call::domain::ports::CallService;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use crate::domain::meeting_links::{MeetingLink, MeetingLinkError, MeetingLinkRequest};+use crate::domain::ports::MeetingLinkProvider;++/// Router path of the meeting setup page, relative to the app origin.+const MEETING_JOIN_PATH: &str = "/app/meet/join/";++/// [`MeetingLinkProvider`] backed by the call domain service.+pub struct CallServiceMeetingLinks<S: CallService> {+ service: Arc<S>,+ app_origin: String,+}++impl<S: CallService> CallServiceMeetingLinks<S> {+ /// Wrap the call service. `app_origin` is the browser origin join links+ /// are built on, e.g. `https://macro.com`; a trailing slash is ignored.+ pub fn new(service: Arc<S>, app_origin: impl Into<String>) -> Self {+ Self {+ service,+ app_origin: app_origin.into().trim_end_matches('/').to_string(),+ }+ }+}++fn join_url(app_origin: &str, share_token: &str) -> String {+ format!("{app_origin}{MEETING_JOIN_PATH}{share_token}")+}++/// Fit an event title into the meeting provider's contract: no control+/// characters, at most [`MAX_MEETING_TITLE_CHARS`], and `None` when nothing+/// is left so the provider's default title applies.+fn meeting_title(title: &str) -> Option<String> {+ let title: String = title+ .chars()+ .map(|character| {+ if character.is_control() {+ ' '+ } else {+ character+ }+ })+ .collect::<String>()+ .trim()+ .chars()+ .take(MAX_MEETING_TITLE_CHARS)+ .collect();+ let title = title.trim().to_string();+ (!title.is_empty()).then_some(title)+}++fn requester<'a>(requester_id: &'a str) -> Result<MacroUserIdStr<'a>, MeetingLinkError> {+ MacroUserIdStr::parse_from_str(requester_id)+ .map_err(|error| MeetingLinkError::InvalidInput(format!("invalid requester id: {error}")))+}++fn map_call_error(error: CallError) -> MeetingLinkError {+ match error {+ CallError::InvalidRequest(message) => MeetingLinkError::InvalidInput(message),+ other => MeetingLinkError::Failed(other.to_string()),+ }+}++impl<S: CallService> MeetingLinkProvider for CallServiceMeetingLinks<S> {+ #[tracing::instrument(skip_all, err)]+ async fn create_meeting_link(+ &self,+ requester_id: &str,+ request: MeetingLinkRequest,+ ) -> Result<MeetingLink, MeetingLinkError> {+ let meeting = self+ .service+ .create_meeting(+ requester(requester_id)?,+ CreateMeetingRequest {+ // No room is pre-reserved: a scheduled meeting allocates+ // its room on first join, like one made from the calendar.+ preparation_id: None,+ title: meeting_title(&request.title),+ scheduled_start: request.scheduled_start,+ scheduled_end: request.scheduled_end,+ },+ )+ .await+ .map_err(map_call_error)?;+ Ok(MeetingLink {+ id: meeting.id,+ url: join_url(&self.app_origin, meeting.share_token.as_str()),+ })+ }++ #[tracing::instrument(skip_all, err)]+ async fn cancel_meeting_link(+ &self,+ requester_id: &str,+ meeting_id: Uuid,+ ) -> Result<(), MeetingLinkError> {+ self.service+ .cancel_meeting(requester(requester_id)?, &meeting_id)+ .await+ .map_err(map_call_error)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/outbound/call_meeting_links/test.rs b/crates/calendar_events/src/outbound/call_meeting_links/test.rsnew file mode 100644index 0000000000..4b0b17019c--- /dev/null+++ b/crates/calendar_events/src/outbound/call_meeting_links/test.rs@@ -0,0 +1,54 @@+use super::*;++#[test]+fn titles_are_fitted_to_the_meeting_contract() {+ assert_eq!(+ meeting_title(" Design review "),+ Some("Design review".to_string())+ );+ assert_eq!(meeting_title(""), None);+ assert_eq!(meeting_title(" "), None);+ assert_eq!(+ meeting_title("Line one\nline two"),+ Some("Line one line two".to_string())+ );+ let long = "x".repeat(MAX_MEETING_TITLE_CHARS + 50);+ assert_eq!(+ meeting_title(&long).map(|title| title.chars().count()),+ Some(MAX_MEETING_TITLE_CHARS)+ );+}++#[test]+fn join_links_use_the_setup_route_the_frontend_recognizes() {+ let token = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";+ assert_eq!(+ join_url("https://macro.com", token),+ format!("https://macro.com/app/meet/join/{token}")+ );+ assert_eq!(+ join_url("http://localhost:3000".trim_end_matches('/'), token),+ format!("http://localhost:3000/app/meet/join/{token}")+ );+}++#[test]+fn provider_validation_failures_surface_as_invalid_input() {+ assert!(matches!(+ map_call_error(CallError::InvalidRequest("bad".to_string())),+ MeetingLinkError::InvalidInput(message) if message == "bad"+ ));+ assert!(matches!(+ map_call_error(CallError::Auth),+ MeetingLinkError::Failed(_)+ ));+}++#[test]+fn requester_ids_must_be_macro_user_ids() {+ assert!(requester("macro|[email protected]").is_ok());+ assert!(matches!(+ requester("not a user id"),+ Err(MeetingLinkError::InvalidInput(_))+ ));+}diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rsindex 6e7d298a3c..b9579573b7 100644--- a/crates/calendar_events/src/outbound/mod.rs+++ b/crates/calendar_events/src/outbound/mod.rs@@ -3,6 +3,9 @@/// Calendar-service HTTP adapter for the mutation port.#[cfg(feature = "mutation-client")]pub mod calendar_service_mutations;+/// Meeting-link adapter over the call domain service.+#[cfg(feature = "call-meetings")]+pub mod call_meeting_links;/// Google Calendar API adapter.#[cfg(feature = "google")]pub mod google;diff --git a/crates/call/src/domain/meetings.rs b/crates/call/src/domain/meetings.rsindex d3f8960962..9718d89f48 100644--- a/crates/call/src/domain/meetings.rs+++ b/crates/call/src/domain/meetings.rs@@ -77,6 +77,9 @@ pub struct Meeting {pub channel_call_id: Option<Uuid>,}+/// Longest accepted meeting title, in characters.+pub const MAX_MEETING_TITLE_CHARS: usize = 200;+/// Inputs for creating a meeting without starting its RTC room.#[derive(Debug, serde::Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]@@ -100,10 +103,13 @@ impl CreateMeetingRequest {.unwrap_or_else(|| "Macro call".to_string()).trim().to_string();- if title.is_empty() || title.chars().count() > 200 || title.chars().any(char::is_control) {- return Err(CallError::InvalidRequest(- "Meeting title must contain 1–200 characters".to_string(),- ));+ if title.is_empty()+ || title.chars().count() > MAX_MEETING_TITLE_CHARS+ || title.chars().any(char::is_control)+ {+ return Err(CallError::InvalidRequest(format!(+ "Meeting title must contain 1–{MAX_MEETING_TITLE_CHARS} characters"+ )));}match (self.scheduled_start, self.scheduled_end) {(None, None) => {}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex a433dd0d0a..dc6c40bab4 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1594,6 +1594,12 @@ Editing or rescheduling an owned event retains and updates its selected Macro caSelecting `Macro call` on an owned editable event without one adds a call on save;choosing another option removes its generated Macro link from the invitation.Removing the link or deleting the calendar event does not revoke the reusable call.+The AI's `CreateCalendarEvent` composer (chat, agent sessions, channel review cards)+offers the same selector under the same quick-calls flag; `Macro call` there maps to+the tool's `addMacroCall`, and the call is created when the tool executes, before the+event is written, so the single invitation already carries the link. The MCP server+and channel bot accept `addMacroCall` directly. `addMacroCall` and `addGoogleMeet`+are mutually exclusive, and out-of-office entries accept neither.The sidebar's `Calendars` section folds each connected account into a collapsiblegroup: a caret plus the account address header with a checkbox that shows or hides all ofdiff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 5aca068c04..485ffa8f58 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -467,6 +467,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arpool.clone(),macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),"test-internal-api-key".to_string(),+ call_tool_context.service.clone(),+ macro_service_urls::AppServiceUrl::local(),);let forms_tool_context = ai_tools::build_forms_tool_context(pool.clone(),@@ -507,6 +509,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arpool.clone(),macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),"test-internal-api-key".to_string(),+ call_tool_context.service.clone(),+ macro_service_urls::AppServiceUrl::local(),),team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(pool.clone(), true),notification_tool_context: notification_tool_context.clone(),diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rsindex acd3f42d2a..b61f64adf7 100644--- a/services/document_cognition_service/src/server.rs+++ b/services/document_cognition_service/src/server.rs@@ -45,8 +45,9 @@ use macro_authorization::{MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,};use macro_service_urls::{- AuthServiceUrl, CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl,- EmailServiceUrl, LexicalServiceUrl, StaticFileServiceUrl, SyncServiceUrl,+ AppServiceUrl, AuthServiceUrl, CalendarServiceUrl, ConnectionGatewayUrl,+ DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl, StaticFileServiceUrl,+ SyncServiceUrl,};use notification::domain::service::{NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,@@ -698,6 +699,8 @@ pub async fn run() -> anyhow::Result<()> {db.clone(),CalendarServiceUrl::new()?,internal_api_key.clone(),+ call_tool_context.service.clone(),+ AppServiceUrl::new()?,);let forms_tool_context = ai_tools::build_forms_tool_context(db.clone(),diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 40b9ce2d06..9ea734e33d 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -36,8 +36,8 @@ use github_pull_requests::{};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_service_urls::{- AiEditingWorkerUrl, CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl,- EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,+ AiEditingWorkerUrl, AppServiceUrl, CalendarServiceUrl, ConnectionGatewayUrl,+ DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,};use mcp_auth_proxy::{domain::{@@ -434,6 +434,8 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Todb.clone(),CalendarServiceUrl::new()?,config.internal_api_key.to_string(),+ call_tool_context.service.clone(),+ AppServiceUrl::new()?,);let forms_tool_context = ai_tools::build_forms_tool_context(db.clone(),@@ -443,7 +445,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<ToSome(side_effect_clients.connection_gateway.as_ref().clone()),ai_tools::MaybeToolEventBroker::Real(macro_event_broker.clone()),ai_tools::FormsToolConfig {- app_origin: macro_service_urls::AppServiceUrl::new()?.to_string(),+ app_origin: AppServiceUrl::new()?.to_string(),editing_worker_url: ai_editing_worker_url,},);