Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(calendar): let the agent add a shared event to the user's calendar (#8706)

gbirman748cee683f1c
diff --git a/apps/docs/AI/mcp/tools/add-shared-calendar-event.mdx b/apps/docs/AI/mcp/tools/add-shared-calendar-event.mdx
new file mode 100644
index 0000000000..9002d31356
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/add-shared-calendar-event.mdx
@@ -0,0 +1,22 @@
+---
+title: AddSharedCalendarEvent
+description: >-
+ Add a copy of a calendar event someone shared with one of the user's channels
+ to one of the user's Google calendars, as `Add to calendar` on the event's
+ card does.
+---
+
+# AddSharedCalendarEvent
+
+Add a copy of a calendar event someone shared with one of the user's channels to one of the user's Google calendars, as `Add to calendar` on the event's card does. Use it for a calendar event mention (`blockName` `calendar`) whose meeting is not on the user's calendar; pass the mention's `documentId` as `eventId`.
+
+The copy is a snapshot, not an invitation: it keeps the real organizer and lists the user, accepted, as its only guest, while the meeting's other guests and its join link stay out. Nobody is notified, and the copy does not change when the organizer changes the meeting. The user can change only its reminders and availability, or delete it. To be added to the meeting itself, the user asks the person who shared it from the event's card.
+
+Only Google calendars take a copy. When the user has one writable Google calendar the copy goes there; when they have several, ask which one and pass its `calendarId` from ListCalendars. The result is the user's copy, whose `eventId` UpdateCalendarEvent and DeleteCalendarEvent accept.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `eventId` | string | Yes | The shared event's id: the `documentId` of its calendar event mention. |
+| `calendarId` | string | No | The `calendarId` of a writable Google calendar from ListCalendars. Omit when the user has only one; required when they have several. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 4e3794e6eb..6a015c921e 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -9,6 +9,7 @@ These pages are generated from Macro's Rust MCP tool registry.
## Tools
+- [AddSharedCalendarEvent](/AI/mcp/tools/add-shared-calendar-event)
- [AddToPipeline](/AI/mcp/tools/add-to-pipeline)
- [ApplyCanvasEdits](/AI/mcp/tools/apply-canvas-edits)
- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 273543f49a..df78af9a1c 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -1,5 +1,6 @@
[
"AI/mcp/tools/index",
+ "AI/mcp/tools/add-shared-calendar-event",
"AI/mcp/tools/add-to-pipeline",
"AI/mcp/tools/apply-canvas-edits",
"AI/mcp/tools/bash-code-execution",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index c0670c8865..6c4922f406 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -104,6 +104,7 @@
"icon": "wrench",
"pages": [
"AI/mcp/tools/index",
+ "AI/mcp/tools/add-shared-calendar-event",
"AI/mcp/tools/add-to-pipeline",
"AI/mcp/tools/apply-canvas-edits",
"AI/mcp/tools/bash-code-execution",
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index 679fc2d3d7..08e5eac312 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -13,6 +13,7 @@ type Wording = (whose: string) => string;
* `null` for the tools that use nobody's access and so are never held.
*/
const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
+ AddSharedCalendarEvent: (whose) => `add a shared event to ${whose} calendar`,
AddToPipeline: (whose) => `add deals to ${whose} pipelines`,
BashCodeExecution: (whose) => `run code with ${whose} access`,
BulkSetEntityPropertyOptions: (whose) =>
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.tsx
index e9805e55a5..e17863640a 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
@@ -275,6 +275,18 @@ export const updateCalendarEventHandler = createToolRenderer({
},
});
+export const addSharedCalendarEventHandler = createToolRenderer({
+ name: 'AddSharedCalendarEvent',
+ render: (ctx) => (
+ <CalendarMutationCard
+ event={ctx.response?.data}
+ icon={CalendarPlus}
+ label="Add to calendar"
+ renderContext={ctx.renderContext}
+ />
+ ),
+});
+
export const deleteCalendarEventHandler = createToolRenderer({
name: 'DeleteCalendarEvent',
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.tsx
index 96850feee4..2b7fb600e1 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
@@ -45,6 +45,7 @@ import {
manageBotChannelAccessHandler,
} from './Bots';
import {
+ addSharedCalendarEventHandler,
createCalendarEventHandler,
createConfirmedCalendarEventHandler,
deleteCalendarEventHandler,
@@ -246,6 +247,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
CreateConfirmedCalendarEvent: createConfirmedCalendarEventHandler,
UpdateCalendarEvent: updateCalendarEventHandler,
DeleteCalendarEvent: deleteCalendarEventHandler,
+ AddSharedCalendarEvent: addSharedCalendarEventHandler,
ListCalendarEvents: listCalendarEventsHandler,
ListCalendars: listCalendarsHandler,
GetTeamAvailability: getTeamAvailabilityHandler,
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 046cfa7645..d5aaede565 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -700,7 +700,8 @@ export const enableCalendarGuestInvites = defineFlag({
// action on a shared event's mention card. On in dev only until a real Google
// import has passed on dev; there is no PostHog flag yet, so it stays off in
// production. "Download .ics" beside it is not gated. Override with
-// VITE_ENABLE_CALENDAR_ADD_SHARED_EVENT.
+// VITE_ENABLE_CALENDAR_ADD_SHARED_EVENT. The agent's AddSharedCalendarEvent
+// tool reads the server switch ENABLE_CALENDAR_ADD_SHARED_EVENT instead.
export const enableCalendarAddSharedEvent = defineFlag({
key: 'enable-calendar-add-shared-event',
env: 'ENABLE_CALENDAR_ADD_SHARED_EVENT',
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 988fc55d48..1031b30dca 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
@@ -3,6 +3,64 @@
*/
import { z } from 'zod/v3';
+export const AddSharedCalendarEvent = z.object({
+ eventId: z.string().uuid(),
+ calendarId: z.union([z.string().uuid(), z.null()]).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(),
+ macroCallUrl: z.union([z.string(), z.null()]).optional(),
+ isReadOnly: z.boolean(),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ calendarName: z.union([z.string(), z.null()]).optional(),
+ inbox: z.union([z.string(), z.null()]).optional(),
+ myRole: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('organizer'), z.literal('guest')];
+ 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(),
+});
+
export const AddToPipeline = z.object({
pipelineId: z.string().uuid(),
entries: z.array(
@@ -2565,59 +2623,6 @@ export const CreateConfirmedCalendarEvent = z.object({
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(),
- macroCallUrl: z.union([z.string(), z.null()]).optional(),
- isReadOnly: z.boolean(),
- calendarId: z.union([z.string().uuid(), z.null()]).optional(),
- calendarName: z.union([z.string(), z.null()]).optional(),
- inbox: z.union([z.string(), z.null()]).optional(),
- myRole: z
- .union([
- z.any().superRefine((x, ctx) => {
- const schemas = [z.literal('organizer'), z.literal('guest')];
- 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(),
-});
-
export const CreateContact = z.object({
companyId: z.string().uuid(),
name: z.string(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 16621fb500..90dde95bf5 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
@@ -9,6 +9,10 @@ import * as schemas from './schemas';
import type * as types from './types';
type ToolParserMap = {
+ AddSharedCalendarEvent: {
+ call: types.AddSharedCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
AddToPipeline: {
call: types.AddToPipeline;
response: types.AddToPipelineResponse;
@@ -530,6 +534,10 @@ type ToolParserMap = {
};
const toolParserMap = {
+ AddSharedCalendarEvent: {
+ call: schemas.AddSharedCalendarEvent,
+ response: schemas.ToolCalendarEvent,
+ },
AddToPipeline: {
call: schemas.AddToPipeline,
response: schemas.AddToPipelineResponse,
@@ -1119,6 +1127,10 @@ type NamedRawTool = {
};
type ToolDataMap = {
+ AddSharedCalendarEvent: {
+ call: types.AddSharedCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
AddToPipeline: {
call: types.AddToPipeline;
response: types.AddToPipelineResponse;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 9971f0a383..5459840cb3 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
@@ -8,6 +8,10 @@
* and run json-schema-to-typescript to regenerate this file.
*/
+/**
+ * What the user is on one copy of an event, through the inbox holding it.
+ */
+export type ToolEventRole = 'organizer' | 'guest';
/**
* Content of a bash code execution response - either a result or an error
*/
@@ -426,10 +430,6 @@ export type UserToolResponseForToolCalendarEvent =
| {
UserAction: ToolCalendarEvent;
};
-/**
- * What the user is on one copy of an event, through the inbox holding it.
- */
-export type ToolEventRole = 'organizer' | 'guest';
/**
* Channel types an agent may create.
*/
@@ -4834,6 +4834,137 @@ export type ReadThreadReadContent =
type: 'itemPreviews';
};
+/**
+ * Add a copy of a calendar event someone shared with one of the user's channels to one of the user's Google calendars, as `Add to calendar` on the event's card does. Use it for a calendar event mention (`blockName` `calendar`) whose meeting is not on the user's calendar; pass the mention's `documentId` as `eventId`.
+ *
+ * The copy is a snapshot, not an invitation: it keeps the real organizer and lists the user, accepted, as its only guest, while the meeting's other guests and its join link stay out. Nobody is notified, and the copy does not change when the organizer changes the meeting. The user can change only its reminders and availability, or delete it. To be added to the meeting itself, the user asks the person who shared it from the event's card.
+ *
+ * Only Google calendars take a copy. When the user has one writable Google calendar the copy goes there; when they have several, ask which one and pass its `calendarId` from ListCalendars. The result is the user's copy, whose `eventId` UpdateCalendarEvent and DeleteCalendarEvent accept.
+ */
+export interface AddSharedCalendarEvent {
+ /**
+ * The shared event's id: the `documentId` of its calendar event mention.
+ */
+ eventId: string;
+ /**
+ * The `calendarId` of a writable Google calendar from ListCalendars. Omit when the user has only one; required when they have several.
+ */
+ calendarId?: string | null;
+}
+/**
+ * A calendar event as returned by the create and update tools.
+ */
+export interface ToolCalendarEvent {
+ /**
+ * Macro calendar event id, used by UpdateCalendarEvent and
+ * DeleteCalendarEvent.
+ */
+ eventId: string;
+ /**
+ * Display title.
+ */
+ title: string;
+ /**
+ * Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events.
+ */
+ start: string;
+ /**
+ * Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ * events.
+ */
+ end: string;
+ /**
+ * Whether the event covers whole days.
+ */
+ isAllDay: boolean;
+ /**
+ * IANA time zone the event was scheduled in, when known.
+ */
+ timeZone?: string | null;
+ /**
+ * Location label, when set.
+ */
+ location?: string | null;
+ /**
+ * Event body, truncated for brevity.
+ */
+ description?: string | null;
+ /**
+ * Event status: confirmed, tentative, or cancelled.
+ */
+ status: string;
+ /**
+ * Whether the event recurs.
+ */
+ isRecurring: boolean;
+ /**
+ * Raw RFC 5545 recurrence properties, when the event recurs.
+ */
+ recurrenceLines: string[];
+ /**
+ * Attendees, capped at 20; `attendee_count` has the full number.
+ */
+ attendees: ToolEventAttendee[];
+ /**
+ * Total number of attendees.
+ */
+ attendeeCount: number;
+ /**
+ * Organizer email address, when known.
+ */
+ organizerEmail?: string | null;
+ /**
+ * 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.
+ */
+ isReadOnly: boolean;
+ /**
+ * Calendar the event belongs to, when known.
+ */
+ calendarId?: string | null;
+ /**
+ * Display name of that calendar, when known.
+ */
+ calendarName?: string | null;
+ /**
+ * Connected inbox address the calendar belongs to, when known.
+ */
+ inbox?: string | null;
+ /**
+ * Whether the user organizes this event or is a guest on it, through
+ * that inbox; absent when they are neither.
+ */
+ myRole?: ToolEventRole | null;
+}
+/**
+ * An attendee of a calendar event, as returned by calendar tools.
+ */
+export interface ToolEventAttendee {
+ /**
+ * Attendee email address.
+ */
+ email: string;
+ /**
+ * RSVP state: needs_action, accepted, declined, or tentative.
+ */
+ responseStatus: string;
+ /**
+ * Whether this attendee organized the event.
+ */
+ isOrganizer: boolean;
+ /**
+ * Whether attendance is optional.
+ */
+ isOptional: boolean;
+}
/**
* Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.
*/
@@ -7109,120 +7240,6 @@ export interface GuestPolicy {
*/
canSeeOtherGuests: boolean;
}
-/**
- * A calendar event as returned by the create and update tools.
- */
-export interface ToolCalendarEvent {
- /**
- * Macro calendar event id, used by UpdateCalendarEvent and
- * DeleteCalendarEvent.
- */
- eventId: string;
- /**
- * Display title.
- */
- title: string;
- /**
- * Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events.
- */
- start: string;
- /**
- * Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
- * events.
- */
- end: string;
- /**
- * Whether the event covers whole days.
- */
- isAllDay: boolean;
- /**
- * IANA time zone the event was scheduled in, when known.
- */
- timeZone?: string | null;
- /**
- * Location label, when set.
- */
- location?: string | null;
- /**
- * Event body, truncated for brevity.
- */
- description?: string | null;
- /**
- * Event status: confirmed, tentative, or cancelled.
- */
- status: string;
- /**
- * Whether the event recurs.
- */
- isRecurring: boolean;
- /**
- * Raw RFC 5545 recurrence properties, when the event recurs.
- */
- recurrenceLines: string[];
- /**
- * Attendees, capped at 20; `attendee_count` has the full number.
- */
- attendees: ToolEventAttendee[];
- /**
- * Total number of attendees.
- */
- attendeeCount: number;
- /**
- * Organizer email address, when known.
- */
- organizerEmail?: string | null;
- /**
- * 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.
- */
- isReadOnly: boolean;
- /**
- * Calendar the event belongs to, when known.
- */
- calendarId?: string | null;
- /**
- * Display name of that calendar, when known.
- */
- calendarName?: string | null;
- /**
- * Connected inbox address the calendar belongs to, when known.
- */
- inbox?: string | null;
- /**
- * Whether the user organizes this event or is a guest on it, through
- * that inbox; absent when they are neither.
- */
- myRole?: ToolEventRole | null;
-}
-/**
- * An attendee of a calendar event, as returned by calendar tools.
- */
-export interface ToolEventAttendee {
- /**
- * Attendee email address.
- */
- email: string;
- /**
- * RSVP state: needs_action, accepted, declined, or tentative.
- */
- responseStatus: string;
- /**
- * Whether this attendee organized the event.
- */
- isOrganizer: boolean;
- /**
- * Whether attendance is optional.
- */
- isOptional: boolean;
-}
/**
* Create a private or team channel and add its first members. Use `private` for an invite-only channel and `team` for a channel owned by the current user's team. Do not use this for a direct message — those are created separately. Team id is resolved from the current user; do not invent one. Participants accept `macro|<email>` ids from ListTeamMembers or bare emails. Creating a team channel when the user has no team fails; create a private channel instead. Creating a team channel with no participants adds the current user so the channel is valid. Use only when the user asks to create a channel.
*/
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 367fc4070b..d98c9de041 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -455,6 +455,9 @@ pub async fn build_tool_service_context_from_env(
env.internal_api_key.to_string(),
call_tool_context.service.clone(),
AppServiceUrl::new()?,
+ macro_env_var::maybe_read_env("ENABLE_CALENDAR_ADD_SHARED_EVENT")
+ .and_then(|value| value.parse::<bool>().ok())
+ .unwrap_or(false),
);
let notification_reader_service = NotificationReaderService {
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index a51fb71ec3..186d74cbad 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -496,12 +496,14 @@ pub fn build_team_calendar_tool_context(
/// `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.
+/// `shared_event_copies` lets the agent add copies of channel-shared events.
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,
+ shared_event_copies: bool,
) -> ToolCalendarToolContext {
CalendarToolContext::new(
Arc::new(
@@ -520,6 +522,7 @@ pub fn build_calendar_tool_context(
),
),
)
+ .with_shared_event_copies(shared_event_copies)
}
/// Settings-only scheduling service; no provider/calendar writes are exposed here.
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 93ccaf9e18..59c2c37ce8 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -115,7 +115,11 @@ reminder dispatch, team availability, and provider/Postgres persistence.
meeting on another calendar of the same inbox. Google
only: never import over a UID the calendar already holds, since an import
updates that event in place and would strip an unsynced invitation's
- guests.
+ guests. The agent adds a copy with `AddSharedCalendarEvent`
+ (`src/inbound/toolset/add_shared_calendar_event.rs`) only while the
+ `ENABLE_CALENDAR_ADD_SHARED_EVENT` deployment switch is on (off unless set,
+ like the card's `enable-calendar-add-shared-event`); without a `calendarId`
+ it takes the card's only target calendar or asks which one.
- Asking to join a channel-shared event (`src/domain/join_requests.rs`) is a
Macro-stored request, not an `entity_access` row: the grant is a provider guest
write. Eligibility is the invite path's own `copy_capabilities` on the
diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rs
index 9e16c9160c..63d5a60235 100644
--- a/crates/calendar_events/src/inbound/toolset.rs
+++ b/crates/calendar_events/src/inbound/toolset.rs
@@ -5,6 +5,7 @@
//! map domain errors to agent-readable failures. Authorization and business
//! policy live behind those ports, exactly as for the HTTP routers.
+mod add_shared_calendar_event;
mod create_calendar_event;
mod create_confirmed_calendar_event;
mod delete_calendar_event;
@@ -37,6 +38,7 @@ use crate::domain::{
},
};
+pub use add_shared_calendar_event::AddSharedCalendarEvent;
pub use create_calendar_event::CreateCalendarEvent;
pub use create_confirmed_calendar_event::CreateConfirmedCalendarEvent;
pub use delete_calendar_event::{
@@ -63,6 +65,10 @@ where
pub occurrences: Arc<O>,
/// Macro meetings minted for events that carry a Macro call.
pub meeting_links: Arc<L>,
+ /// Whether AddSharedCalendarEvent adds copies of channel-shared events:
+ /// the `ENABLE_CALENDAR_ADD_SHARED_EVENT` deployment switch, off unless
+ /// set, like the event card's Add to calendar.
+ pub shared_event_copies: bool,
}
impl<M, O, L> Clone for CalendarToolContext<M, O, L>
@@ -76,6 +82,7 @@ where
mutations: Arc::clone(&self.mutations),
occurrences: Arc::clone(&self.occurrences),
meeting_links: Arc::clone(&self.meeting_links),
+ shared_event_copies: self.shared_event_copies,
}
}
}
@@ -93,6 +100,15 @@ where
mutations,
occurrences,
meeting_links,
+ shared_event_copies: false,
+ }
+ }
+
+ /// Let AddSharedCalendarEvent add copies of channel-shared events.
+ pub fn with_shared_event_copies(self, enabled: bool) -> Self {
+ Self {
+ shared_event_copies: enabled,
+ ..self
}
}
}
@@ -108,14 +124,15 @@ where
.add_tool::<ListCalendars, CalendarToolContext<M, O, L>>()
.add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O, L>>()
.add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O, L>>()
+ .add_tool::<AddSharedCalendarEvent, CalendarToolContext<M, O, L>>()
}
/// 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.
+/// decides which fits the surface the prompt came from. Reads, updates,
+/// deletions, and copies of shared events execute in the agent loop.
pub fn calendar_toolset<M, O, L>() -> AsyncToolCollection<CalendarToolContext<M, O, L>>
where
M: CalendarMutationService,
@@ -426,6 +443,11 @@ impl CalendarLabels {
else {
return Self::default();
};
+ Self::from_calendars(calendars)
+ }
+
+ /// Labels from calendars the tool already listed.
+ fn from_calendars(calendars: Vec<VisibleCalendar>) -> Self {
let inbox_by_link = calendars
.iter()
.map(|calendar| (calendar.email_link_id, calendar.email_address.clone()))
diff --git a/crates/calendar_events/src/inbound/toolset/add_shared_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/add_shared_calendar_event.rs
new file mode 100644
index 0000000000..74077e25d7
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/add_shared_calendar_event.rs
@@ -0,0 +1,167 @@
+//! AddSharedCalendarEvent tool for adding a copy of an event shared with one
+//! of the user's channels to their own Google calendar, as the event card's
+//! Add to calendar does.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+use uuid::Uuid;
+
+use super::{CalendarLabels, CalendarToolContext, ToolCalendarEvent, mutation_tool_error};
+use crate::domain::{
+ models::{CalendarProvider, VisibleCalendar},
+ ports::{CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider},
+};
+
+const ACTION: &str = "add the shared event to the calendar";
+
+/// Add a copy of a channel-shared event to one of the user's calendars.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "AddSharedCalendarEvent",
+ description = "\
+Add a copy of a calendar event someone shared with one of the user's channels to one of the \
+user's Google calendars, as `Add to calendar` on the event's card does. Use it for a calendar \
+event mention (`blockName` `calendar`) whose meeting is not on the user's calendar; pass the \
+mention's `documentId` as `eventId`.\n\
+\n\
+The copy is a snapshot, not an invitation: it keeps the real organizer and lists the user, \
+accepted, as its only guest, while the meeting's other guests and its join link stay out. \
+Nobody is notified, and the copy does not change when the organizer changes the meeting. The \
+user can change only its reminders and availability, or delete it. To be added to the meeting \
+itself, the user asks the person who shared it from the event's card.\n\
+\n\
+Only Google calendars take a copy. When the user has one writable Google calendar the copy goes \
+there; when they have several, ask which one and pass its `calendarId` from ListCalendars. The \
+result is the user's copy, whose `eventId` UpdateCalendarEvent and DeleteCalendarEvent accept."
+)]
+pub struct AddSharedCalendarEvent {
+ /// Shared event to copy.
+ #[schemars(
+ description = "The shared event's id: the `documentId` of its calendar event mention."
+ )]
+ pub event_id: Uuid,
+
+ /// Google calendar to add the copy to.
+ #[schemars(
+ description = "The `calendarId` of a writable Google calendar from ListCalendars. Omit \
+ when the user has only one; required when they have several."
+ )]
+ #[serde(default)]
+ pub calendar_id: Option<Uuid>,
+}
+
+impl ToolAnnotated for AddSharedCalendarEvent {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::additive("Add shared event to calendar").with_open_world();
+}
+
+/// The calendars the event card offers: only a writable Google calendar that
+/// a person maintains imports a copy under the meeting's own UID.
+fn takes_copies(calendar: &VisibleCalendar) -> bool {
+ calendar.is_writable
+ && calendar.provider == CalendarProvider::Google
+ && !calendar.is_subscription
+}
+
+fn refused(description: String) -> ToolCallError {
+ ToolCallError {
+ internal_error: anyhow::anyhow!(description.clone()),
+ description,
+ }
+}
+
+/// A named calendar, held to the card's choices.
+fn named_target(calendars: &[VisibleCalendar], calendar_id: Uuid) -> Result<Uuid, ToolCallError> {
+ if calendars
+ .iter()
+ .any(|calendar| calendar.id == calendar_id && takes_copies(calendar))
+ {
+ return Ok(calendar_id);
+ }
+ Err(refused(
+ "That calendar can't take a copy: shared events can be added only to a writable Google \
+ calendar the user keeps, not a subscribed one. Pick another from ListCalendars, or \
+ suggest downloading the event's .ics file from its card."
+ .to_string(),
+ ))
+}
+
+/// The calendar a copy goes to when none was named: the only one that takes
+/// copies, or a refusal that lists the choices to ask the user about.
+fn only_target(calendars: &[VisibleCalendar]) -> Result<Uuid, ToolCallError> {
+ let targets: Vec<&VisibleCalendar> = calendars
+ .iter()
+ .filter(|calendar| takes_copies(calendar))
+ .collect();
+ match targets.as_slice() {
+ [] => Err(refused(
+ "None of the user's calendars can take a copy: shared events can be added only to a \
+ writable Google calendar. Suggest downloading the event's .ics file from its card."
+ .to_string(),
+ )),
+ [target] => Ok(target.id),
+ // Ids only: a refusal is traced, and Google names a primary calendar
+ // after its owner's address. ListCalendars has the names to ask with.
+ targets => {
+ let choices = targets
+ .iter()
+ .map(|calendar| calendar.id.to_string())
+ .collect::<Vec<_>>()
+ .join(", ");
+ Err(refused(format!(
+ "The user has several Google calendars that can take a copy. Ask which one, \
+ naming them from ListCalendars, and call again with its calendarId, one of: \
+ {choices}."
+ )))
+ }
+ }
+}
+
+#[async_trait]
+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for AddSharedCalendarEvent
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+ L: MeetingLinkProvider,
+{
+ type Output = ToolCalendarEvent;
+
+ #[tracing::instrument(skip_all, fields(event_id=%self.event_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if !service_context.shared_event_copies {
+ return Err(refused(
+ "Adding a shared event to the user's calendar is not enabled for this deployment."
+ .to_string(),
+ ));
+ }
+ let requester_id = request_context.user_id.to_string();
+ let calendars = service_context
+ .mutations
+ .list_visible_calendars(&requester_id)
+ .await
+ .map_err(|error| mutation_tool_error(ACTION, error))?;
+ let calendar_id = match self.calendar_id {
+ Some(calendar_id) => named_target(&calendars, calendar_id)?,
+ None => only_target(&calendars)?,
+ };
+ let copy = service_context
+ .mutations
+ .copy_shared_event(&requester_id, self.event_id, Some(calendar_id))
+ .await
+ .map_err(|error| mutation_tool_error(ACTION, error))?;
+ Ok(ToolCalendarEvent::from_event(
+ &copy,
+ &CalendarLabels::from_calendars(calendars),
+ ))
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
index 24b267dd98..9d3d5b78e1 100644
--- a/crates/calendar_events/src/inbound/toolset/test.rs
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -1,3 +1,5 @@
+mod add_shared_calendar_event;
+
use std::sync::Mutex;
use ai_toolset::schema::generate_validated_input_schema;
@@ -47,6 +49,10 @@ fn tool_input_schemas_satisfy_strict_mode() {
"DeleteCalendarEvent",
generate_validated_input_schema::<DeleteCalendarEvent>().map(|schema| schema.name),
),
+ (
+ "AddSharedCalendarEvent",
+ generate_validated_input_schema::<AddSharedCalendarEvent>().map(|schema| schema.name),
+ ),
] {
match result {
Ok(schema_name) => assert_eq!(schema_name, name, "schema title for {name}"),
@@ -156,6 +162,8 @@ struct MockMutations {
deleted: Mutex<Vec<(Uuid, CalendarDeletionScope)>>,
answered: Mutex<Vec<(Uuid, AttendeeResponseStatus, CalendarRsvpScope)>>,
calendars: Mutex<Vec<VisibleCalendar>>,
+ copied: Mutex<Vec<(Uuid, Option<Uuid>)>>,
+ copy_error: Mutex<Option<CalendarMutationError>>,
}
impl CalendarMutationService for MockMutations {
@@ -236,10 +244,14 @@ impl CalendarMutationService for MockMutations {
async fn copy_shared_event(
&self,
_requester_id: &str,
- _event_id: Uuid,
- _calendar_id: Option<Uuid>,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
) -> Result<CalendarEvent, CalendarMutationError> {
- unreachable!("no calendar tool copies shared events")
+ if let Some(error) = self.copy_error.lock().unwrap().take() {
+ return Err(error);
+ }
+ self.copied.lock().unwrap().push((event_id, calendar_id));
+ Ok(sample_event(Vec::new()))
}
async fn respond_to_join_request(
diff --git a/crates/calendar_events/src/inbound/toolset/test/add_shared_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/test/add_shared_calendar_event.rs
new file mode 100644
index 0000000000..0a5b3e5ff9
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/test/add_shared_calendar_event.rs
@@ -0,0 +1,152 @@
+use super::*;
+use crate::domain::models::{CalendarCapabilities, CalendarProvider};
+
+const SHARED_EVENT: Uuid = Uuid::from_u128(77);
+
+async fn add(
+ calendars: Vec<VisibleCalendar>,
+ copy_error: Option<CalendarMutationError>,
+ shared_event_copies: bool,
+ args: serde_json::Value,
+) -> (
+ ai_toolset::ToolResult<serde_json::Value>,
+ Vec<(Uuid, Option<Uuid>)>,
+) {
+ let (mutations, context) = context(
+ MockMutations {
+ calendars: Mutex::new(calendars),
+ copy_error: Mutex::new(copy_error),
+ ..Default::default()
+ },
+ empty_occurrences(),
+ );
+ let result = calendar_toolset()
+ .try_tool_call(
+ context.0.with_shared_event_copies(shared_event_copies),
+ request_context(),
+ "AddSharedCalendarEvent",
+ &args,
+ )
+ .await
+ .unwrap();
+ let copied = mutations.copied.lock().unwrap().clone();
+ (result, copied)
+}
+
+fn args(calendar_id: Option<Uuid>) -> serde_json::Value {
+ serde_json::json!({ "eventId": SHARED_EVENT, "calendarId": calendar_id })
+}
+
+/// Calendars the card does not offer: Outlook, a read-only Google calendar
+/// and a subscribed one.
+fn calendars_without_copies() -> Vec<VisibleCalendar> {
+ let mut outlook = visible_calendar(20, 21, "[email protected]", "Outlook");
+ outlook.provider = CalendarProvider::Outlook;
+ outlook.capabilities = CalendarCapabilities::outlook(true);
+ let mut read_only = visible_calendar(22, 4, "[email protected]", "Team");
+ read_only.is_writable = false;
+ let mut holidays = visible_calendar(23, 4, "[email protected]", "Holidays");
+ holidays.is_subscription = true;
+ vec![outlook, read_only, holidays]
+}
+
+#[tokio::test]
+async fn adds_the_copy_to_the_only_calendar_the_card_offers() {
+ let mut calendars = calendars_without_copies();
+ calendars.push(visible_calendar(9, 4, "[email protected]", "Work"));
+
+ let (result, copied) = add(calendars, None, true, args(None)).await;
+
+ let copy = result.unwrap();
+ assert_eq!(copied, vec![(SHARED_EVENT, Some(Uuid::from_u128(9)))]);
+ assert_eq!(copy["eventId"], Uuid::from_u128(7).to_string());
+ assert_eq!(copy["calendarName"], "Work");
+ assert_eq!(copy["inbox"], "[email protected]");
+}
+
+#[tokio::test]
+async fn asks_which_calendar_when_several_take_copies() {
+ let calendars = vec![
+ visible_calendar(9, 4, "[email protected]", "Work"),
+ visible_calendar(10, 5, "[email protected]", "Personal"),
+ ];
+
+ let (result, copied) = add(calendars, None, true, args(None)).await;
+
+ let error = result.unwrap_err();
+ assert!(copied.is_empty());
+ assert!(error.description.contains("Ask which one"));
+ assert!(error.description.contains(&Uuid::from_u128(9).to_string()));
+ assert!(error.description.contains(&Uuid::from_u128(10).to_string()));
+ assert!(!error.description.contains("@"));
+}
+
+#[tokio::test]
+async fn adds_the_copy_to_the_named_calendar() {
+ let calendars = vec![
+ visible_calendar(9, 4, "[email protected]", "Work"),
+ visible_calendar(10, 5, "[email protected]", "Personal"),
+ ];
+
+ let (result, copied) = add(calendars, None, true, args(Some(Uuid::from_u128(10)))).await;
+
+ result.unwrap();
+ assert_eq!(copied, vec![(SHARED_EVENT, Some(Uuid::from_u128(10)))]);
+}
+
+#[tokio::test]
+async fn refuses_a_named_calendar_the_card_does_not_offer() {
+ let mut calendars = calendars_without_copies();
+ calendars.push(visible_calendar(9, 4, "[email protected]", "Work"));
+
+ // Outlook, read-only and subscribed.
+ for named in [20, 22, 23].map(Uuid::from_u128) {
+ let (result, copied) = add(calendars.clone(), None, true, args(Some(named))).await;
+
+ assert!(copied.is_empty());
+ assert!(
+ result
+ .unwrap_err()
+ .description
+ .contains("can't take a copy")
+ );
+ }
+}
+
+#[tokio::test]
+async fn points_to_the_ics_file_when_no_calendar_takes_copies() {
+ let (result, copied) = add(calendars_without_copies(), None, true, args(None)).await;
+
+ assert!(copied.is_empty());
+ assert!(result.unwrap_err().description.contains(".ics"));
+}
+
+#[tokio::test]
+async fn says_why_the_server_refused_the_copy() {
+ let calendars = vec![visible_calendar(9, 4, "[email protected]", "Work")];
+
+ let (result, _) = add(
+ calendars,
+ Some(CalendarMutationError::JoinRequestOpen),
+ true,
+ args(None),
+ )
+ .await;
+
+ assert!(
+ result
+ .unwrap_err()
+ .description
+ .contains("asked the person who shared this event")
+ );
+}
+
+#[tokio::test]
+async fn adds_nothing_while_the_deployment_switch_is_off() {
+ let calendars = vec![visible_calendar(9, 4, "[email protected]", "Work")];
+
+ let (result, copied) = add(calendars, None, false, args(None)).await;
+
+ assert!(copied.is_empty());
+ assert!(result.unwrap_err().description.contains("not enabled"));
+}
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index 01077719d5..3b5979b245 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -680,7 +680,10 @@ when they have several; Outlook calendars are not offered, since Microsoft canno
meeting's iCalendar UID. Google imports an event only for its organizer or an attendee, so the
snapshot keeps the real organizer and lists the viewer, already accepted, as its only guest: the
meeting's other guests and join link stay out and nobody is notified. If Google refuses anyway,
-the card says Google won't add the event to that calendar and points to `Download .ics`. The
+the card says Google won't add the event to that calendar and points to `Download .ics`. The agent
+adds the same snapshot with `AddSharedCalendarEvent` while the server switch
+`ENABLE_CALENDAR_ADD_SHARED_EVENT` is on (off unless set): it uses the one calendar the card would
+offer, asks which one when there are several, and meets the same refusals. The
mention then opens the snapshot, whose details say `Your copy of a shared event. It doesn't
update when the organizer changes it.` and offer no RSVP, `Add guests` or `Only the organizer can
invite guests.` line, since none of it would reach the meeting. It offers no `Edit event` on
diff --git a/services/agent_harness_service/src/cognition/api/context/test.rs b/services/agent_harness_service/src/cognition/api/context/test.rs
index 42d33f1721..d276d4ea02 100644
--- a/services/agent_harness_service/src/cognition/api/context/test.rs
+++ b/services/agent_harness_service/src/cognition/api/context/test.rs
@@ -483,6 +483,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"test-internal-api-key".to_string(),
call_tool_context.service.clone(),
macro_service_urls::AppServiceUrl::local(),
+ true,
);
let forms_tool_context = ai_tools::build_forms_tool_context(
pool.clone(),
@@ -532,6 +533,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"test-internal-api-key".to_string(),
call_tool_context.service.clone(),
macro_service_urls::AppServiceUrl::local(),
+ true,
),
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/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rs
index 290152d0ca..33baa59a23 100644
--- a/services/agent_harness_service/src/cognition/server.rs
+++ b/services/agent_harness_service/src/cognition/server.rs
@@ -769,6 +769,9 @@ pub async fn build(
internal_api_key.clone(),
call_tool_context.service.clone(),
AppServiceUrl::new()?,
+ macro_env_var::maybe_read_env("ENABLE_CALENDAR_ADD_SHARED_EVENT")
+ .and_then(|value| value.parse::<bool>().ok())
+ .unwrap_or(false),
);
let forms_tool_context = ai_tools::build_forms_tool_context(
db.clone(),