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): create events from a thread on the user's approving reply (#7359)
Wolf Mermelstein2501cb092466
diff --git a/apps/docs/AI/mcp/tools/create-calendar-event.mdx b/apps/docs/AI/mcp/tools/create-calendar-event.mdxindex b8814b0854..2f3b72685e 100644--- a/apps/docs/AI/mcp/tools/create-calendar-event.mdx+++ b/apps/docs/AI/mcp/tools/create-calendar-event.mdx@@ -7,7 +7,7 @@ description: >-# CreateCalendarEvent-Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call.+Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the event out in your reply, ask whether to create it, and use CreateConfirmedCalendarEvent once the user approves.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.diff --git a/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdx b/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdxnew file mode 100644index 0000000000..9940a85a82--- /dev/null+++ b/apps/docs/AI/mcp/tools/create-confirmed-calendar-event.mdx@@ -0,0 +1,26 @@+---+title: CreateConfirmedCalendarEvent+description: >-+ Create a calendar event immediately, with no review card or composer.+---++# 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.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `title` | string | Yes | The event title. |+| `time` | EventTimeInput | Yes | The mutually exclusive time shape supplied to calendar tools. |+| `description` | string | No | Optional event body/description. |+| `location` | string | No | Optional physical or virtual location label. |+| `attendees` | AttendeeInput[] | No | Attendees to invite by email. They are notified by Google Calendar as soon as the event is created. Omit for a solo event. |+| `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. |+| `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/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 21d647a3b2..fbf5a88db5 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -19,6 +19,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [CreateBot](/AI/mcp/tools/create-bot)- [CreateCalendarEvent](/AI/mcp/tools/create-calendar-event)- [CreateChannel](/AI/mcp/tools/create-channel)+- [CreateConfirmedCalendarEvent](/AI/mcp/tools/create-confirmed-calendar-event)- [CreateDocument](/AI/mcp/tools/create-document)- [CreateImportEntity](/AI/mcp/tools/create-import-entity)- [CreateInitiative](/AI/mcp/tools/create-initiative)diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex 53b83f3cb9..5d1815618c 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -10,6 +10,7 @@"AI/mcp/tools/create-bot","AI/mcp/tools/create-calendar-event","AI/mcp/tools/create-channel",+ "AI/mcp/tools/create-confirmed-calendar-event","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-initiative",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex f2ce29a66a..c00f3db666 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -81,6 +81,7 @@"AI/mcp/tools/create-bot","AI/mcp/tools/create-calendar-event","AI/mcp/tools/create-channel",+ "AI/mcp/tools/create-confirmed-calendar-event","AI/mcp/tools/create-document","AI/mcp/tools/create-import-entity","AI/mcp/tools/create-initiative",diff --git a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.test.tsxnew file mode 100644index 0000000000..5f47f5ba96--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.test.tsx@@ -0,0 +1,123 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import type { Component, JSX, ParentProps } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { afterEach, expect, it, vi } from 'vitest';+import {+ createCalendarEventHandler,+ createConfirmedCalendarEventHandler,+} from './CalendarTools';++const openToolCalendarEvent = vi.hoisted(() => vi.fn());+vi.mock('./calendar/open-tool-event', () => ({+ openToolCalendarEvent,+ toolInputOpenTime: vi.fn(),+}));+vi.mock('./calendar/ChatCompose', () => ({+ CalendarChatCompose: () => <div>calendar composer</div>,+}));+vi.mock('@ui', () => ({+ Layer: (props: ParentProps) => props.children,+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button+ type="button"+ onClick={props.onClick}+ aria-expanded={props['aria-expanded']}+ >+ {props.children}+ </button>+ ),+}));+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++const handlers = {+ CreateCalendarEvent: createCalendarEventHandler,+ CreateConfirmedCalendarEvent: createConfirmedCalendarEventHandler,+};++const draft = {+ title: 'Board sync',+ time: {+ kind: 'timed',+ startsAt: '2026-10-05T14:00:00Z',+ endsAt: '2026-10-05T15:00:00Z',+ timeZone: 'America/New_York',+ },+ attendees: [{ email: '[email protected]' }],+};++const createdEvent = {+ eventId: '01992d2f-8444-7000-8000-000000000001',+ title: 'Board sync',+ start: '2026-10-05T14:00:00Z',+ end: '2026-10-05T15:00:00Z',+ isAllDay: false,+ timeZone: 'America/New_York',+ location: null,+ description: null,+ status: 'confirmed',+ isRecurring: false,+ recurrenceLines: [],+ attendees: [+ {+ email: '[email protected]',+ responseStatus: 'needs_action',+ isOrganizer: false,+ isOptional: false,+ },+ ],+ attendeeCount: 1,+ organizerEmail: '[email protected]',+ conferenceUrl: null,+ isReadOnly: false,+ calendarId: null,+};++function tool(name: keyof typeof handlers, data: unknown, response?: unknown) {+ return render(() => (+ <Dynamic+ component={handlers[name].render as Component<Record<string, unknown>>}+ tool={{ id: 'call-1', name, data }}+ response={response === undefined ? undefined : { name, data: response }}+ renderContext={{ isStreaming: response === undefined, grouped: false }}+ chat_id="chat-1"+ message_id="message-1"+ />+ ));+}++it('shows a confirmed create in flight as the plain create card', () => {+ tool('CreateConfirmedCalendarEvent', {+ ...draft,+ userConfirmation: 'yes, go ahead',+ });+ expect(screen.getByText('Create calendar event')).toBeTruthy();+ expect(screen.getByText('Board sync')).toBeTruthy();+ expect(screen.queryByText('calendar composer')).toBeNull();+});++it('renders the created event directly, with no composer or pending state', () => {+ tool(+ 'CreateConfirmedCalendarEvent',+ { ...draft, userConfirmation: 'yes, go ahead' },+ createdEvent+ );+ expect(screen.getByText('Done')).toBeTruthy();+ expect(screen.queryByText('calendar composer')).toBeNull();++ fireEvent.click(screen.getByRole('button', { expanded: false }));+ expect(screen.getByText('1 attendee: [email protected]')).toBeTruthy();++ fireEvent.click(screen.getByText('Board sync', { selector: 'span.text-xs' }));+ expect(openToolCalendarEvent).toHaveBeenCalledWith(+ createdEvent,+ expect.objectContaining({})+ );+});++it('still defers the plain create to the composer', () => {+ tool('CreateCalendarEvent', draft, 'PendingUserExecution');+ expect(screen.getByText('calendar composer')).toBeTruthy();+});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 bdc16cf42e..6e5f0c9579 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@@ -225,6 +225,25 @@ export const createCalendarEventHandler = createToolRenderer({},});+/**+ * `CreateConfirmedCalendarEvent` creates on a confirmation the user already+ * gave in a conversation thread, so there is no pending composer and no+ * review to render: the response is the created event itself, shown the way+ * `CreateCalendarEvent` shows its finished create.+ */+export const createConfirmedCalendarEventHandler = createToolRenderer({+ name: 'CreateConfirmedCalendarEvent',+ render: (ctx) => (+ <CalendarMutationCard+ event={ctx.response?.data}+ icon={CalendarPlus}+ label="Create calendar event"+ renderContext={ctx.renderContext}+ title={ctx.tool.data.title}+ />+ ),+});+export const updateCalendarEventHandler = createToolRenderer({name: 'UpdateCalendarEvent',render: (ctx) => {diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 5c2aa3cd22..e7e8ed718e 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -24,6 +24,7 @@ import {} from './Bots';import {createCalendarEventHandler,+ createConfirmedCalendarEventHandler,deleteCalendarEventHandler,listCalendarEventsHandler,listCalendarsHandler,@@ -160,6 +161,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ListBots: listBotsHandler,ManageBotChannelAccess: manageBotChannelAccessHandler,CreateCalendarEvent: createCalendarEventHandler,+ CreateConfirmedCalendarEvent: createConfirmedCalendarEventHandler,UpdateCalendarEvent: updateCalendarEventHandler,DeleteCalendarEvent: deleteCalendarEventHandler,ListCalendarEvents: listCalendarEventsHandler,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 058cde259b..cd171fd617 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@@ -1836,6 +1836,146 @@ export const CreateChannelResponse = z.object({summary: z.string(),});+export const CreateConfirmedCalendarEvent = z.object({+ title: z.string(),+ time: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({+ startsAt: z.string().datetime({ offset: true }),+ endsAt: z.string().datetime({ offset: true }),+ timeZone: z.union([z.string(), z.null()]).optional(),+ kind: z.literal('timed'),+ }),+ z.object({+ startDate: z.string().date(),+ endDate: z.string().date(),+ kind: z.literal('allDay'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ description: z.union([z.string(), z.null()]).optional(),+ location: z.union([z.string(), z.null()]).optional(),+ attendees: z+ .array(z.object({ email: z.string(), isOptional: z.boolean().optional() }))+ .optional(),+ recurrenceLines: z.array(z.string()).optional(),+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ reminders: z+ .union([+ z.object({+ useDefault: z.boolean(),+ overrides: z+ .array(+ z.object({ method: z.string(), minutes: z.number().int().gte(0) })+ )+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ addGoogleMeet: z.boolean().optional(),+ eventType: z+ .any()+ .superRefine((x, ctx) => {+ const schemas = [z.literal('default'), z.literal('out_of_office')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ })+ .optional(),+ outOfOffice: z+ .union([+ z.object({+ autoDeclineMode: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('decline_none'),+ z.literal('decline_all'),+ z.literal('decline_new_only'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ declineMessage: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),+ userConfirmation: z.string(),+});++export const ToolCalendarEvent = z.object({+ eventId: z.string().uuid(),+ title: z.string(),+ start: z.string(),+ end: z.string(),+ isAllDay: z.boolean(),+ timeZone: z.union([z.string(), z.null()]).optional(),+ location: z.union([z.string(), z.null()]).optional(),+ description: z.union([z.string(), z.null()]).optional(),+ status: z.string(),+ isRecurring: z.boolean(),+ recurrenceLines: z.array(z.string()),+ attendees: z.array(+ z.object({+ email: z.string(),+ responseStatus: z.string(),+ isOrganizer: z.boolean(),+ isOptional: z.boolean(),+ })+ ),+ attendeeCount: z.number().int().gte(0),+ organizerEmail: z.union([z.string(), z.null()]).optional(),+ conferenceUrl: z.union([z.string(), z.null()]).optional(),+ isReadOnly: z.boolean(),+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),+});+export const CreateDocument = z.object({documentName: z.string(),fileContent: z.string(),@@ -9193,33 +9333,6 @@ export const UpdateCalendarEvent = z.object({.optional(),});-export const ToolCalendarEvent = z.object({- eventId: z.string().uuid(),- title: z.string(),- start: z.string(),- end: z.string(),- isAllDay: z.boolean(),- timeZone: z.union([z.string(), z.null()]).optional(),- location: z.union([z.string(), z.null()]).optional(),- description: z.union([z.string(), z.null()]).optional(),- status: z.string(),- isRecurring: z.boolean(),- recurrenceLines: z.array(z.string()),- attendees: z.array(- z.object({- email: z.string(),- responseStatus: z.string(),- isOrganizer: z.boolean(),- isOptional: z.boolean(),- })- ),- attendeeCount: z.number().int().gte(0),- organizerEmail: z.union([z.string(), z.null()]).optional(),- conferenceUrl: z.union([z.string(), z.null()]).optional(),- isReadOnly: z.boolean(),- calendarId: z.union([z.string().uuid(), z.null()]).optional(),-});-export const UpdateInitiative = z.object({initiativeId: z.string().uuid(),name: z.union([z.string(), z.null()]).optional(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex 00cabf17ac..1f3f2a312a 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -45,6 +45,10 @@ type ToolParserMap = {call: types.CreateChannel;response: types.CreateChannelResponse;};+ CreateConfirmedCalendarEvent: {+ call: types.CreateConfirmedCalendarEvent;+ response: types.ToolCalendarEvent;+ };CreateDocument: {call: types.CreateDocument;response: types.CreateDocumentResponse;@@ -372,6 +376,10 @@ const toolParserMap = {call: schemas.CreateChannel,response: schemas.CreateChannelResponse,},+ CreateConfirmedCalendarEvent: {+ call: schemas.CreateConfirmedCalendarEvent,+ response: schemas.ToolCalendarEvent,+ },CreateDocument: {call: schemas.CreateDocument,response: schemas.CreateDocumentResponse,@@ -746,6 +754,10 @@ type ToolDataMap = {call: types.CreateChannel;response: types.CreateChannelResponse;};+ CreateConfirmedCalendarEvent: {+ call: types.CreateConfirmedCalendarEvent;+ response: types.ToolCalendarEvent;+ };CreateDocument: {call: types.CreateDocument;response: types.CreateDocumentResponse;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 b248b42789..3bb220ec44 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@@ -5236,7 +5236,7 @@ export interface BotWebhook {webhookUrl: string;}/**- * Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call.+ * Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the event out in your reply, ask whether to create it, and use CreateConfirmedCalendarEvent once the user approves.** 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.*@@ -5467,6 +5467,53 @@ 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.+ */+export interface CreateConfirmedCalendarEvent {+ /**+ * The event title.+ */+ title: string;+ time: EventTimeInput;+ /**+ * Optional event body/description.+ */+ description?: string | null;+ /**+ * Optional physical or virtual location label.+ */+ location?: string | null;+ /**+ * Attendees to invite by email. They are notified by Google Calendar as soon as the event is created. Omit for a solo event.+ */+ attendees?: AttendeeInput[];+ /**+ * Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE"]. Omit for a one-off event.+ */+ recurrenceLines?: string[];+ /**+ * Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar.+ */+ calendarId?: string | null;+ /**+ * Reminder configuration for the event. Omit to use the selected calendar's defaults.+ */+ reminders?: EventRemindersInput | null;+ /**+ * Attach a freshly generated Google Meet video conference to the event.+ */+ addGoogleMeet?: boolean;+ eventType?: CalendarEventTypeInput;+ /**+ * 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`.+ */+ outOfOffice?: OutOfOfficeInput | null;+ /**+ * 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.+ */+ userConfirmation: string;+}/*** Create a plaintext document or a native Macro spreadsheet. For a workbook use fileExtension spreadsheet, empty fileContent, and isTask false; then ReadSpreadsheet and EditSpreadsheet to populate cells, formulas and sheets. Works without an open editor.*/diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex 5ae8498ea8..ce51e4ac08 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -147,6 +147,15 @@ fn the_agent_session_host_keeps_chats_user_tools_with_the_review_prompt() {.contains_key("CreateCalendarEvent"));assert!(session.toolset.user_tools.contains_key("SendEmail"));+ // The confirmed twins execute in the loop, beside the deferring tools,+ // for the prompts a session reads out of a thread.+ assert!(session.toolset.tools.contains_key("SendConfirmedEmail"));+ assert!(+ session+ .toolset+ .tools+ .contains_key("CreateConfirmedCalendarEvent")+ );let prompt = session.prompt.to_string();assert!(prompt.contains("review card"));assert!(!prompt.contains("PendingUserExecution"));@@ -188,6 +197,14 @@ fn composerless_hosts_execute_calendar_create_directly_and_omit_send_email() {!tools.iter().any(|tool| tool["name"] == "SendEmail"),"{host:?} toolset must not expose SendEmail");+ // The confirmed twins are for the in-process agent's thread turns;+ // these hosts already create directly and keep their own policy.+ for name in ["SendConfirmedEmail", "CreateConfirmedCalendarEvent"] {+ assert!(+ !tools.iter().any(|tool| tool["name"] == name),+ "{host:?} toolset must not expose {name}"+ );+ }}}diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rsindex 6203a7ca2a..065a883617 100644--- a/crates/calendar_events/src/inbound/toolset.rs+++ b/crates/calendar_events/src/inbound/toolset.rs@@ -6,6 +6,7 @@//! policy live behind those ports, exactly as for the HTTP routers.mod create_calendar_event;+mod create_confirmed_calendar_event;mod delete_calendar_event;mod list_calendar_events;mod list_calendars;@@ -31,6 +32,7 @@ use crate::domain::{};pub use create_calendar_event::CreateCalendarEvent;+pub use create_confirmed_calendar_event::CreateConfirmedCalendarEvent;pub use delete_calendar_event::{DeleteCalendarEvent, DeleteCalendarEventResponse, DeletionScopeInput,};@@ -93,16 +95,20 @@ where.add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O>>()}-/// Create the AI chat calendar toolset.-///-/// Event creation is deferred until the user reviews and executes the pending-/// call. Reads, updates, and deletions continue to execute in the agent loop.+/// The full calendar toolset, for hosts that finish user tools: the deferring+/// `CreateCalendarEvent`, which a composer or review card confirms, beside+/// `CreateConfirmedCalendarEvent`, which creates on a confirmation the user+/// 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>>whereM: CalendarMutationService,O: CalendarOccurrenceService,{- shared_calendar_toolset().add_user_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()+ shared_calendar_toolset()+ .add_user_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()+ .add_tool::<CreateConfirmedCalendarEvent, CalendarToolContext<M, O>>()}/// Create the calendar toolset for hosts without a composer — the MCP server@@ -110,7 +116,9 @@ where////// These hosts receive the real create tool and apply their own confirmation/// policy from its annotations rather than the chat-specific deferred flow,-/// which only the chat frontend can finish.+/// 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>>whereM: CalendarMutationService,diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rsindex d9f7839a39..1743871970 100644--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs@@ -29,7 +29,10 @@ Calendar. In Macro chat this tool opens an inline composer so the user can revieconfirm the event; use the tool to present the proposal instead of asking for a redundant \confirmation in prose. When the pending call is executed, the event is written to Google \immediately and attendees receive invitations. Other clients should confirm attendee events \-before executing the call.\n\+before executing the call. Do NOT use it for a prompt that came from a channel or document \+thread — the context block names a conversation parent when it did, and there is no surface \+to review a draft in: write the event out in your reply, ask whether to create it, and use \+CreateConfirmedCalendarEvent once the user approves.\n\\n\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. \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.rsnew file mode 100644index 0000000000..b0cb312b11--- /dev/null+++ b/crates/calendar_events/src/inbound/toolset/create_confirmed_calendar_event.rs@@ -0,0 +1,92 @@+//! `CreateConfirmedCalendarEvent`: [`CreateCalendarEvent`] without the+//! review, for a host that has nothing to review in.+//!+//! `CreateCalendarEvent` defers: it returns `PendingUserExecution` and a host+//! finishes it - the chat composer after the turn, or a review-card+//! elicitation in an agent-session turn. A prompt read out of a channel or+//! document thread has neither surface, so the agent asks in prose there, the+//! user answers in the thread, and this tool creates on that answer. Every+//! host gets both tools; the prompt, not the toolset, says which to reach for.+//!+//! The event is always floated first. Being told to schedule something is a+//! request to draft the event, not permission to create it, so the agent+//! writes the event into the thread and stops; only the user's reply to that+//! draft authorizes the create. An instruction detailed enough to create from+//! is still only a draft request - the point is that nothing lands on a+//! calendar, or in a guest's inbox, before the user has seen it.+//!+//! The gate is `userConfirmation`: the model must quote that approving reply+//! to call this. That is a cheap first pass, deliberately - it makes the+//! model produce evidence rather than create silently, and the requirement is+//! self-documenting in the schema - but nothing here checks the quote against+//! the thread, so it is not a guarantee. The same trade-off as+//! `SendConfirmedEmail`, and the same place a session-scoped proposal state+//! would tighten it.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::Deserialize;++use super::create_calendar_event::CreateCalendarEvent;+use super::{CalendarToolContext, ToolCalendarEvent};+use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};++/// Create a calendar event the user has already approved in conversation.+///+/// The fields are [`CreateCalendarEvent`]'s, flattened, plus the+/// confirmation; the creation is [`CreateCalendarEvent`]'s too. The two tools+/// differ in whether a host reviews the call, not in what a create is.+#[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."+)]+#[serde(rename_all = "camelCase")]+pub struct CreateConfirmedCalendarEvent {+ /// The event, exactly as `CreateCalendarEvent` takes it.+ #[serde(flatten)]+ pub event: CreateCalendarEvent,+ /// The user's own words approving this create.+ #[schemars(+ description = "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."+ )]+ pub user_confirmation: String,+}++impl ToolAnnotated for CreateConfirmedCalendarEvent {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::additive("Create confirmed calendar event").with_open_world();+}++#[async_trait]+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for CreateConfirmedCalendarEvent+where+ M: CalendarMutationService,+ O: CalendarOccurrenceService,+{+ 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>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ // The schema makes the field required, so a call gets here with one;+ // a blank one is the model going through the motions, and is refused+ // the same way a missing one would be.+ if self.user_confirmation.trim().is_empty() {+ return Err(ToolCallError {+ description: "CreateConfirmedCalendarEvent requires the user's own message approving this event in userConfirmation. Describe the event in prose, ask whether to create it, and call this tool only after they say yes.".to_owned(),+ internal_error: anyhow::anyhow!(+ "CreateConfirmedCalendarEvent called without a confirmation"+ ),+ });+ }+ self.event.call(service_context, request_context).await+ }+}diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rsindex d362d8bbba..42000f1068 100644--- a/crates/calendar_events/src/inbound/toolset/test.rs+++ b/crates/calendar_events/src/inbound/toolset/test.rs@@ -33,6 +33,11 @@ fn tool_input_schemas_satisfy_strict_mode() {"CreateCalendarEvent",generate_validated_input_schema::<CreateCalendarEvent>().map(|schema| schema.name),),+ (+ "CreateConfirmedCalendarEvent",+ generate_validated_input_schema::<CreateConfirmedCalendarEvent>()+ .map(|schema| schema.name),+ ),("UpdateCalendarEvent",generate_validated_input_schema::<UpdateCalendarEvent>().map(|schema| schema.name),@@ -347,6 +352,116 @@ async fn mcp_toolset_executes_create_directly() {assert_eq!(mutations.created.lock().unwrap().len(), 1);}+/// The confirmed variant takes exactly `CreateCalendarEvent`'s fields plus+/// the confirmation, and the confirmation is required: the schema is the gate.+#[test]+fn create_confirmed_is_create_plus_a_required_confirmation() {+ let confirmed = generate_validated_input_schema::<CreateConfirmedCalendarEvent>().unwrap();+ let plain = generate_validated_input_schema::<CreateCalendarEvent>().unwrap();+ assert_eq!(confirmed.name, "CreateConfirmedCalendarEvent");+ assert!(+ confirmed.description.contains("userConfirmation"),+ "{}",+ confirmed.description+ );++ let confirmed = confirmed.schema.to_value();+ let plain = plain.schema.to_value();+ let properties = |schema: &serde_json::Value| {+ let mut names: Vec<String> = schema["properties"]+ .as_object()+ .expect("an object schema")+ .keys()+ .cloned()+ .collect();+ names.sort();+ names+ };+ let mut expected = properties(&plain);+ expected.push("userConfirmation".to_owned());+ expected.sort();+ assert_eq!(properties(&confirmed), expected);+ assert!(+ confirmed["required"]+ .as_array()+ .expect("required is an array")+ .contains(&serde_json::json!("userConfirmation")),+ "{confirmed:#}"+ );+}++/// The confirmed tool is registered beside the deferring one, executes in+/// the loop rather than deferring, and creates exactly what the plain tool+/// would have.+#[tokio::test]+async fn confirmed_create_executes_directly_in_the_user_tool_toolset() {+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());+ let mut args = create_tool_args();+ args["userConfirmation"] = serde_json::json!("yes, go ahead and put it on the calendar");+ let event = calendar_toolset()+ .try_tool_call(+ context.0,+ request_context(),+ "CreateConfirmedCalendarEvent",+ &args,+ )+ .await+ .unwrap()+ .unwrap();++ assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());+ let created = mutations.created.lock().unwrap();+ let (_, _, draft) = created.first().expect("one create call");+ assert_eq!(draft.title, "Design review");+}++/// Composer-less hosts already create directly through the plain tool, so+/// the confirmed variant would be a second name for the same thing there.+#[tokio::test]+async fn mcp_toolset_omits_the_confirmed_create() {+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());+ let mut args = create_tool_args();+ args["userConfirmation"] = serde_json::json!("yes");+ let result = mcp_toolset()+ .try_tool_call(+ context.0,+ request_context(),+ "CreateConfirmedCalendarEvent",+ &args,+ )+ .await;++ assert!(+ matches!(result, Err(ai_toolset::ToolSetError::NotFound(_))),+ "{result:?}"+ );+ assert!(mutations.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn confirmed_create_refuses_a_blank_confirmation() {+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());+ let mut args = create_tool_args();+ args["userConfirmation"] = serde_json::json!(" ");+ let error = calendar_toolset()+ .try_tool_call(+ context.0,+ request_context(),+ "CreateConfirmedCalendarEvent",+ &args,+ )+ .await+ .unwrap()+ .unwrap_err();++ assert!(+ error.description.contains("userConfirmation"),+ "{}",+ error.description+ );+ assert!(mutations.created.lock().unwrap().is_empty());+}+#[tokio::test]async fn create_converts_input_into_a_domain_draft() {let (mutations, context) = context(MockMutations::default(), empty_occurrences());diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex ea4041ea57..9d9f697ccf 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -216,13 +216,17 @@ mod tests {assert!(session.contains("quoted verbatim"));assert!(session.contains("`userConfirmation`"));assert!(session.contains("`AskUser`"));- assert!(session.contains("`SendConfirmedEmail` is never right here"));+ assert!(session.contains(+ "`SendConfirmedEmail` and `CreateConfirmedCalendarEvent` are never right here"+ ));// The thread rule is to restate what the tool would have done, whole,// so the user can approve it without opening the session - and it- // covers every user tool, not just email.+ // covers every user tool, not just email: an approved event goes+ // through the calendar twin of the confirmed send.assert!(session.contains("written out verbatim"));assert!(session.contains("the whole calendar event"));+ assert!(session.contains("`CreateConfirmedCalendarEvent` for the event"));// Which prompt is being answered decides it, not the session.assert!(session.contains("decided per"));@@ -243,18 +247,17 @@ mod tests {}#[test]- fn chat_prompt_names_the_confirmed_send_only_to_rule_it_out() {+ fn chat_prompt_names_the_confirmed_tools_only_to_rule_them_out() {// The chat host has the same toolset and a composer, so the direct- // tool is visible there and must be steered away from; the direct- // prompt's hosts do not register it and say nothing about it.+ // tools are visible there and must be steered away from; the direct+ // prompt's hosts do not register them and say nothing about them.let chat = TOOL_USE_PROMPT.to_string();assert!(chat.contains("`SendConfirmedEmail`"));- assert!(chat.contains("never use it here"));- assert!(- !DIRECT_TOOL_USE_PROMPT- .to_string()- .contains("SendConfirmedEmail")- );+ assert!(chat.contains("`CreateConfirmedCalendarEvent`"));+ assert!(chat.contains("never use them here"));+ let direct = DIRECT_TOOL_USE_PROMPT.to_string();+ assert!(!direct.contains("SendConfirmedEmail"));+ assert!(!direct.contains("CreateConfirmedCalendarEvent"));}#[test]diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rsindex 219187c453..78e78f251c 100644--- a/crates/prompt/src/user_tools.rs+++ b/crates/prompt/src/user_tools.rs@@ -8,12 +8,13 @@//! (the channel-mention bot, MCP) get toolsets where those tools execute//! directly or are absent, and neither section applies.//!-//! Both hosts also carry `SendConfirmedEmail`, which sends with no review at-//! all. It exists for the one surface an agent session reads prompts from+//! Both hosts also carry `SendConfirmedEmail` and+//! `CreateConfirmedCalendarEvent`, which send or create with no review at+//! all. They exist for the one surface an agent session reads prompts from//! that has nothing to review in - a channel or document thread - and the-//! toolset is the same everywhere, so each section says when it is the right-//! tool: in the session prompt, when the context block names a thread as the-//! prompt's origin; in chat, never.+//! toolset is the same everywhere, so each section says when they are the+//! right tools: in the session prompt, when the context block names a thread+//! as the prompt's origin; in chat, never.use crate::types::StaticPrompt;@@ -30,15 +31,16 @@ static INSTRUCTIONS: &str = r##"- User tools are tools that must be executed bysending are the same tool: it always creates a draft for the user to confirm before anything issent, so use it even when the user only wants a draft.-- `SendConfirmedEmail` sends immediately, with no composer. It is for conversation threads that- have no composer, and this chat does, so never use it here: `SendEmail` and its composer are how- the user confirms an email in chat.+- `SendConfirmedEmail` and `CreateConfirmedCalendarEvent` send or create immediately, with no+ composer. They are for conversation threads that have no composer, and this chat does, so+ never use them here: `SendEmail` and `CreateCalendarEvent` and their composers are how the+ user confirms an email or an event in chat."##;static INTENT: &str = "The model treats user tools as composer-confirmed: a PendingUserExecution \result means the user still has to finish the call, and email drafting or sending always goes \-through the SendEmail tool rather than inline text in the chat - never through SendConfirmedEmail, \-which is for surfaces without a composer.";+through the SendEmail tool rather than inline text in the chat - never through SendConfirmedEmail \+or CreateConfirmedCalendarEvent, which are for surfaces without a composer.";/// The user-tools prompt section for composer-capable chat hosts.pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);@@ -54,9 +56,10 @@ static SESSION_INSTRUCTIONS: &str = r##"- Before reaching for `SendEmail` or `Crin your reply - the whole email with its recipients, subject and body; the whole calendar eventwith its title, time and guests; whatever it is, written out verbatim so the user can check itwithout opening anything - then ask whether to go ahead, and end your turn. When the user- replies approving it, call `SendConfirmedEmail` with that same email and their approving message- quoted verbatim in `userConfirmation`. Never call it without such a reply, and never paraphrase- or invent one.+ replies approving it, call the confirmed twin of the tool - `SendConfirmedEmail` for the email,+ `CreateConfirmedCalendarEvent` for the event - with that same draft and their approving message+ quoted verbatim in `userConfirmation`. Never call either without such a reply, and never+ paraphrase or invent one.- The rule above is for you, not the user. Never explain why you are writing the draft out: donot mention the agent session view, review cards, threads versus sessions, `AskUser`, tools,@@ -70,7 +73,8 @@ static SESSION_INSTRUCTIONS: &str = r##"- Before reaching for `SendEmail` or `Credits, confirms or declines, and the tool then returns what happened: the sent email or createdevent, or "Rejected". Nothing is pending afterwards and there is no chat composer; do not tellthe user to confirm anything, and do not ask for confirmation in prose before calling the tool -- the review card is the confirmation. `SendConfirmedEmail` is never right here.+ the review card is the confirmation.+ `SendConfirmedEmail` and `CreateConfirmedCalendarEvent` are never right here.- IMPORTANT: When the user asks you to draft, write, compose, or send an email (or reply to one)from the session view, you MUST use the `SendEmail` tool to produce it. NEVER write the email@@ -81,10 +85,10 @@ static SESSION_INSTRUCTIONS: &str = r##"- Before reaching for `SendEmail` or `Crstatic SESSION_INTENT: &str = "The model checks where the newest prompt came from before using a \user tool: from a channel or document thread it states the whole email or event verbatim in its \-reply, asks, and sends only on the user's approving reply through SendConfirmedEmail - without \-ever explaining the session, review card or thread mechanics to the user; from the \-session view it calls SendEmail or CreateCalendarEvent and lets the review card be the \-confirmation, never asking for confirmation in prose first.";+reply, asks, and sends or creates only on the user's approving reply through SendConfirmedEmail \+or CreateConfirmedCalendarEvent - without ever explaining the session, review card or thread \+mechanics to the user; from the session view it calls SendEmail or CreateCalendarEvent and lets \+the review card be the confirmation, never asking for confirmation in prose first.";/// The user-tools prompt section for an agent session, whose in-process/// agent finishes user tools in the turn through a review elicitation.diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 0570725e3d..61c4f326e7 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -297,6 +297,12 @@ bottom of the area carries the other decisions, refusal first: `Dismiss · Openfor a tool draft, `Decline · Submit · Open in session` (or `Open` for a URL) for a question.Only the session's owner can act; other viewers see the question read-only and the headernames who is being waited on. Once answered, the area shows the agent's passage again.+A prompt the agent read out of a channel or document thread opens no review card at all:+the reply writes the whole email or calendar event into the thread and asks whether to go+ahead, and a reply in that same thread approving it ("yes, send it" / "go ahead") is the+confirmation - the agent then sends or creates directly (`SendConfirmedEmail`,+`CreateConfirmedCalendarEvent`), with no session visit needed. Being asked to send or+schedule something only produces the draft; nothing goes out before that approving reply.Images made with `GenerateImage` are saved to static file service. The bot embedsthe returned URL as a Markdown image in its channel reply; generated images haveno document mention or filename card.