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): create events with their Macro call in one write (#8187)

gbirman2875de3ebcc8
diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
index 632d7c5217..ac844f3b1b 100644
--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx
@@ -85,7 +85,7 @@ function EventComposerContent(
<EventForm
controller={controller}
macroCallsEnabled={macroCallsEnabled()}
- isEdit={isEdit() || editor.eventCreated()}
+ isEdit={isEdit()}
saveError={editor.saveError()}
disabledFields={editor.disabledFields()}
showRecurringEditNotice={editor.showRecurringEditNotice()}
diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts b/apps/web/src/features/calendar/hooks/use-event-editor.test.ts
index c5e61fda44..c698e4be6c 100644
--- a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts
+++ b/apps/web/src/features/calendar/hooks/use-event-editor.test.ts
@@ -440,6 +440,9 @@ describe('scheduling a Macro call', () => {
try {
await editor.save(values);
expect(mocks.createEvent).toHaveBeenCalledOnce();
+ expect(mocks.createEvent.mock.calls[0]?.[0]).not.toHaveProperty(
+ 'macroCall'
+ );
expect(mocks.createMeeting).not.toHaveBeenCalled();
expect(mocks.updateMeeting).not.toHaveBeenCalled();
expect(saved).toHaveBeenCalledOnce();
@@ -449,11 +452,8 @@ describe('scheduling a Macro call', () => {
}
);
- it('rechecks the flag after the calendar save before attaching a call', async () => {
- mocks.createEvent.mockImplementation(async () => {
- mocks.quickCalls = false;
- return { id: 'event-1' };
- });
+ it('creates the event with its Macro call in a single write', async () => {
+ const saved = vi.fn();
const [editor, dispose] = createRoot(
(dispose) =>
[
@@ -461,41 +461,26 @@ describe('scheduling a Macro call', () => {
macroCallsEnabled: () =>
mocks.quickCalls && !mocks.quickCallsLoading,
event: () => undefined,
- onSaved: vi.fn(),
+ onSaved: saved,
}),
dispose,
] as const
);
try {
await editor.save(values);
+ expect(mocks.createEvent).toHaveBeenCalledOnce();
+ expect(mocks.createEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'Planning',
+ location: 'Meeting room',
+ description: '<p>Roadmap discussion</p>',
+ macroCall: true,
+ })
+ );
expect(mocks.createMeeting).not.toHaveBeenCalled();
expect(mocks.updateEvent).not.toHaveBeenCalled();
- } finally {
- dispose();
- }
- });
-
- it('does not attach an in-flight created call after the flag is disabled', async () => {
- mocks.createMeeting.mockImplementation(async () => {
- mocks.quickCalls = false;
- return { shareToken: '8m8mGwzHqxzYjeIN5-nJRquRbzyTEhGF' };
- });
- const [editor, dispose] = createRoot(
- (dispose) =>
- [
- useEventEditor({
- event: () => undefined,
- onSaved: vi.fn(),
- macroCallsEnabled: () =>
- mocks.quickCalls && !mocks.quickCallsLoading,
- }),
- dispose,
- ] as const
- );
- try {
- await editor.save(values);
- expect(mocks.createMeeting).toHaveBeenCalledOnce();
- expect(mocks.updateEvent).not.toHaveBeenCalled();
+ expect(editor.saveError()).toBeUndefined();
+ expect(saved).toHaveBeenCalledOnce();
} finally {
dispose();
}
@@ -739,50 +724,7 @@ describe('scheduling a Macro call', () => {
}
});
- it.each(['none', 'disabled'] as const)(
- 'saves edited event details after failed attachment when switching to %s',
- async (choice) => {
- mocks.updateEvent.mockRejectedValueOnce(new Error('Update unavailable'));
- const saved = vi.fn();
- const [editor, dispose] = createRoot(
- (dispose) =>
- [
- useEventEditor({
- macroCallsEnabled: () =>
- mocks.quickCalls && !mocks.quickCallsLoading,
- event: () => undefined,
- onSaved: saved,
- }),
- dispose,
- ] as const
- );
- try {
- await editor.save(values);
- expect(editor.saveError()).toBeDefined();
- if (choice === 'disabled') mocks.quickCalls = false;
- await editor.save({
- ...values,
- title: 'Updated planning',
- conferenceChoice: choice === 'none' ? 'none' : 'macro',
- });
- expect(mocks.createEvent).toHaveBeenCalledOnce();
- expect(mocks.createMeeting).toHaveBeenCalledOnce();
- expect(mocks.updateMeeting).not.toHaveBeenCalled();
- expect(mocks.updateEvent.mock.lastCall?.[0].patch.title).toBe(
- 'Updated planning'
- );
- expect(mocks.updateEvent.mock.lastCall?.[0].patch.description).toBe(
- values.description
- );
- expect(editor.saveError()).toBeUndefined();
- expect(saved).toHaveBeenCalledOnce();
- } finally {
- dispose();
- }
- }
- );
-
- it('keeps an all-day call untimed instead of inventing local-midnight times', async () => {
+ it('asks the server for an untimed call on an all-day event', async () => {
const [editor, dispose] = createRoot(
(dispose) =>
[
@@ -804,11 +746,17 @@ describe('scheduling a Macro call', () => {
endDate: '2026-09-24',
},
});
- expect(mocks.createMeeting).toHaveBeenCalledWith({
- title: 'Planning',
- scheduledStart: null,
- scheduledEnd: null,
- });
+ expect(mocks.createEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ macroCall: true,
+ time: {
+ kind: 'allDay',
+ startDate: '2026-09-22',
+ endDate: '2026-09-24',
+ },
+ })
+ );
+ expect(mocks.createMeeting).not.toHaveBeenCalled();
} finally {
dispose();
}
@@ -878,48 +826,6 @@ describe('scheduling a Macro call', () => {
}
});
- it('creates the calendar event before creating and attaching its call', async () => {
- const saved = vi.fn();
- const [editor, dispose] = createRoot(
- (dispose) =>
- [
- useEventEditor({
- macroCallsEnabled: () =>
- mocks.quickCalls && !mocks.quickCallsLoading,
- event: () => undefined,
- onSaved: saved,
- }),
- dispose,
- ] as const
- );
- try {
- await editor.save(values);
-
- expect(mocks.createEvent).toHaveBeenCalledWith(
- expect.objectContaining({
- title: 'Planning',
- location: 'Meeting room',
- description: '<p>Roadmap discussion</p>',
- })
- );
- expect(mocks.createEvent.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.createMeeting.mock.invocationCallOrder[0]
- );
- expect(mocks.updateEvent).toHaveBeenCalledWith(
- expect.objectContaining({
- eventId: 'event-1',
- patch: expect.objectContaining({
- location: 'Meeting room',
- description: expect.stringContaining('Join Macro call'),
- }),
- })
- );
- expect(saved).toHaveBeenCalledOnce();
- } finally {
- dispose();
- }
- });
-
it('does not create a call when event creation fails', async () => {
mocks.createEvent.mockRejectedValueOnce(new Error('Calendar unavailable'));
const [editor, dispose] = createRoot(
@@ -945,38 +851,10 @@ describe('scheduling a Macro call', () => {
}
});
- it('retries call creation on the saved event without duplicating the event', async () => {
- mocks.createMeeting.mockRejectedValueOnce(new Error('Call unavailable'));
- const saved = vi.fn();
- const [editor, dispose] = createRoot(
- (dispose) =>
- [
- useEventEditor({
- macroCallsEnabled: () =>
- mocks.quickCalls && !mocks.quickCallsLoading,
- event: () => undefined,
- onSaved: saved,
- }),
- dispose,
- ] as const
+ it('retries a failed create from scratch instead of patching a saved event', async () => {
+ mocks.createEvent.mockRejectedValueOnce(
+ new Error('the Macro call for the event could not be created')
);
- try {
- await editor.save(values);
- expect(mocks.createEvent).toHaveBeenCalledOnce();
- expect(editor.saveError()).toContain('Your event is saved');
- expect(saved).not.toHaveBeenCalled();
- await editor.save(values);
- expect(mocks.createEvent).toHaveBeenCalledOnce();
- expect(mocks.createMeeting).toHaveBeenCalledTimes(2);
- expect(editor.saveError()).toBeUndefined();
- expect(saved).toHaveBeenCalledOnce();
- } finally {
- dispose();
- }
- });
-
- it('retains the same call link when attaching it fails and the title changes before retry', async () => {
- mocks.updateEvent.mockRejectedValueOnce(new Error('Update unavailable'));
const saved = vi.fn();
const [editor, dispose] = createRoot(
(dispose) =>
@@ -992,20 +870,17 @@ describe('scheduling a Macro call', () => {
);
try {
await editor.save(values);
- const linkedDescription =
- mocks.updateEvent.mock.lastCall?.[0].patch.description;
- expect(linkedDescription).toContain('/meet/');
- expect(editor.saveError()).toContain('Save again to retry');
+ expect(mocks.failure).toHaveBeenCalledWith('Failed to create event', {
+ subtext: 'the Macro call for the event could not be created',
+ });
+ expect(editor.saveError()).toBeUndefined();
expect(saved).not.toHaveBeenCalled();
- await editor.save({ ...values, title: 'Updated planning' });
- expect(mocks.createEvent).toHaveBeenCalledOnce();
- expect(mocks.createMeeting).toHaveBeenCalledOnce();
- expect(mocks.updateMeeting).toHaveBeenCalledWith(
- expect.objectContaining({ title: 'Updated planning' })
- );
- expect(mocks.updateEvent.mock.lastCall?.[0].patch.description).toBe(
- linkedDescription
- );
+ await editor.save(values);
+ expect(mocks.createEvent).toHaveBeenCalledTimes(2);
+ expect(mocks.createEvent.mock.lastCall?.[0]).toMatchObject({
+ macroCall: true,
+ });
+ expect(mocks.updateEvent).not.toHaveBeenCalled();
expect(saved).toHaveBeenCalledOnce();
} finally {
dispose();
@@ -1036,11 +911,11 @@ describe('scheduling a Macro call', () => {
expect(editor.pending()).toBe(true);
await editor.save(values);
expect(mocks.createEvent).toHaveBeenCalledOnce();
- expect(mocks.createMeeting).not.toHaveBeenCalled();
finish({ id: 'event-1' });
await saving;
expect(editor.pending()).toBe(false);
- expect(mocks.createMeeting).toHaveBeenCalledOnce();
+ expect(mocks.createEvent).toHaveBeenCalledOnce();
+ expect(mocks.createMeeting).not.toHaveBeenCalled();
} finally {
dispose();
}
diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.ts b/apps/web/src/features/calendar/hooks/use-event-editor.ts
index 397f15221a..bd52416b3d 100644
--- a/apps/web/src/features/calendar/hooks/use-event-editor.ts
+++ b/apps/web/src/features/calendar/hooks/use-event-editor.ts
@@ -146,11 +146,7 @@ export function useEventEditor(props: UseEventEditorProps) {
const createMeeting = useCreateMeetingMutation();
const [pending, setPending] = createSignal(false);
const [saveError, setSaveError] = createSignal<string>();
- // If adding the link fails, retry the same saved event and meeting.
- const [createdEvent, setCreatedEvent] = createSignal<{
- id: string;
- calendarId?: string;
- }>();
+ // If attaching the link to an existing event fails, retry the same meeting.
const [createdMeeting, setCreatedMeeting] = createSignal<{
url: string;
shareToken: string;
@@ -246,7 +242,9 @@ export function useEventEditor(props: UseEventEditorProps) {
try {
if (!event) {
- const eventValues = {
+ // The server mints the call and writes its link into the event, so
+ // the one invitation attendees receive already carries it.
+ await create.mutateAsync({
title: values.title,
time: values.time,
calendarId: values.calendarId,
@@ -259,46 +257,10 @@ export function useEventEditor(props: UseEventEditorProps) {
: cleanContent.description,
attendees: values.guestEmails.map((email) => ({ email })),
...(conference ? { conference } : {}),
+ ...(needsCall() ? { macroCall: true } : {}),
...(values.reminders ? { reminders: values.reminders } : {}),
...(values.outOfOffice ? { outOfOffice: values.outOfOffice } : {}),
- };
- let created = createdEvent();
- if (created) {
- await update.mutateAsync({
- eventId: created.id,
- calendarId: created.calendarId,
- patch: {
- ...eventValues,
- location: cleanContent.location,
- description: cleanContent.description,
- },
- });
- } else {
- const result = await create.mutateAsync(eventValues);
- created = {
- id: result.id,
- calendarId: values.calendarId ?? result.calendarId ?? undefined,
- };
- setCreatedEvent(created);
- }
- calendarSaved = true;
-
- if (needsCall()) {
- const meetingUrl = await createScheduledMeeting(values);
- const linkedContent = attachCalendarMacroCall(
- cleanContent,
- meetingUrl
- );
- if (needsCall())
- await update.mutateAsync({
- eventId: created.id,
- calendarId: created.calendarId ?? values.calendarId,
- patch: {
- location: linkedContent.location,
- description: linkedContent.description,
- },
- });
- }
+ });
props.onSaved();
return;
}
@@ -415,7 +377,7 @@ export function useEventEditor(props: UseEventEditorProps) {
const disabledFields = createMemo<EventEditorDisabledFields | undefined>(
() => {
const event = props.event();
- if (!event) return createdEvent() ? EDIT_DISABLED_FIELDS : undefined;
+ if (!event) return undefined;
const editsOtherCopy = !editsPrimaryCopy(event);
return {
...EDIT_DISABLED_FIELDS,
@@ -434,7 +396,6 @@ export function useEventEditor(props: UseEventEditorProps) {
showRecurringEditNotice,
pending,
saveError,
- eventCreated: () => createdEvent() !== undefined,
save,
};
}
diff --git a/apps/web/src/lib/queries/calendar/graphql/mutations.ts b/apps/web/src/lib/queries/calendar/graphql/mutations.ts
index ad592eea00..cd454e48c1 100644
--- a/apps/web/src/lib/queries/calendar/graphql/mutations.ts
+++ b/apps/web/src/lib/queries/calendar/graphql/mutations.ts
@@ -615,6 +615,7 @@ export async function executeGraphqlCreate(
),
}
: {}),
+ ...(args.macroCall ? { macroCall: true } : {}),
...(args.outOfOffice
? {
outOfOffice: {
diff --git a/apps/web/src/lib/queries/calendar/graphql/tests/mutations.test.ts b/apps/web/src/lib/queries/calendar/graphql/tests/mutations.test.ts
index 8514f20004..bf6aa76b22 100644
--- a/apps/web/src/lib/queries/calendar/graphql/tests/mutations.test.ts
+++ b/apps/web/src/lib/queries/calendar/graphql/tests/mutations.test.ts
@@ -522,6 +522,26 @@ describe('executeGraphqlCreate', () => {
expect(event.id).toBe('server-1');
});
+ it('asks the server for a Macro call only when the create requests one', async () => {
+ const { calls, client } = fakeClient('committed', {
+ event: graphqlEvent({ id: 'server-1', title: 'Lunch' }),
+ });
+ const time = {
+ kind: 'allDay' as const,
+ startDate: '2026-10-07',
+ endDate: '2026-10-08',
+ };
+
+ await executeGraphqlCreate(
+ { title: 'Lunch', time, macroCall: true },
+ client
+ );
+ await executeGraphqlCreate({ title: 'Lunch', time }, client);
+
+ expect(calls[0]?.variables.input.macroCall).toBe(true);
+ expect(calls[1]?.variables.input).not.toHaveProperty('macroCall');
+ });
+
it('marks a recurring create uncertain', async () => {
const { calls, client } = fakeClient('committed', {
event: graphqlEvent({ id: 'server-1' }),
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMutationErrorCode.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMutationErrorCode.ts
index 8dc49f5b3e..ef3623a926 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMutationErrorCode.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMutationErrorCode.ts
@@ -23,4 +23,5 @@ export const CalendarMutationErrorCode = {
provider_rejected: 'provider_rejected',
retryable: 'retryable',
persist_failed: 'persist_failed',
+ macro_call_failed: 'macro_call_failed',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
index 75c8cf19e3..01309f76c4 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
@@ -36,6 +36,10 @@ to the requester's primary inbox. */
idempotencyKey?: CreateCalendarEventRequestIdempotencyKey;
/** Optional location label. */
location?: CreateCalendarEventRequestLocation;
+ /** Mint a Macro call and write its join link into the description and
+location before creating the event, so the invitation carries it.
+Cannot be combined with `conference`. */
+ macroCall?: boolean;
outOfOffice?: CreateCalendarEventRequestOutOfOffice;
/** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */
recurrenceLines?: string[];
diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.json
index 8af17d5d41..a57c0b0758 100644
--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json
+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json
@@ -153,7 +153,7 @@
}
},
"503": {
- "description": "Transient provider failure",
+ "description": "Transient provider failure, or the Macro call could not be created",
"content": {
"application/json": {
"schema": {
@@ -860,7 +860,8 @@
"reauth_required",
"provider_rejected",
"retryable",
- "persist_failed"
+ "persist_failed",
+ "macro_call_failed"
]
},
"CalendarRsvpScopeParam": {
@@ -929,6 +930,10 @@
"type": ["string", "null"],
"description": "Optional location label."
},
+ "macroCall": {
+ "type": "boolean",
+ "description": "Mint a Macro call and write its join link into the description and\nlocation before creating the event, so the invitation carries it.\nCannot be combined with `conference`."
+ },
"outOfOffice": {
"oneOf": [
{
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 865d206dfb..a302ec8903 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -148,6 +148,12 @@ export type CreateCalendarEventInput = {
idempotencyKey?: string | number | null | undefined;
/** Optional location label. */
location?: string | null | undefined;
+ /**
+ * Mint a Macro call and write its join link into the description and
+ * location before creating the event, so the invitation carries it.
+ * Cannot be combined with `conference`.
+ */
+ macroCall?: boolean;
/**
* Present to create an out-of-office status event (primary calendar
* only, timed, no attendees).
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index d092dfbee8..7581243bc4 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -20,8 +20,8 @@
{
"name": "calendar",
"description": "Find and manage calendar events.",
- "overview": "<!-- src/entities/calendar/namespace/classes/CalendarNamespace.md -->\n# Class: CalendarNamespace\n\nThe calendar surface: the caller's visible calendars, event creation, and\nhandles to individual events and calendars. Backed by calendar_service (the\nSDK reaches it on the gateway's `/calendar` route).\n\n## Constructors\n\n### Constructor\n\n> **new CalendarNamespace**(`client`): `CalendarNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`CalendarNamespace`\n\n## Methods\n\n### calendar()\n\n> **calendar**(`id`): [`Calendar`](../../calendar/classes/Calendar.md)\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Calendar`](../../calendar/classes/Calendar.md)\n\n***\n\n### calendars()\n\n> **calendars**(): `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Returns\n\n`Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\n***\n\n### createEvent()\n\n> **createEvent**(`options`): `Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\nCreate a calendar event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`CreateEventOptions`](../interfaces/CreateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\n***\n\n### event()\n\n> **event**(`id`): [`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\nA handle to a calendar event by id, for driving mutations.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\n\n<!-- src/entities/calendar/namespace/interfaces/CreateEventOptions.md -->\n# Interface: CreateEventOptions\n\nFields for a new calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Invited attendees. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Exact calendar to create the event on; takes precedence over the inbox default. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | Conference to attach; omit to create the event without one. |\n| <a id=\"property-description\"></a> `description?` | `string` | Optional event body. |\n| <a id=\"property-emaillink\"></a> `emailLink?` | [`Link`](../../../email/link/classes/Link.md) | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |\n| <a id=\"property-location\"></a> `location?` | `string` | Optional location label. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Out-of-office properties; present to create a Google out-of-office event. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Reminder configuration; omit to keep the calendar defaults. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Event visibility. |\n",
- "documentation": "# Macro SDK: calendar\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/calendar/types.gen/type-aliases/AttendeeResponseStatus.md -->\n# Type Alias: AttendeeResponseStatus\n\n> **AttendeeResponseStatus** = `\"needs_action\"` \\| `\"accepted\"` \\| `\"declined\"` \\| `\"tentative\"`\n\nRSVP state for an attendee.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarAttendee.md -->\n# Type Alias: CalendarAttendee\n\n> **CalendarAttendee** = \\{ `comment?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `email`: `string`; `isOptional`: `boolean`; `isOrganizer`: `boolean`; `isSelf`: `boolean`; `responseStatus`: [`AttendeeResponseStatus`](AttendeeResponseStatus.md); \\}\n\nAn attendee on a calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Optional attendee comment. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Provider display name. |\n| <a id=\"property-email\"></a> `email` | `string` | Normalized email address. |\n| <a id=\"property-isoptional\"></a> `isOptional` | `boolean` | Whether attendance is optional. |\n| <a id=\"property-isorganizer\"></a> `isOrganizer` | `boolean` | Whether this attendee is the organizer. |\n| <a id=\"property-isself\"></a> `isSelf` | `boolean` | Whether this attendee is one of the viewing requester's inboxes. |\n| <a id=\"property-responsestatus\"></a> `responseStatus` | [`AttendeeResponseStatus`](AttendeeResponseStatus.md) | RSVP state. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md -->\n# Type Alias: CalendarAttendeeInputBody\n\n> **CalendarAttendeeInputBody** = \\{ `email`: `string`; `isOptional?`: `boolean`; \\}\n\nAn attendee supplied to a calendar mutation.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Attendee email address. |\n| <a id=\"property-isoptional\"></a> `isOptional?` | `boolean` | Whether attendance is optional. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarDeletionScopeParam.md -->\n# Type Alias: CalendarDeletionScopeParam\n\n> **CalendarDeletionScopeParam** = `\"all\"` \\| `\"this_event\"` \\| `\"this_and_following\"`\n\nHow much of a recurring series a deletion removes.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarEvent.md -->\n# Type Alias: CalendarEvent\n\n> **CalendarEvent** = \\{ `attendees`: [`CalendarAttendee`](CalendarAttendee.md)[]; `calendarId?`: `string` \\| `null`; `conferenceProvider?`: `null` \\| [`ConferenceProvider`](ConferenceProvider.md); `conferenceUrl?`: `string` \\| `null`; `createdAt`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: [`EventType`](EventType.md); `icalUid`: `string`; `id`: `string`; `isReadOnly`: `boolean`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `ownerId`: `string`; `recurrenceLines`: `string`[]; `reminders?`: [`EventReminders`](EventReminders.md); `sequence`: `number`; `sources?`: [`CalendarEventSourceContent`](CalendarEventSourceContent.md)[]; `status`: [`EventStatus`](EventStatus.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `transparency`: [`EventTransparency`](EventTransparency.md); `updatedAt`: `string`; `visibility`: [`EventVisibility`](EventVisibility.md); \\}\n\nA stable, first-class Macro calendar event entity.\n\nContent fields hold the canonical source's values: the account's primary\ncalendar copy when one is synced, else the freshest remaining copy.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | [`CalendarAttendee`](CalendarAttendee.md)[] | Attendees, keyed by email during persistence. |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` | Calendar the canonical source belongs to, when known. Absent only in projections stored before calendars were attributed. |\n| <a id=\"property-conferenceprovider\"></a> `conferenceProvider?` | `null` \\| [`ConferenceProvider`](ConferenceProvider.md) | - |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Direct join URL when known. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Entity creation time. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. Distinct from the organizer when someone writes onto a calendar they do not own. Omitted from stored projections when unknown so events ingested before this field still compare equal. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType?` | [`EventType`](EventType.md) | Provider event type. Skipped when it is the regular type so projections stored before event types were modeled still compare equal. |\n| <a id=\"property-icaluid\"></a> `icalUid` | `string` | RFC 5545 UID used to reconcile provider and email sources. |\n| <a id=\"property-id\"></a> `id` | `string` | Macro entity identifier. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the canonical source's calendar prohibits editing it. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer email. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer display name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who owns this event entity. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](EventReminders.md) | Per-user reminder configuration. Skipped when it is the provider default so projections stored before reminders were modeled still compare equal. |\n| <a id=\"property-sequence\"></a> `sequence` | `number` | Provider/iCalendar sequence number. |\n| <a id=\"property-sources\"></a> `sources?` | [`CalendarEventSourceContent`](CalendarEventSourceContent.md)[] | Content of every active copy of this event, canonical first: the primary calendar's copy, then the freshest. A client picks the copy whose calendar it is showing and falls back to the first. Populated only on the read path, so stored projections omit it. |\n| <a id=\"property-status\"></a> `status` | [`EventStatus`](EventStatus.md) | Event status. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | [`EventTransparency`](EventTransparency.md) | Availability behavior. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Entity update time. |\n| <a id=\"property-visibility\"></a> `visibility` | [`EventVisibility`](EventVisibility.md) | Event visibility. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarEventSourceContent.md -->\n# Type Alias: CalendarEventSourceContent\n\n> **CalendarEventSourceContent** = \\{ `calendarId`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType`: [`EventType`](EventType.md); `isReadOnly`: `boolean`; `location?`: `string` \\| `null`; `reminders`: [`EventReminders`](EventReminders.md); `title`: `string`; `transparency`: [`EventTransparency`](EventTransparency.md); `visibility`: [`EventVisibility`](EventVisibility.md); \\}\n\nThe content one provider copy of an event carries.\n\nGoogle keeps these fields per calendar copy: a shared calendar's copy of a\nmember's event can have its own title, type, reminders, and access role.\nThe entity holds its canonical source's values. Every other copy's values\nare read from here so a client can show the copy that belongs to the\ncalendar being viewed.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendarid\"></a> `calendarId` | `string` | Calendar this copy lives on. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType` | [`EventType`](EventType.md) | Provider event type. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the calendar's access role prohibits editing this copy. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-reminders\"></a> `reminders` | [`EventReminders`](EventReminders.md) | Reminder configuration of this copy. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | [`EventTransparency`](EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility` | [`EventVisibility`](EventVisibility.md) | Event visibility. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarRsvpScopeParam.md -->\n# Type Alias: CalendarRsvpScopeParam\n\n> **CalendarRsvpScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an RSVP applies to.\n\nUnlike deletion there is no this-and-following variant: the provider\ncannot express a forward-scoped response, so offering one would be a\npromise sync could not keep.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md -->\n# Type Alias: CalendarUpdateScopeParam\n\n> **CalendarUpdateScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an update applies to.\n\nLike RSVPs there is no this-and-following variant: the provider cannot\nexpress a forward-scoped edit as one write, and emulating it (truncate\nthe series, insert an edited clone) is non-atomic and re-invites the\nattendees of the clone. Compose it from a this-and-following deletion\nand a create when that shape is wanted.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ConferenceChange.md -->\n# Type Alias: ConferenceChange\n\n> **ConferenceChange** = `\"google_meet\"` \\| `\"none\"`\n\nA requested change to an event's conferencing. Omitting the field leaves\nthe existing conference untouched; only these values change it.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ConferenceProvider.md -->\n# Type Alias: ConferenceProvider\n\n> **ConferenceProvider** = `\"google_meet\"` \\| `\"other\"`\n\nThe conferencing system backing an event's join URL.\n\nMacro generates only Google Meet conferences, so this distinguishes one it\ncreated from a third party's — Zoom and friends arriving as `addOn`\nconference data, or a legacy classic Hangout. Clients use it to label the\nconference and to tell whether the Meet toggle reflects a Macro-managed\nconference.\n\nIt does not gate mutation. An explicit request replaces or detaches any\nconference, third-party included, exactly as deleting the event would;\nwhat protects a conference is that omitting the field leaves it untouched,\nso an unrelated edit never disturbs it.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventReminderOverride.md -->\n# Type Alias: EventReminderOverride\n\n> **EventReminderOverride** = \\{ `method`: `string`; `minutes`: `number`; \\}\n\nOne reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-method\"></a> `method` | `string` | Provider method, stored verbatim; only `popup` fires Macro notifications. |\n| <a id=\"property-minutes\"></a> `minutes` | `number` | Minutes before the event start. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventReminders.md -->\n# Type Alias: EventReminders\n\n> **EventReminders** = \\{ `overrides?`: [`EventReminderOverride`](EventReminderOverride.md)[]; `useDefault`: `boolean`; \\}\n\nPer-user reminder configuration for an event, mirroring Google's model:\neither the calendar's default reminders apply, or the explicit overrides\nreplace them entirely.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-overrides\"></a> `overrides?` | [`EventReminderOverride`](EventReminderOverride.md)[] | Explicit reminders replacing the defaults when `use_default` is off. |\n| <a id=\"property-usedefault\"></a> `useDefault` | `boolean` | Whether the calendar's default reminders apply. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventStatus.md -->\n# Type Alias: EventStatus\n\n> **EventStatus** = `\"confirmed\"` \\| `\"tentative\"` \\| `\"cancelled\"`\n\nCanonical event status.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTime.md -->\n# Type Alias: EventTime\n\n> **EventTime** = \\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\} \\| \\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nThe mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.\n\n## Union Members\n\n### Type Literal\n\n\\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endsAt` | `string` | Exclusive end instant; equal to the start for an imported point event. |\n| `kind` | `\"timed\"` | - |\n| `startsAt` | `string` | Inclusive start instant. |\n| `timeZone?` | `string` \\| `null` | Original IANA time-zone identifier, when supplied. |\n\n***\n\n### Type Literal\n\n\\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endDate` | `string` | Exclusive local end date. |\n| `kind` | `\"allDay\"` | - |\n| `startDate` | `string` | Inclusive local start date. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTransparency.md -->\n# Type Alias: EventTransparency\n\n> **EventTransparency** = `\"opaque\"` \\| `\"transparent\"`\n\nWhether an event blocks availability.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventType.md -->\n# Type Alias: EventType\n\n> **EventType** = `\"default\"` \\| `\"out_of_office\"` \\| `\"focus_time\"` \\| `\"working_location\"` \\| `\"birthday\"` \\| `\"from_gmail\"`\n\nGoogle's event type: ordinary meetings versus the status-style entries\n(working location, out of office, focus time, birthdays) Google renders\nand notifies differently. Immutable at the provider after creation.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventVisibility.md -->\n# Type Alias: EventVisibility\n\n> **EventVisibility** = `\"default\"` \\| `\"public\"` \\| `\"private\"` \\| `\"confidential\"`\n\nVisibility of event details.\n\n\n<!-- generated/calendar/types.gen/type-aliases/OutOfOfficeAutoDeclineMode.md -->\n# Type Alias: OutOfOfficeAutoDeclineMode\n\n> **OutOfOfficeAutoDeclineMode** = `\"decline_none\"` \\| `\"decline_all_conflicting_invitations\"` \\| `\"decline_only_new_conflicting_invitations\"`\n\nHow an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.\n\n\n<!-- generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md -->\n# Type Alias: OutOfOfficeProperties\n\n> **OutOfOfficeProperties** = \\{ `autoDeclineMode?`: [`OutOfOfficeAutoDeclineMode`](OutOfOfficeAutoDeclineMode.md); `declineMessage?`: `string` \\| `null`; \\}\n\nThe extra properties Google requires on an out-of-office event, mirroring\nits `outOfOfficeProperties` block. Their presence on a draft or patch is\nwhat marks the mutation as out-of-office.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodeclinemode\"></a> `autoDeclineMode?` | [`OutOfOfficeAutoDeclineMode`](OutOfOfficeAutoDeclineMode.md) | How conflicting invitations are handled while the user is out. |\n| <a id=\"property-declinemessage\"></a> `declineMessage?` | `string` \\| `null` | Message returned to organizers whose invitations are auto-declined. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/VisibleCalendar.md -->\n# Type Alias: VisibleCalendar\n\n> **VisibleCalendar** = \\{ `color?`: `string` \\| `null`; `defaultReminders`: [`EventReminderOverride`](EventReminderOverride.md)[]; `emailAddress`: `string`; `emailLinkId`: `string`; `id`: `string`; `isPrimary`: `boolean`; `isSubscription`: `boolean`; `isWritable`: `boolean`; `name`: `string`; `syncError?`: `string` \\| `null`; \\}\n\nA calendar visible to a requester, listed for pickers and filters.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-color\"></a> `color?` | `string` \\| `null` | Provider color. |\n| <a id=\"property-defaultreminders\"></a> `defaultReminders` | [`EventReminderOverride`](EventReminderOverride.md)[] | Default reminders applied to events that keep `useDefault`. |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `string` | Connected inbox address, for grouping in multi-inbox pickers. |\n| <a id=\"property-emaillinkid\"></a> `emailLinkId` | `string` | Connected inbox that syncs this calendar. |\n| <a id=\"property-id\"></a> `id` | `string` | Persisted Macro calendar identifier. |\n| <a id=\"property-isprimary\"></a> `isPrimary` | `boolean` | Whether this is its account's primary calendar. |\n| <a id=\"property-issubscription\"></a> `isSubscription` | `boolean` | Whether this is one of Google's shared system calendars (holidays, birthdays) the account subscribes to rather than one a person maintains. |\n| <a id=\"property-iswritable\"></a> `isWritable` | `boolean` | Whether the grant can create and modify events on this calendar. |\n| <a id=\"property-name\"></a> `name` | `string` | Provider display name. |\n| <a id=\"property-syncerror\"></a> `syncError?` | `string` \\| `null` | A persistent sync failure isolated to this calendar, surfaced so the settings row can badge it. `None` while the calendar is syncing normally or a failure has not yet crossed the persistence threshold. |\n\n\n<!-- src/entities/calendar/calendar/classes/Calendar.md -->\n# Class: Calendar\n\nA calendar visible to the requester across their connected inboxes: a\nfree-to-construct handle whose detail resolves from the caller's calendar\nlist. There is no fetch-by-id endpoint, so a bare [Calendar.byId](#byid)\nhandle loads its detail by listing the caller's calendars and matching on id.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Provider color, when set. | - |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `readonly` | () => `Promise`\\<`string`\\> | Connected inbox address that syncs this calendar. | - |\n| <a id=\"property-emaillink\"></a> `emailLink` | `readonly` | () => `Promise`\\<[`Link`](../../../email/link/classes/Link.md)\\> | The connected inbox (email link) that syncs this calendar. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-isprimary\"></a> `isPrimary` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether this is its account's primary calendar. | - |\n| <a id=\"property-issubscription\"></a> `isSubscription` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether this is a subscribed system calendar (holidays, birthdays). | - |\n| <a id=\"property-iswritable\"></a> `isWritable` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the grant can create and modify events on this calendar. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Provider display name. | - |\n| <a id=\"property-syncerror\"></a> `syncError` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | A persistent per-calendar sync failure, surfaced for settings badges. | - |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Calendar`\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Calendar`\n\n***\n\n### list()\n\n> `static` **list**(`client`): `Promise`\\<`Calendar`[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`Calendar`[]\\>\n\n\n<!-- src/entities/calendar/event/classes/CalendarEvent.md -->\n# Class: CalendarEvent\n\nA Macro calendar event: a handle exposing the event's synced fields and the\nmutations that act on it ([CalendarEvent.update](#update),\n[CalendarEvent.delete](#delete), [CalendarEvent.rsvp](#rsvp)).\n\nThe calendar service has no fetch-by-id endpoint, so a handle reads its\nfields only when seeded with a record — as returned by\n[CalendarEvent.update](#update), [CalendarEvent.rsvp](#rsvp), or\n`calendar.createEvent`. A bare [CalendarEvent.byId](#byid) handle can drive\nmutations, but reading a field on it throws.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `readonly` | () => `Promise`\\<[`CalendarAttendee`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendee.md)[]\\> | Attendees on the canonical copy. | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | () => `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md) \\| `undefined`\\> | The calendar the canonical source belongs to, when known. | - |\n| <a id=\"property-description\"></a> `description` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Optional event body. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the canonical source's calendar prohibits editing. | - |\n| <a id=\"property-location\"></a> `location` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Optional physical or virtual location label. | - |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `readonly` | () => `Promise`\\<`string`[]\\> | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`EventStatus`](../../../../../generated/calendar/types.gen/type-aliases/EventStatus.md)\\> | Event status. | - |\n| <a id=\"property-time\"></a> `time` | `readonly` | () => `Promise`\\<[`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md)\\> | Timed or all-day shape. | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | Display title. | - |\n| <a id=\"property-transparency\"></a> `transparency` | `readonly` | () => `Promise`\\<[`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md)\\> | Availability behavior. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(`options?`): `Promise`\\<`void`\\>\n\nDelete the event (or a scoped part of a recurring series) at its provider.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | [`DeleteEventOptions`](../interfaces/DeleteEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### record()\n\n> **record**(): `Promise`\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\nThe full synced event record. Available on a seeded handle (from create /\nupdate / rsvp); a bare `byId` handle throws (no fetch-by-id endpoint).\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\n***\n\n### rsvp()\n\n> **rsvp**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nRecord the requester's RSVP and return a handle to the synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RsvpEventOptions`](../interfaces/RsvpEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nUpdate the event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`UpdateEventOptions`](../interfaces/UpdateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `CalendarEvent`\n\nA handle to a calendar event by id, for driving mutations. Reading a\nfield on it throws (there is no fetch-by-id endpoint).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`CalendarEvent`\n\n***\n\n### fromRecord()\n\n> `static` **fromRecord**(`client`, `record`): `CalendarEvent`\n\nA handle seeded with a synced event record; reads resolve without a fetch.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md) |\n\n#### Returns\n\n`CalendarEvent`\n\n\n<!-- src/entities/calendar/event/interfaces/DeleteEventOptions.md -->\n# Interface: DeleteEventOptions\n\nHow a deletion is scoped across a recurring series.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is deleted, for a multi-calendar event. Omit to delete the canonical copy. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence a scoped deletion targets. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarDeletionScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarDeletionScopeParam.md) | Deletion scope; defaults to the entire event or series. |\n\n\n<!-- src/entities/calendar/event/interfaces/RsvpEventOptions.md -->\n# Interface: RsvpEventOptions\n\nThe RSVP to record and how it is scoped across a recurring series.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is answered, for a multi-calendar event. Omit to answer on the canonical copy. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the response targets. |\n| <a id=\"property-response\"></a> `response` | [`AttendeeResponseStatus`](../../../../../generated/calendar/types.gen/type-aliases/AttendeeResponseStatus.md) | The response to record for the connected account. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarRsvpScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarRsvpScopeParam.md) | How much of a recurring series the response covers. Omit to let `recurrenceId` decide. |\n\n\n<!-- src/entities/calendar/event/interfaces/UpdateEventOptions.md -->\n# Interface: UpdateEventOptions\n\nFields to change on an event; omitted fields are left untouched.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Replacement attendee list. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is patched, for a multi-calendar event. Omit to patch the canonical copy. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | `google_meet` attaches a fresh Meet, `none` detaches; omit to leave the conference untouched. |\n| <a id=\"property-description\"></a> `description?` | `string` | Replacement description; an empty string clears it. |\n| <a id=\"property-location\"></a> `location?` | `string` | Replacement location; an empty string clears it. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Replacement out-of-office properties, applied only to an event that is already out-of-office. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the update targets. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Replacement recurrence properties; an empty list clears them. |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Replacement reminder configuration. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarUpdateScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md) | How much of a recurring series the update covers. Omit to let `recurrenceId` decide. |\n| <a id=\"property-time\"></a> `time?` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Replacement time. |\n| <a id=\"property-title\"></a> `title?` | `string` | Replacement title; an empty string clears it. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Replacement availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Replacement visibility. |\n\n\n<!-- src/entities/calendar/namespace/classes/CalendarNamespace.md -->\n# Class: CalendarNamespace\n\nThe calendar surface: the caller's visible calendars, event creation, and\nhandles to individual events and calendars. Backed by calendar_service (the\nSDK reaches it on the gateway's `/calendar` route).\n\n## Constructors\n\n### Constructor\n\n> **new CalendarNamespace**(`client`): `CalendarNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`CalendarNamespace`\n\n## Methods\n\n### calendar()\n\n> **calendar**(`id`): [`Calendar`](../../calendar/classes/Calendar.md)\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Calendar`](../../calendar/classes/Calendar.md)\n\n***\n\n### calendars()\n\n> **calendars**(): `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Returns\n\n`Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\n***\n\n### createEvent()\n\n> **createEvent**(`options`): `Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\nCreate a calendar event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`CreateEventOptions`](../interfaces/CreateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\n***\n\n### event()\n\n> **event**(`id`): [`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\nA handle to a calendar event by id, for driving mutations.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\n\n<!-- src/entities/calendar/namespace/interfaces/CreateEventOptions.md -->\n# Interface: CreateEventOptions\n\nFields for a new calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Invited attendees. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Exact calendar to create the event on; takes precedence over the inbox default. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | Conference to attach; omit to create the event without one. |\n| <a id=\"property-description\"></a> `description?` | `string` | Optional event body. |\n| <a id=\"property-emaillink\"></a> `emailLink?` | [`Link`](../../../email/link/classes/Link.md) | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |\n| <a id=\"property-location\"></a> `location?` | `string` | Optional location label. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Out-of-office properties; present to create a Google out-of-office event. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Reminder configuration; omit to keep the calendar defaults. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Event visibility. |\n"
+ "overview": "<!-- src/entities/calendar/namespace/classes/CalendarNamespace.md -->\n# Class: CalendarNamespace\n\nThe calendar surface: the caller's visible calendars, event creation, and\nhandles to individual events and calendars. Backed by calendar_service (the\nSDK reaches it on the gateway's `/calendar` route).\n\n## Constructors\n\n### Constructor\n\n> **new CalendarNamespace**(`client`): `CalendarNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`CalendarNamespace`\n\n## Methods\n\n### calendar()\n\n> **calendar**(`id`): [`Calendar`](../../calendar/classes/Calendar.md)\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Calendar`](../../calendar/classes/Calendar.md)\n\n***\n\n### calendars()\n\n> **calendars**(): `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Returns\n\n`Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\n***\n\n### createEvent()\n\n> **createEvent**(`options`): `Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\nCreate a calendar event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`CreateEventOptions`](../interfaces/CreateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\n***\n\n### event()\n\n> **event**(`id`): [`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\nA handle to a calendar event by id, for driving mutations.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\n\n<!-- src/entities/calendar/namespace/interfaces/CreateEventOptions.md -->\n# Interface: CreateEventOptions\n\nFields for a new calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Invited attendees. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Exact calendar to create the event on; takes precedence over the inbox default. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | Conference to attach; omit to create the event without one. |\n| <a id=\"property-description\"></a> `description?` | `string` | Optional event body. |\n| <a id=\"property-emaillink\"></a> `emailLink?` | [`Link`](../../../email/link/classes/Link.md) | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |\n| <a id=\"property-location\"></a> `location?` | `string` | Optional location label. |\n| <a id=\"property-macrocall\"></a> `macroCall?` | `boolean` | Mint a Macro call with the event; its join link lands in the description and location. Cannot be combined with `conference`. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Out-of-office properties; present to create a Google out-of-office event. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Reminder configuration; omit to keep the calendar defaults. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Event visibility. |\n",
+ "documentation": "# Macro SDK: calendar\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/calendar/types.gen/type-aliases/AttendeeResponseStatus.md -->\n# Type Alias: AttendeeResponseStatus\n\n> **AttendeeResponseStatus** = `\"needs_action\"` \\| `\"accepted\"` \\| `\"declined\"` \\| `\"tentative\"`\n\nRSVP state for an attendee.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarAttendee.md -->\n# Type Alias: CalendarAttendee\n\n> **CalendarAttendee** = \\{ `comment?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `email`: `string`; `isOptional`: `boolean`; `isOrganizer`: `boolean`; `isSelf`: `boolean`; `responseStatus`: [`AttendeeResponseStatus`](AttendeeResponseStatus.md); \\}\n\nAn attendee on a calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Optional attendee comment. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Provider display name. |\n| <a id=\"property-email\"></a> `email` | `string` | Normalized email address. |\n| <a id=\"property-isoptional\"></a> `isOptional` | `boolean` | Whether attendance is optional. |\n| <a id=\"property-isorganizer\"></a> `isOrganizer` | `boolean` | Whether this attendee is the organizer. |\n| <a id=\"property-isself\"></a> `isSelf` | `boolean` | Whether this attendee is one of the viewing requester's inboxes. |\n| <a id=\"property-responsestatus\"></a> `responseStatus` | [`AttendeeResponseStatus`](AttendeeResponseStatus.md) | RSVP state. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md -->\n# Type Alias: CalendarAttendeeInputBody\n\n> **CalendarAttendeeInputBody** = \\{ `email`: `string`; `isOptional?`: `boolean`; \\}\n\nAn attendee supplied to a calendar mutation.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Attendee email address. |\n| <a id=\"property-isoptional\"></a> `isOptional?` | `boolean` | Whether attendance is optional. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarDeletionScopeParam.md -->\n# Type Alias: CalendarDeletionScopeParam\n\n> **CalendarDeletionScopeParam** = `\"all\"` \\| `\"this_event\"` \\| `\"this_and_following\"`\n\nHow much of a recurring series a deletion removes.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarEvent.md -->\n# Type Alias: CalendarEvent\n\n> **CalendarEvent** = \\{ `attendees`: [`CalendarAttendee`](CalendarAttendee.md)[]; `calendarId?`: `string` \\| `null`; `conferenceProvider?`: `null` \\| [`ConferenceProvider`](ConferenceProvider.md); `conferenceUrl?`: `string` \\| `null`; `createdAt`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: [`EventType`](EventType.md); `icalUid`: `string`; `id`: `string`; `isReadOnly`: `boolean`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `ownerId`: `string`; `recurrenceLines`: `string`[]; `reminders?`: [`EventReminders`](EventReminders.md); `sequence`: `number`; `sources?`: [`CalendarEventSourceContent`](CalendarEventSourceContent.md)[]; `status`: [`EventStatus`](EventStatus.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `transparency`: [`EventTransparency`](EventTransparency.md); `updatedAt`: `string`; `visibility`: [`EventVisibility`](EventVisibility.md); \\}\n\nA stable, first-class Macro calendar event entity.\n\nContent fields hold the canonical source's values: the account's primary\ncalendar copy when one is synced, else the freshest remaining copy.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | [`CalendarAttendee`](CalendarAttendee.md)[] | Attendees, keyed by email during persistence. |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` | Calendar the canonical source belongs to, when known. Absent only in projections stored before calendars were attributed. |\n| <a id=\"property-conferenceprovider\"></a> `conferenceProvider?` | `null` \\| [`ConferenceProvider`](ConferenceProvider.md) | - |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Direct join URL when known. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Entity creation time. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. Distinct from the organizer when someone writes onto a calendar they do not own. Omitted from stored projections when unknown so events ingested before this field still compare equal. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType?` | [`EventType`](EventType.md) | Provider event type. Skipped when it is the regular type so projections stored before event types were modeled still compare equal. |\n| <a id=\"property-icaluid\"></a> `icalUid` | `string` | RFC 5545 UID used to reconcile provider and email sources. |\n| <a id=\"property-id\"></a> `id` | `string` | Macro entity identifier. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the canonical source's calendar prohibits editing it. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer email. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer display name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who owns this event entity. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](EventReminders.md) | Per-user reminder configuration. Skipped when it is the provider default so projections stored before reminders were modeled still compare equal. |\n| <a id=\"property-sequence\"></a> `sequence` | `number` | Provider/iCalendar sequence number. |\n| <a id=\"property-sources\"></a> `sources?` | [`CalendarEventSourceContent`](CalendarEventSourceContent.md)[] | Content of every active copy of this event, canonical first: the primary calendar's copy, then the freshest. A client picks the copy whose calendar it is showing and falls back to the first. Populated only on the read path, so stored projections omit it. |\n| <a id=\"property-status\"></a> `status` | [`EventStatus`](EventStatus.md) | Event status. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | [`EventTransparency`](EventTransparency.md) | Availability behavior. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Entity update time. |\n| <a id=\"property-visibility\"></a> `visibility` | [`EventVisibility`](EventVisibility.md) | Event visibility. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarEventSourceContent.md -->\n# Type Alias: CalendarEventSourceContent\n\n> **CalendarEventSourceContent** = \\{ `calendarId`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType`: [`EventType`](EventType.md); `isReadOnly`: `boolean`; `location?`: `string` \\| `null`; `reminders`: [`EventReminders`](EventReminders.md); `title`: `string`; `transparency`: [`EventTransparency`](EventTransparency.md); `visibility`: [`EventVisibility`](EventVisibility.md); \\}\n\nThe content one provider copy of an event carries.\n\nGoogle keeps these fields per calendar copy: a shared calendar's copy of a\nmember's event can have its own title, type, reminders, and access role.\nThe entity holds its canonical source's values. Every other copy's values\nare read from here so a client can show the copy that belongs to the\ncalendar being viewed.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendarid\"></a> `calendarId` | `string` | Calendar this copy lives on. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType` | [`EventType`](EventType.md) | Provider event type. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the calendar's access role prohibits editing this copy. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-reminders\"></a> `reminders` | [`EventReminders`](EventReminders.md) | Reminder configuration of this copy. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | [`EventTransparency`](EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility` | [`EventVisibility`](EventVisibility.md) | Event visibility. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarRsvpScopeParam.md -->\n# Type Alias: CalendarRsvpScopeParam\n\n> **CalendarRsvpScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an RSVP applies to.\n\nUnlike deletion there is no this-and-following variant: the provider\ncannot express a forward-scoped response, so offering one would be a\npromise sync could not keep.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md -->\n# Type Alias: CalendarUpdateScopeParam\n\n> **CalendarUpdateScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an update applies to.\n\nLike RSVPs there is no this-and-following variant: the provider cannot\nexpress a forward-scoped edit as one write, and emulating it (truncate\nthe series, insert an edited clone) is non-atomic and re-invites the\nattendees of the clone. Compose it from a this-and-following deletion\nand a create when that shape is wanted.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ConferenceChange.md -->\n# Type Alias: ConferenceChange\n\n> **ConferenceChange** = `\"google_meet\"` \\| `\"none\"`\n\nA requested change to an event's conferencing. Omitting the field leaves\nthe existing conference untouched; only these values change it.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ConferenceProvider.md -->\n# Type Alias: ConferenceProvider\n\n> **ConferenceProvider** = `\"google_meet\"` \\| `\"other\"`\n\nThe conferencing system backing an event's join URL.\n\nMacro generates only Google Meet conferences, so this distinguishes one it\ncreated from a third party's — Zoom and friends arriving as `addOn`\nconference data, or a legacy classic Hangout. Clients use it to label the\nconference and to tell whether the Meet toggle reflects a Macro-managed\nconference.\n\nIt does not gate mutation. An explicit request replaces or detaches any\nconference, third-party included, exactly as deleting the event would;\nwhat protects a conference is that omitting the field leaves it untouched,\nso an unrelated edit never disturbs it.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventReminderOverride.md -->\n# Type Alias: EventReminderOverride\n\n> **EventReminderOverride** = \\{ `method`: `string`; `minutes`: `number`; \\}\n\nOne reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-method\"></a> `method` | `string` | Provider method, stored verbatim; only `popup` fires Macro notifications. |\n| <a id=\"property-minutes\"></a> `minutes` | `number` | Minutes before the event start. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventReminders.md -->\n# Type Alias: EventReminders\n\n> **EventReminders** = \\{ `overrides?`: [`EventReminderOverride`](EventReminderOverride.md)[]; `useDefault`: `boolean`; \\}\n\nPer-user reminder configuration for an event, mirroring Google's model:\neither the calendar's default reminders apply, or the explicit overrides\nreplace them entirely.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-overrides\"></a> `overrides?` | [`EventReminderOverride`](EventReminderOverride.md)[] | Explicit reminders replacing the defaults when `use_default` is off. |\n| <a id=\"property-usedefault\"></a> `useDefault` | `boolean` | Whether the calendar's default reminders apply. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventStatus.md -->\n# Type Alias: EventStatus\n\n> **EventStatus** = `\"confirmed\"` \\| `\"tentative\"` \\| `\"cancelled\"`\n\nCanonical event status.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTime.md -->\n# Type Alias: EventTime\n\n> **EventTime** = \\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\} \\| \\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nThe mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.\n\n## Union Members\n\n### Type Literal\n\n\\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endsAt` | `string` | Exclusive end instant; equal to the start for an imported point event. |\n| `kind` | `\"timed\"` | - |\n| `startsAt` | `string` | Inclusive start instant. |\n| `timeZone?` | `string` \\| `null` | Original IANA time-zone identifier, when supplied. |\n\n***\n\n### Type Literal\n\n\\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endDate` | `string` | Exclusive local end date. |\n| `kind` | `\"allDay\"` | - |\n| `startDate` | `string` | Inclusive local start date. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTransparency.md -->\n# Type Alias: EventTransparency\n\n> **EventTransparency** = `\"opaque\"` \\| `\"transparent\"`\n\nWhether an event blocks availability.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventType.md -->\n# Type Alias: EventType\n\n> **EventType** = `\"default\"` \\| `\"out_of_office\"` \\| `\"focus_time\"` \\| `\"working_location\"` \\| `\"birthday\"` \\| `\"from_gmail\"`\n\nGoogle's event type: ordinary meetings versus the status-style entries\n(working location, out of office, focus time, birthdays) Google renders\nand notifies differently. Immutable at the provider after creation.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventVisibility.md -->\n# Type Alias: EventVisibility\n\n> **EventVisibility** = `\"default\"` \\| `\"public\"` \\| `\"private\"` \\| `\"confidential\"`\n\nVisibility of event details.\n\n\n<!-- generated/calendar/types.gen/type-aliases/OutOfOfficeAutoDeclineMode.md -->\n# Type Alias: OutOfOfficeAutoDeclineMode\n\n> **OutOfOfficeAutoDeclineMode** = `\"decline_none\"` \\| `\"decline_all_conflicting_invitations\"` \\| `\"decline_only_new_conflicting_invitations\"`\n\nHow an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.\n\n\n<!-- generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md -->\n# Type Alias: OutOfOfficeProperties\n\n> **OutOfOfficeProperties** = \\{ `autoDeclineMode?`: [`OutOfOfficeAutoDeclineMode`](OutOfOfficeAutoDeclineMode.md); `declineMessage?`: `string` \\| `null`; \\}\n\nThe extra properties Google requires on an out-of-office event, mirroring\nits `outOfOfficeProperties` block. Their presence on a draft or patch is\nwhat marks the mutation as out-of-office.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodeclinemode\"></a> `autoDeclineMode?` | [`OutOfOfficeAutoDeclineMode`](OutOfOfficeAutoDeclineMode.md) | How conflicting invitations are handled while the user is out. |\n| <a id=\"property-declinemessage\"></a> `declineMessage?` | `string` \\| `null` | Message returned to organizers whose invitations are auto-declined. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/VisibleCalendar.md -->\n# Type Alias: VisibleCalendar\n\n> **VisibleCalendar** = \\{ `color?`: `string` \\| `null`; `defaultReminders`: [`EventReminderOverride`](EventReminderOverride.md)[]; `emailAddress`: `string`; `emailLinkId`: `string`; `id`: `string`; `isPrimary`: `boolean`; `isSubscription`: `boolean`; `isWritable`: `boolean`; `name`: `string`; `syncError?`: `string` \\| `null`; \\}\n\nA calendar visible to a requester, listed for pickers and filters.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-color\"></a> `color?` | `string` \\| `null` | Provider color. |\n| <a id=\"property-defaultreminders\"></a> `defaultReminders` | [`EventReminderOverride`](EventReminderOverride.md)[] | Default reminders applied to events that keep `useDefault`. |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `string` | Connected inbox address, for grouping in multi-inbox pickers. |\n| <a id=\"property-emaillinkid\"></a> `emailLinkId` | `string` | Connected inbox that syncs this calendar. |\n| <a id=\"property-id\"></a> `id` | `string` | Persisted Macro calendar identifier. |\n| <a id=\"property-isprimary\"></a> `isPrimary` | `boolean` | Whether this is its account's primary calendar. |\n| <a id=\"property-issubscription\"></a> `isSubscription` | `boolean` | Whether this is one of Google's shared system calendars (holidays, birthdays) the account subscribes to rather than one a person maintains. |\n| <a id=\"property-iswritable\"></a> `isWritable` | `boolean` | Whether the grant can create and modify events on this calendar. |\n| <a id=\"property-name\"></a> `name` | `string` | Provider display name. |\n| <a id=\"property-syncerror\"></a> `syncError?` | `string` \\| `null` | A persistent sync failure isolated to this calendar, surfaced so the settings row can badge it. `None` while the calendar is syncing normally or a failure has not yet crossed the persistence threshold. |\n\n\n<!-- src/entities/calendar/calendar/classes/Calendar.md -->\n# Class: Calendar\n\nA calendar visible to the requester across their connected inboxes: a\nfree-to-construct handle whose detail resolves from the caller's calendar\nlist. There is no fetch-by-id endpoint, so a bare [Calendar.byId](#byid)\nhandle loads its detail by listing the caller's calendars and matching on id.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Provider color, when set. | - |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `readonly` | () => `Promise`\\<`string`\\> | Connected inbox address that syncs this calendar. | - |\n| <a id=\"property-emaillink\"></a> `emailLink` | `readonly` | () => `Promise`\\<[`Link`](../../../email/link/classes/Link.md)\\> | The connected inbox (email link) that syncs this calendar. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-isprimary\"></a> `isPrimary` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether this is its account's primary calendar. | - |\n| <a id=\"property-issubscription\"></a> `isSubscription` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether this is a subscribed system calendar (holidays, birthdays). | - |\n| <a id=\"property-iswritable\"></a> `isWritable` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the grant can create and modify events on this calendar. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Provider display name. | - |\n| <a id=\"property-syncerror\"></a> `syncError` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | A persistent per-calendar sync failure, surfaced for settings badges. | - |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`VisibleCalendar`](../../../../../generated/calendar/types.gen/type-aliases/VisibleCalendar.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Calendar`\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Calendar`\n\n***\n\n### list()\n\n> `static` **list**(`client`): `Promise`\\<`Calendar`[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`Calendar`[]\\>\n\n\n<!-- src/entities/calendar/event/classes/CalendarEvent.md -->\n# Class: CalendarEvent\n\nA Macro calendar event: a handle exposing the event's synced fields and the\nmutations that act on it ([CalendarEvent.update](#update),\n[CalendarEvent.delete](#delete), [CalendarEvent.rsvp](#rsvp)).\n\nThe calendar service has no fetch-by-id endpoint, so a handle reads its\nfields only when seeded with a record — as returned by\n[CalendarEvent.update](#update), [CalendarEvent.rsvp](#rsvp), or\n`calendar.createEvent`. A bare [CalendarEvent.byId](#byid) handle can drive\nmutations, but reading a field on it throws.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `readonly` | () => `Promise`\\<[`CalendarAttendee`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendee.md)[]\\> | Attendees on the canonical copy. | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | () => `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md) \\| `undefined`\\> | The calendar the canonical source belongs to, when known. | - |\n| <a id=\"property-description\"></a> `description` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Optional event body. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the canonical source's calendar prohibits editing. | - |\n| <a id=\"property-location\"></a> `location` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Optional physical or virtual location label. | - |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `readonly` | () => `Promise`\\<`string`[]\\> | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`EventStatus`](../../../../../generated/calendar/types.gen/type-aliases/EventStatus.md)\\> | Event status. | - |\n| <a id=\"property-time\"></a> `time` | `readonly` | () => `Promise`\\<[`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md)\\> | Timed or all-day shape. | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | Display title. | - |\n| <a id=\"property-transparency\"></a> `transparency` | `readonly` | () => `Promise`\\<[`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md)\\> | Availability behavior. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(`options?`): `Promise`\\<`void`\\>\n\nDelete the event (or a scoped part of a recurring series) at its provider.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | [`DeleteEventOptions`](../interfaces/DeleteEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### record()\n\n> **record**(): `Promise`\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\nThe full synced event record. Available on a seeded handle (from create /\nupdate / rsvp); a bare `byId` handle throws (no fetch-by-id endpoint).\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md)\\>\n\n***\n\n### rsvp()\n\n> **rsvp**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nRecord the requester's RSVP and return a handle to the synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RsvpEventOptions`](../interfaces/RsvpEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nUpdate the event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`UpdateEventOptions`](../interfaces/UpdateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `CalendarEvent`\n\nA handle to a calendar event by id, for driving mutations. Reading a\nfield on it throws (there is no fetch-by-id endpoint).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`CalendarEvent`\n\n***\n\n### fromRecord()\n\n> `static` **fromRecord**(`client`, `record`): `CalendarEvent`\n\nA handle seeded with a synced event record; reads resolve without a fetch.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`CalendarEvent`](../../../../../generated/calendar/types.gen/type-aliases/CalendarEvent.md) |\n\n#### Returns\n\n`CalendarEvent`\n\n\n<!-- src/entities/calendar/event/interfaces/DeleteEventOptions.md -->\n# Interface: DeleteEventOptions\n\nHow a deletion is scoped across a recurring series.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is deleted, for a multi-calendar event. Omit to delete the canonical copy. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence a scoped deletion targets. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarDeletionScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarDeletionScopeParam.md) | Deletion scope; defaults to the entire event or series. |\n\n\n<!-- src/entities/calendar/event/interfaces/RsvpEventOptions.md -->\n# Interface: RsvpEventOptions\n\nThe RSVP to record and how it is scoped across a recurring series.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is answered, for a multi-calendar event. Omit to answer on the canonical copy. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the response targets. |\n| <a id=\"property-response\"></a> `response` | [`AttendeeResponseStatus`](../../../../../generated/calendar/types.gen/type-aliases/AttendeeResponseStatus.md) | The response to record for the connected account. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarRsvpScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarRsvpScopeParam.md) | How much of a recurring series the response covers. Omit to let `recurrenceId` decide. |\n\n\n<!-- src/entities/calendar/event/interfaces/UpdateEventOptions.md -->\n# Interface: UpdateEventOptions\n\nFields to change on an event; omitted fields are left untouched.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Replacement attendee list. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Calendar whose copy of the event is patched, for a multi-calendar event. Omit to patch the canonical copy. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | `google_meet` attaches a fresh Meet, `none` detaches; omit to leave the conference untouched. |\n| <a id=\"property-description\"></a> `description?` | `string` | Replacement description; an empty string clears it. |\n| <a id=\"property-location\"></a> `location?` | `string` | Replacement location; an empty string clears it. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Replacement out-of-office properties, applied only to an event that is already out-of-office. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the update targets. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Replacement recurrence properties; an empty list clears them. |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Replacement reminder configuration. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarUpdateScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md) | How much of a recurring series the update covers. Omit to let `recurrenceId` decide. |\n| <a id=\"property-time\"></a> `time?` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Replacement time. |\n| <a id=\"property-title\"></a> `title?` | `string` | Replacement title; an empty string clears it. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Replacement availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Replacement visibility. |\n\n\n<!-- src/entities/calendar/namespace/classes/CalendarNamespace.md -->\n# Class: CalendarNamespace\n\nThe calendar surface: the caller's visible calendars, event creation, and\nhandles to individual events and calendars. Backed by calendar_service (the\nSDK reaches it on the gateway's `/calendar` route).\n\n## Constructors\n\n### Constructor\n\n> **new CalendarNamespace**(`client`): `CalendarNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`CalendarNamespace`\n\n## Methods\n\n### calendar()\n\n> **calendar**(`id`): [`Calendar`](../../calendar/classes/Calendar.md)\n\nA handle to a calendar by id. Detail loads on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Calendar`](../../calendar/classes/Calendar.md)\n\n***\n\n### calendars()\n\n> **calendars**(): `Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\nThe caller's visible calendars, primaries and writable first.\n\n#### Returns\n\n`Promise`\\<[`Calendar`](../../calendar/classes/Calendar.md)[]\\>\n\n***\n\n### createEvent()\n\n> **createEvent**(`options`): `Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\nCreate a calendar event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`CreateEventOptions`](../interfaces/CreateEventOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarEvent`](../../event/classes/CalendarEvent.md)\\>\n\n***\n\n### event()\n\n> **event**(`id`): [`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\nA handle to a calendar event by id, for driving mutations.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`CalendarEvent`](../../event/classes/CalendarEvent.md)\n\n\n<!-- src/entities/calendar/namespace/interfaces/CreateEventOptions.md -->\n# Interface: CreateEventOptions\n\nFields for a new calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | [`CalendarAttendeeInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarAttendeeInputBody.md)[] | Invited attendees. |\n| <a id=\"property-calendar\"></a> `calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) | Exact calendar to create the event on; takes precedence over the inbox default. |\n| <a id=\"property-conference\"></a> `conference?` | [`ConferenceChange`](../../../../../generated/calendar/types.gen/type-aliases/ConferenceChange.md) | Conference to attach; omit to create the event without one. |\n| <a id=\"property-description\"></a> `description?` | `string` | Optional event body. |\n| <a id=\"property-emaillink\"></a> `emailLink?` | [`Link`](../../../email/link/classes/Link.md) | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |\n| <a id=\"property-location\"></a> `location?` | `string` | Optional location label. |\n| <a id=\"property-macrocall\"></a> `macroCall?` | `boolean` | Mint a Macro call with the event; its join link lands in the description and location. Cannot be combined with `conference`. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Out-of-office properties; present to create a Google out-of-office event. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Reminder configuration; omit to keep the calendar defaults. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency?` | [`EventTransparency`](../../../../../generated/calendar/types.gen/type-aliases/EventTransparency.md) | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | [`EventVisibility`](../../../../../generated/calendar/types.gen/type-aliases/EventVisibility.md) | Event visibility. |\n"
},
{
"name": "calls",
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index a41beb6849..9b956dabfc 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -6,7 +6,9 @@ use chrono::{DateTime, Utc};
use rootcause::Report;
use uuid::Uuid;
-use super::meeting_links::{MeetingLink, MeetingLinkError, MeetingLinkRequest};
+use super::meeting_links::{
+ CreateEventWithMacroCallError, MeetingLink, MeetingLinkError, MeetingLinkRequest,
+};
use super::models::{
ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee,
CalendarBackfillClaim, CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome,
@@ -728,6 +730,26 @@ pub trait CalendarMutationService: Send + Sync + 'static {
) -> impl Future<Output = Result<(), CalendarMutationError>> + Send;
}
+/// Inbound service port creating events that carry a Macro call.
+///
+/// The meeting is minted before the calendar write, so the one invitation
+/// attendees receive already names the call, and its join link travels in
+/// the event's description and location. Hosts that mint meetings compose a
+/// [`CalendarMutationService`] with a [`MeetingLinkProvider`] through
+/// [`super::meeting_links::create_event_with_macro_call`]; hosts that are
+/// not the calendar write authority forward the request to the calendar
+/// service.
+pub trait CalendarMacroCallService: Send + Sync + 'static {
+ /// Mint a Macro call for `draft` and create the event carrying its link.
+ fn create_event_with_macro_call(
+ &self,
+ requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> impl Future<Output = Result<CalendarEvent, CreateEventWithMacroCallError>> + Send;
+}
+
/// Outbound port minting Macro meetings for calendar events.
///
/// Implementations act as the requester: the meeting is owned by the user
diff --git a/crates/calendar_events/src/inbound/mutation_router.rs b/crates/calendar_events/src/inbound/mutation_router.rs
index fecc7bbb37..b56fd26370 100644
--- a/crates/calendar_events/src/inbound/mutation_router.rs
+++ b/crates/calendar_events/src/inbound/mutation_router.rs
@@ -23,6 +23,9 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::domain::{
+ meeting_links::{
+ CreateEventWithMacroCallError, MeetingLinkError, create_event_with_macro_call,
+ },
models::{
AttendeeResponseStatus, CalendarAttendeeInput, CalendarEvent, CalendarEventDraft,
CalendarEventPatch, ConferenceChange, EventReminders, EventTime, EventTransparency,
@@ -30,61 +33,72 @@ use crate::domain::{
},
ports::{
CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
- CalendarUpdateScope,
+ CalendarUpdateScope, MeetingLinkProvider,
},
};
/// Router state for authenticated calendar mutations.
-pub struct CalendarMutationRouterState<S, Auth> {
+pub struct CalendarMutationRouterState<S, L, Auth> {
service: Arc<S>,
+ meeting_links: Arc<L>,
authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, Auth> Clone for CalendarMutationRouterState<S, Auth> {
+impl<S, L, Auth> Clone for CalendarMutationRouterState<S, L, Auth> {
fn clone(&self) -> Self {
Self {
service: Arc::clone(&self.service),
+ meeting_links: Arc::clone(&self.meeting_links),
authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S, Auth> CalendarMutationRouterState<S, Auth> {
- /// Create router state from a shared mutation service and authorization state.
- pub fn new(service: Arc<S>, authorization_state: MacroAuthorizationState<Auth>) -> Self {
+impl<S, L, Auth> CalendarMutationRouterState<S, L, Auth> {
+ /// Create router state from a shared mutation service, the meeting-link
+ /// provider minting Macro calls for new events, and authorization state.
+ pub fn new(
+ service: Arc<S>,
+ meeting_links: Arc<L>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
Self {
service,
+ meeting_links,
authorization_state,
}
}
}
-impl<S, Auth> FromRef<CalendarMutationRouterState<S, Auth>> for MacroAuthorizationState<Auth> {
- fn from_ref(state: &CalendarMutationRouterState<S, Auth>) -> Self {
+impl<S, L, Auth> FromRef<CalendarMutationRouterState<S, L, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &CalendarMutationRouterState<S, L, Auth>) -> Self {
state.authorization_state.clone()
}
}
/// Build the authenticated calendar mutation router, exposing `/calendars`
/// and `/events` (mounted under `/calendar` by the service).
-pub fn calendar_mutation_router<S, Auth, T>(
- state: CalendarMutationRouterState<S, Auth>,
+pub fn calendar_mutation_router<S, L, Auth, T>(
+ state: CalendarMutationRouterState<S, L, Auth>,
) -> Router<T>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
T: Send + Sync + 'static,
{
Router::new()
- .route("/calendars", get(list_calendars::<S, Auth>))
- .route("/events", post(create_calendar_event::<S, Auth>))
+ .route("/calendars", get(list_calendars::<S, L, Auth>))
+ .route("/events", post(create_calendar_event::<S, L, Auth>))
.route(
"/events/{event_id}",
- patch(update_calendar_event::<S, Auth>).delete(delete_calendar_event::<S, Auth>),
+ patch(update_calendar_event::<S, L, Auth>).delete(delete_calendar_event::<S, L, Auth>),
)
.route(
"/events/{event_id}/rsvp",
- put(rsvp_calendar_event::<S, Auth>),
+ put(rsvp_calendar_event::<S, L, Auth>),
)
.with_state(state)
}
@@ -144,6 +158,11 @@ pub struct CreateCalendarEventRequest {
pub reminders: Option<EventReminders>,
/// Conference to attach to the new event; omit to create it without one.
pub conference: Option<ConferenceChange>,
+ /// Mint a Macro call and write its join link into the description and
+ /// location before creating the event, so the invitation carries it.
+ /// Cannot be combined with `conference`.
+ #[serde(default)]
+ pub macro_call: bool,
/// Out-of-office properties; present to create the event as a Google
/// out-of-office status event (primary calendar only, timed, no
/// attendees), omitted for a regular event.
@@ -302,6 +321,9 @@ pub enum CalendarMutationErrorCode {
/// The provider applied the mutation but local persistence lagged;
/// refetching converges.
PersistFailed,
+ /// The Macro call for a new event could not be created; nothing was
+ /// written to the calendar.
+ MacroCallFailed,
}
/// HTTP error body returned by calendar mutation endpoints.
@@ -397,6 +419,31 @@ impl From<CalendarMutationError> for CalendarMutationApiError {
}
}
+impl From<CreateEventWithMacroCallError> for CalendarMutationApiError {
+ fn from(error: CreateEventWithMacroCallError) -> Self {
+ match error {
+ CreateEventWithMacroCallError::Calendar(error) => error.into(),
+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::InvalidInput(message)) => {
+ Self {
+ code: CalendarMutationErrorCode::InvalidInput,
+ message,
+ status: StatusCode::BAD_REQUEST,
+ }
+ }
+ CreateEventWithMacroCallError::MeetingLink(error) => {
+ tracing::error!(error = ?error, "calendar event macro call creation failed");
+ Self {
+ code: CalendarMutationErrorCode::MacroCallFailed,
+ message: "the Macro call for the event could not be created; the event was \
+ not saved"
+ .to_string(),
+ status: StatusCode::SERVICE_UNAVAILABLE,
+ }
+ }
+ }
+ }
+}
+
/// Create a calendar event and return its synced entity.
#[tracing::instrument(skip_all, err)]
#[utoipa::path(
@@ -410,16 +457,17 @@ impl From<CalendarMutationError> for CalendarMutationApiError {
(status = 401, description = "Authentication required"),
(status = 403, description = "Calendar is read-only or needs reauthorization", body = CalendarMutationApiError),
(status = 409, description = "No writable calendar or the provider rejected the event", body = CalendarMutationApiError),
- (status = 503, description = "Transient provider failure", body = CalendarMutationApiError),
+ (status = 503, description = "Transient provider failure, or the Macro call could not be created", body = CalendarMutationApiError),
)
)]
-pub async fn create_calendar_event<S, Auth>(
- State(state): State<CalendarMutationRouterState<S, Auth>>,
+pub async fn create_calendar_event<S, L, Auth>(
+ State(state): State<CalendarMutationRouterState<S, L, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(request): Json<CreateCalendarEventRequest>,
) -> Result<(StatusCode, Json<CalendarEvent>), CalendarMutationApiError>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
{
let draft = CalendarEventDraft {
@@ -436,15 +484,29 @@ where
conference: request.conference,
out_of_office: request.out_of_office,
};
- let event = state
- .service
- .create_event(
- user.authorization.user.macro_user_id.as_ref(),
+ let requester_id: &str = user.authorization.user.macro_user_id.as_ref();
+ let event = if request.macro_call {
+ create_event_with_macro_call(
+ &*state.service,
+ &*state.meeting_links,
+ requester_id,
request.email_link_id,
request.calendar_id,
draft,
)
- .await?;
+ .await?
+ .event
+ } else {
+ state
+ .service
+ .create_event(
+ requester_id,
+ request.email_link_id,
+ request.calendar_id,
+ draft,
+ )
+ .await?
+ };
Ok((StatusCode::CREATED, Json(event)))
}
@@ -468,12 +530,13 @@ pub struct ListCalendarsResponse {
(status = 503, description = "Transient failure", body = CalendarMutationApiError),
)
)]
-pub async fn list_calendars<S, Auth>(
- State(state): State<CalendarMutationRouterState<S, Auth>>,
+pub async fn list_calendars<S, L, Auth>(
+ State(state): State<CalendarMutationRouterState<S, L, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<Json<ListCalendarsResponse>, CalendarMutationApiError>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
{
let calendars = state
@@ -526,14 +589,15 @@ fn update_scope(
(status = 503, description = "Transient provider failure", body = CalendarMutationApiError),
)
)]
-pub async fn update_calendar_event<S, Auth>(
- State(state): State<CalendarMutationRouterState<S, Auth>>,
+pub async fn update_calendar_event<S, L, Auth>(
+ State(state): State<CalendarMutationRouterState<S, L, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(event_id): Path<Uuid>,
Json(request): Json<UpdateCalendarEventRequest>,
) -> Result<Json<CalendarEvent>, CalendarMutationApiError>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
{
let scope = update_scope(request.scope, request.recurrence_id)?;
@@ -584,14 +648,15 @@ where
(status = 503, description = "Transient provider failure", body = CalendarMutationApiError),
)
)]
-pub async fn delete_calendar_event<S, Auth>(
- State(state): State<CalendarMutationRouterState<S, Auth>>,
+pub async fn delete_calendar_event<S, L, Auth>(
+ State(state): State<CalendarMutationRouterState<S, L, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(event_id): Path<Uuid>,
Query(query): Query<DeleteCalendarEventQuery>,
) -> Result<StatusCode, CalendarMutationApiError>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
{
let scoped_occurrence = |kind: &'static str| {
@@ -639,14 +704,15 @@ where
(status = 503, description = "Transient provider failure", body = CalendarMutationApiError),
)
)]
-pub async fn rsvp_calendar_event<S, Auth>(
- State(state): State<CalendarMutationRouterState<S, Auth>>,
+pub async fn rsvp_calendar_event<S, L, Auth>(
+ State(state): State<CalendarMutationRouterState<S, L, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(event_id): Path<Uuid>,
Json(request): Json<RsvpCalendarEventRequest>,
) -> Result<Json<CalendarEvent>, CalendarMutationApiError>
where
S: CalendarMutationService,
+ L: MeetingLinkProvider,
Auth: MacroAuthorizationService,
{
let scope = match (request.scope, request.recurrence_id) {
diff --git a/crates/calendar_events/src/inbound/mutation_router/test.rs b/crates/calendar_events/src/inbound/mutation_router/test.rs
index 7b893883ac..a956ce3559 100644
--- a/crates/calendar_events/src/inbound/mutation_router/test.rs
+++ b/crates/calendar_events/src/inbound/mutation_router/test.rs
@@ -117,3 +117,56 @@ fn attendee_body_defaults_to_required_attendance() {
assert!(!input.is_optional);
assert_eq!(input.email, "[email protected]");
}
+
+#[test]
+fn macro_call_failures_map_to_transport_semantics() {
+ let failed = CalendarMutationApiError::from(CreateEventWithMacroCallError::MeetingLink(
+ MeetingLinkError::Failed("call service at 10.0.0.9 returned 502".to_string()),
+ ));
+ assert_eq!(
+ (failed.status, failed.code),
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ CalendarMutationErrorCode::MacroCallFailed
+ )
+ );
+ assert!(!failed.message.contains("10.0.0.9"));
+
+ let invalid = CalendarMutationApiError::from(CreateEventWithMacroCallError::MeetingLink(
+ MeetingLinkError::InvalidInput("title too long".to_string()),
+ ));
+ assert_eq!(
+ (invalid.status, invalid.code),
+ (
+ StatusCode::BAD_REQUEST,
+ CalendarMutationErrorCode::InvalidInput
+ )
+ );
+ assert_eq!(invalid.message, "title too long");
+
+ let calendar = CalendarMutationApiError::from(CreateEventWithMacroCallError::Calendar(
+ CalendarMutationError::ReadOnly,
+ ));
+ assert_eq!(
+ (calendar.status, calendar.code),
+ (StatusCode::FORBIDDEN, CalendarMutationErrorCode::ReadOnly)
+ );
+}
+
+#[test]
+fn create_requests_carry_no_macro_call_unless_asked() {
+ let time = serde_json::to_value(EventTime::AllDay {
+ start_date: chrono::NaiveDate::from_ymd_opt(2026, 10, 6).unwrap(),
+ end_date: chrono::NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
+ })
+ .unwrap();
+ let request: CreateCalendarEventRequest =
+ serde_json::from_value(serde_json::json!({ "title": "Lunch", "time": time })).unwrap();
+ assert!(!request.macro_call);
+
+ let request: CreateCalendarEventRequest = serde_json::from_value(
+ serde_json::json!({ "title": "Lunch", "time": time, "macroCall": true }),
+ )
+ .unwrap();
+ assert!(request.macro_call);
+}
diff --git a/crates/calendar_events/src/outbound/calendar_service_mutations.rs b/crates/calendar_events/src/outbound/calendar_service_mutations.rs
index 9421765df4..a1549cf9dd 100644
--- a/crates/calendar_events/src/outbound/calendar_service_mutations.rs
+++ b/crates/calendar_events/src/outbound/calendar_service_mutations.rs
@@ -20,13 +20,14 @@ use serde::Deserialize;
use uuid::Uuid;
use crate::domain::{
+ meeting_links::{CreateEventWithMacroCallError, MeetingLinkError},
models::{
AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch,
VisibleCalendar,
},
ports::{
- CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
- CalendarUpdateScope,
+ CalendarDeletionScope, CalendarMacroCallService, CalendarMutationError,
+ CalendarMutationService, CalendarRsvpScope, CalendarUpdateScope,
},
};
@@ -68,12 +69,14 @@ impl CalendarServiceMutations {
.header(INTERNAL_MACRO_USER_ID_HEADER, requester_id)
}
- async fn send(
+ /// Send the request, keeping an error response's status and body for
+ /// the caller to classify.
+ async fn send_raw(
&self,
request: reqwest::RequestBuilder,
- ) -> Result<reqwest::Response, CalendarMutationError> {
+ ) -> Result<reqwest::Response, ResponseFailure> {
let response = request.send().await.map_err(|error| {
- CalendarMutationError::Retryable(format!(
+ ResponseFailure::Transport(format!(
"calendar mutation request failed to reach the calendar service: {error}"
))
})?;
@@ -81,23 +84,44 @@ impl CalendarServiceMutations {
if status.is_success() {
return Ok(response);
}
- Err(error_from_response(status, response.text().await.ok()))
+ Err(ResponseFailure::Status(status, response.text().await.ok()))
}
- async fn event_from(
+ async fn send(
&self,
request: reqwest::RequestBuilder,
- ) -> Result<CalendarEvent, CalendarMutationError> {
- self.send(request)
- .await?
- .json::<CalendarEvent>()
+ ) -> Result<reqwest::Response, CalendarMutationError> {
+ self.send_raw(request)
.await
- .map_err(|error| {
- CalendarMutationError::PersistFailed(format!(
- "calendar mutation succeeded but its echo could not be parsed: {error}"
- ))
+ .map_err(|failure| match failure {
+ ResponseFailure::Transport(message) => CalendarMutationError::Retryable(message),
+ ResponseFailure::Status(status, body) => error_from_response(status, body),
})
}
+
+ async fn event_from(
+ &self,
+ request: reqwest::RequestBuilder,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ parse_event(self.send(request).await?).await
+ }
+}
+
+/// A request that produced no successful response.
+enum ResponseFailure {
+ /// The calendar service could not be reached.
+ Transport(String),
+ /// The calendar service answered with an error status and body.
+ Status(StatusCode, Option<String>),
+}
+
+/// Parse the event echo of a successful mutation response.
+async fn parse_event(response: reqwest::Response) -> Result<CalendarEvent, CalendarMutationError> {
+ response.json::<CalendarEvent>().await.map_err(|error| {
+ CalendarMutationError::PersistFailed(format!(
+ "calendar mutation succeeded but its echo could not be parsed: {error}"
+ ))
+ })
}
/// Wire body for the calendars listing.
@@ -157,11 +181,30 @@ fn fallback_error(status: StatusCode, message: String) -> CalendarMutationError
}
}
+/// Map an error response of a create carrying a Macro call. The calendar
+/// service reports a meeting it could not mint under its own code; every
+/// other failure is the calendar write's.
+fn macro_call_error_from_response(
+ status: StatusCode,
+ body: Option<String>,
+) -> CreateEventWithMacroCallError {
+ let parsed = body
+ .as_deref()
+ .and_then(|body| serde_json::from_str::<MutationErrorWire>(body).ok());
+ match parsed {
+ Some(error) if error.code == "macro_call_failed" => {
+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::Failed(error.message))
+ }
+ _ => CreateEventWithMacroCallError::Calendar(error_from_response(status, body)),
+ }
+}
+
/// Wire body for event creation, matching `CreateCalendarEventRequest`.
fn create_body(
email_link_id: Option<Uuid>,
calendar_id: Option<Uuid>,
draft: &CalendarEventDraft,
+ macro_call: bool,
) -> serde_json::Value {
serde_json::json!({
"emailLinkId": email_link_id,
@@ -178,6 +221,7 @@ fn create_body(
"conference": draft.conference,
"outOfOffice": draft.out_of_office,
"idempotencyKey": draft.idempotency_key,
+ "macroCall": macro_call,
})
}
@@ -274,6 +318,33 @@ fn rsvp_body(
}
}
+impl CalendarMacroCallService for CalendarServiceMutations {
+ #[tracing::instrument(skip(self, requester_id, draft), err)]
+ async fn create_event_with_macro_call(
+ &self,
+ requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> Result<CalendarEvent, CreateEventWithMacroCallError> {
+ let response = self
+ .send_raw(
+ self.request(reqwest::Method::POST, "/events", requester_id)
+ .json(&create_body(email_link_id, calendar_id, &draft, true)),
+ )
+ .await
+ .map_err(|failure| match failure {
+ ResponseFailure::Transport(message) => {
+ CalendarMutationError::Retryable(message).into()
+ }
+ ResponseFailure::Status(status, body) => {
+ macro_call_error_from_response(status, body)
+ }
+ })?;
+ parse_event(response).await.map_err(Into::into)
+ }
+}
+
impl CalendarMutationService for CalendarServiceMutations {
#[tracing::instrument(skip(self, requester_id, draft), err)]
async fn create_event(
@@ -285,7 +356,7 @@ impl CalendarMutationService for CalendarServiceMutations {
) -> Result<CalendarEvent, CalendarMutationError> {
self.event_from(
self.request(reqwest::Method::POST, "/events", requester_id)
- .json(&create_body(email_link_id, calendar_id, &draft)),
+ .json(&create_body(email_link_id, calendar_id, &draft, false)),
)
.await
}
diff --git a/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs b/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
index a36687f8e1..e81787164e 100644
--- a/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
+++ b/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
@@ -44,7 +44,7 @@ fn sample_draft() -> CalendarEventDraft {
#[test]
fn create_body_matches_the_router_request() {
let calendar_id = Some(Uuid::from_u128(3));
- let body = create_body(None, calendar_id, &sample_draft());
+ let body = create_body(None, calendar_id, &sample_draft(), false);
let request: CreateCalendarEventRequest = serde_json::from_value(body).unwrap();
assert_eq!(request.calendar_id, calendar_id);
@@ -71,7 +71,7 @@ fn out_of_office_survives_the_create_wire_contract() {
decline_message: Some("Away".to_string()),
});
let request: CreateCalendarEventRequest =
- serde_json::from_value(create_body(None, None, &draft)).unwrap();
+ serde_json::from_value(create_body(None, None, &draft, false)).unwrap();
let out_of_office = request
.out_of_office
@@ -254,3 +254,40 @@ fn unrecognized_failures_are_classified_by_status() {
);
assert!(matches!(parsed, CalendarMutationError::Retryable(_)));
}
+
+#[test]
+fn create_body_asks_for_a_macro_call_only_when_requested() {
+ let request: CreateCalendarEventRequest =
+ serde_json::from_value(create_body(None, None, &sample_draft(), true)).unwrap();
+ assert!(request.macro_call);
+ let request: CreateCalendarEventRequest =
+ serde_json::from_value(create_body(None, None, &sample_draft(), false)).unwrap();
+ assert!(!request.macro_call);
+}
+
+#[test]
+fn macro_call_failures_round_trip_to_the_meeting_link_error() {
+ let api_error = CalendarMutationApiError::from(CreateEventWithMacroCallError::MeetingLink(
+ MeetingLinkError::Failed("down".to_string()),
+ ));
+ let body = serde_json::to_string(&api_error).unwrap();
+ let parsed = macro_call_error_from_response(StatusCode::SERVICE_UNAVAILABLE, Some(body));
+ assert!(matches!(
+ parsed,
+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::Failed(_))
+ ));
+
+ let api_error = CalendarMutationApiError::from(CalendarMutationError::NoWritableCalendar);
+ let body = serde_json::to_string(&api_error).unwrap();
+ let parsed = macro_call_error_from_response(StatusCode::CONFLICT, Some(body));
+ assert!(matches!(
+ parsed,
+ CreateEventWithMacroCallError::Calendar(CalendarMutationError::NoWritableCalendar)
+ ));
+
+ let parsed = macro_call_error_from_response(StatusCode::SERVICE_UNAVAILABLE, None);
+ assert!(matches!(
+ parsed,
+ CreateEventWithMacroCallError::Calendar(CalendarMutationError::Retryable(_))
+ ));
+}
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index a5170f6784..3dfdb2ebca 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,5 +1,5 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function VO($,O,x){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let j=Array($.length),S=0,K=async()=>{while(S<$.length){let Z=S;S+=1,j[Z]=await x($[Z])}},G=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(G),j}class M${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*s($){let O;do{let x=await $(O),j=x.nextCursor??void 0;if(O!==void 0&&j!==void 0&&JSON.stringify(j)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*x.items,O=j}while(O!==void 0)}class w extends Error{constructor($){super($);this.name="MacroError"}}class a$ extends w{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class m extends w{constructor($){super($);this.name="MacroNotFoundError"}}function V($){if($.error!==void 0)throw new a$($.response?.status??0,$.error);return $.data}class q{client;id;detail;constructor($,O,x){this.client=$;this.id=O;this.detail=new M$(()=>this.fetch(),x)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=V(await $(this.client));return this.detail.clear(),O}}class N$ extends q{async favorite(){return V(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return V(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class x$ extends N${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=V(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){V(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return V(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}))}}))}async deleteProperty($){V(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function b$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function kS($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var yS={toMention:()=>({tag:b$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function hS($,...O){let x="",j=[];for(let[S,K]of $.entries()){x+=K;let G=O[S];if(G===void 0)continue;if(kS(G)){let Z=G.toMention();x+=Z.tag,j.push(Z.mention)}else x+=String(G)}return{content:x,mentions:vS(j)}}function vS($){let O=new Set;return $.filter((x)=>{let j=`${x.entity_type}:${x.entity_id}`;if(O.has(j))return!1;return O.add(j),!0})}function e($){return typeof $==="string"?{content:$,mentions:[]}:$}var mS=50;function o($){let{filters:O,type:x,make:j,includeCrm:S}=$;return(K,G,Z)=>{let X=Z?.searchOn??"name_content",L=Z?.pageSize??mS;return s(async(Y)=>{let{results:Q,next_cursor:T}=V(await K.search.unifiedSearch({body:{query:G,match_type:"partial",search_on:X,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===x).map((W)=>j(K,W)),nextCursor:T}})}}async function FO($,O,x){let{channelId:j,thread:S}=cS(O);if(await dS($)){let{id:G}=V(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:j},body:{content:x.content,mentions:x.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return G}if(S)throw new w("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=V(await $.storage.postChannelBotWebhook({path:{channel_id:j},body:{content:x.content},headers:{"x-macro-bot-scope":"user"}}));return K}function cS($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function dS($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class P${client;channelId;rootId;constructor($,O,x){this.client=$;this.channelId=O;this.rootId=x}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return j$.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=V(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>j$.from(this.client,this.channelId,O))}async reply($){let O=await FO(this.client,this,e($));return j$.byId(this.client,this.channelId,O)}}class j$ extends N${channelId;mentions;entityType="channel_message";constructor($,O,x,j=[],S){super($,x,S);this.channelId=O;this.mentions=j}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x,j=[]){return new j$($,O,x,j)}static from($,O,x){return new j$($,O,x.id,x.mentions,x)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new P$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class f extends x${entityType="channel";propertyEntityType="CHANNEL";async fetch(){return V(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:x}=V(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,x)}static async private($,O){let{channel_id:x}=V(await $.storage.getOrCreatePrivate({body:{recipients:O.map((j)=>j.id)}}));return new f($,x)}static async create($,O){let{id:x}=V(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((j)=>j.id),team_id:O.team?.id??null}}));return new f($,x)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let x=await FO(this.client,O?.thread??this,e($));return j$.byId(this.client,this.id,x)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return s(async(O)=>{let x=V(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:x.items.map((j)=>j$.from(this.client,this.id,j)),nextCursor:x.next_cursor}})}message($){return j$.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=V(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return V(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((x)=>x.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((x)=>x.id)}}))}async typing($,O){V(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return s(async(O)=>{let x=V(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:x.items,nextCursor:x.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=o({type:"channel",make:($,O)=>new f($,O.channel_id)})}class M extends x${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=V(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=V(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:b$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class Z$ extends q{parent;constructor($,O,x,j){super($,x,j);this.parent=O}static byId($,O,x){return new Z$($,O,x)}static fromRecord($,O,x){return new Z$($,O,x.id,x)}static async create($,O,x){return Z$.createForSession($,O.session(),x,O)}static async createForSession($,O,x,j){let S=V(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...x,executionId:j?.id??null}}));return Z$.fromRecord($,O,S)}static async list($,O){return V(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((j)=>Z$.fromRecord($,O.session(),j))}async fetch(){return V(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((x)=>x.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class WO extends q{parent;constructor($,O,x){super($,O);this.parent=x}static byId($,O,x){return new WO($,x,O)}async fetch(){return V(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>Z$.create(this.client,this,$),list:()=>Z$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class EO{client;sessionId;dto;constructor($,O,x){this.client=$;this.sessionId=O;this.dto=x}static from($,O,x){return new EO($,O,x)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return V(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){V(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){V(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class $$ extends q{static byId($,O){return new $$($,O)}static async createManaged($,O){let{session:x}=V(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new $$($,x.id,x)}static async repositories($){let{repositories:O}=V(await $.agentHarness.listAgentRepositories());return O.map((x)=>({url:x.url,defaultBranch:x.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:x}=V(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return x}async fetch(){return V(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:x}=V(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return x.map((j)=>$$.byId($,j))}async pullRequests(){let{pullRequests:$}=V(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){V(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){V(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((x)=>x.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return V(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return V(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return V(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return V(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=V(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>EO.from(this.client,this.id,O))}async changes(){return V(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return V(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async log(){return V(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>Z$.createForSession(this.client,this,$),byId:($)=>Z$.byId(this.client,this,$)};codeExecutions={byId:($)=>WO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class vx{client;constructor($){this.client=$}byId($){return $$.byId(this.client,$)}createManaged($){return $$.createManaged(this.client,$)}repositories(){return $$.repositories(this.client)}repositoryBranches($){return $$.repositoryBranches(this.client,$)}forPullRequest($){return $$.forPullRequest(this.client,$)}defaultSandboxSize(){return $$.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return $$.setDefaultSandboxSize(this.client,$)}codingPreferences(){return $$.codingPreferences(this.client)}setCodingPreferences($){return $$.setCodingPreferences(this.client,$)}}class mx{client;constructor($){this.client=$}async structuredCompletion($){return V(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return V(await this.client.cognition.decisions({body:$}))}}class BO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new w("bots.me() requires bot auth — a user API key has no bot identity");return V(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new w("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return V(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new w("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class X$ extends q{async fetch(){let{links:$}=V(await this.client.email.listLinks()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`email link ${this.id} not found`);return O}static byId($,O){return new X$($,O)}static async list($){let{links:O}=V(await $.email.listLinks());return O.map((x)=>new X$($,x.id,x))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url")}class g$ extends q{async fetch(){let{calendars:$}=V(await this.client.calendar.listCalendars()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`calendar ${this.id} not found`);return O}static byId($,O){return new g$($,O)}static async list($){let{calendars:O}=V(await $.calendar.listCalendars());return O.map((x)=>new g$($,x.id,x))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>X$.byId(this.client,$))}class U$ extends q{async fetch(){throw new w(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new U$($,O)}static fromRecord($,O){return new U$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");calendar=this.mappedField("calendarId",($)=>$?g$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((x)=>x.calendar.updateCalendarEvent({path:{event_id:this.id},body:uS($)}));return U$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId}}))}async rsvp($){let O=await this.mutate((x)=>x.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return U$.fromRecord(this.client,O)}}function uS($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class cx{client;constructor($){this.client=$}calendars(){return g$.list(this.client)}calendar($){return g$.byId(this.client,$)}event($){return U$.byId(this.client,$)}async createEvent($){let O=V(await this.client.calendar.createCalendarEvent({body:lS($)}));return U$.fromRecord(this.client,O)}}function lS($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class k$ extends q{callId;constructor($,O,x,j){super($,x,j);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new k$($,O,x)}static from($,O,x){return new k$($,O,x.id,x)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=V(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...e($),thread_id:this.callId}}));return k$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class K$ extends N${entityType="call";async fetch(){return V(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return k$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=o({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class dx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class ux{client;constructor($){this.client=$}async list(){let{labels:$}=V(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return V(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((x)=>x.id)}}))}async createSmartTag($,O){return V(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return V(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,x){return V(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:x}}))}async rename($,O){return V(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){V(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){V(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class lx{client;labels;constructor($){this.client=$;this.labels=new ux($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=V(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:x}=V(await this.client.storage.getChannels()),j=$.toLowerCase();for(let S of x)if(S.name?.toLowerCase().includes(j))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class u extends x${entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=V(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new u($,O)}static async create($,O){let{data:x}=V(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new u($,x.id,x)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?u.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=V(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=o({filters:{project_filters:{}},type:"project",make:($,O)=>new u($,O.id)})}class V$ extends x${entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=V(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new V$($,O)}static async create($,O){let{id:x}=V(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new V$($,x)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?u.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new V$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=V(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=o({filters:{chat_filters:{}},type:"chat",make:($,O)=>new V$($,O.chat_id)});toMention(){return{tag:b$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class rx{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}search($,O){return V$.search(this.client,$,O)}}class z$ extends q{async fetch(){let O=V(await this.client.auth.getUserTeams()).find((x)=>x.id===this.id);if(!O)throw new m(`team ${this.id} not found`);return O}static byId($,O){return new z$($,O)}static async current($){let O=V(await $.auth.getTeam());if(!O)throw new m("caller has no current team");return new z$($,O.team.id,O.team)}static async list($){return V(await $.auth.getUserTeams()).map((x)=>new z$($,x.id,x))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=V(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new w("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}var rS=8;class _$ extends q{parent;constructor($,O,x,j){super($,x,j);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new _$($,O,x)}static from($,O,x){return new _$($,O,x.id,x)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return LO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function wO($,O){let x={parent_type:O.type,parent_id:O.id},j=s(async(K)=>{let G=V(await $.storage.messageTimeline({path:x,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:G.items,nextCursor:G.next_cursor}}),S=[];for await(let K of j)S.push(K);return VO(S,rS,async(K)=>{let{state:G,root:Z,replies:X}=V(await $.storage.entityMessageGetThread({path:{...x,id:K.id}}));return{thread:G,comments:[Z,...X].map((L)=>_$.from($,O,L))}})}async function LO($,O,x,j){let S=V(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...e(x),thread_id:j?.threadId??null}}));return _$.from($,O,S)}class I$ extends N${entityType="crm_contact";async fetch(){return V(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>T$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return wO(this.client,this.commentParent)}async comment($,O){return LO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class T$ extends x${entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return V(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>z$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return V(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>I$.from(this.client,O))}static search=o({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new T$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((x)=>x.storage.createCrmContact({path:{company_id:this.id},body:$}));return I$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return wO(this.client,this.commentParent)}async comment($,O){return LO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class px{client;constructor($){this.client=$}companyById($){return T$.byId(this.client,$)}contactById($){return I$.byId(this.client,$)}async contactByEmail($){let{contact:O}=V(await this.client.storage.getContactByEmail({query:{email:$}}));return O?I$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:x}=V(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return x.map((j)=>I$.from(this.client,j))}async createCompany($){return T$.from(this.client,V(await this.client.storage.createCrmCompany({body:$})))}async settings(){return V(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return V(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return V(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){V(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return T$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),J0=Symbol.for("@ts-pattern/isVariadic");var ax=($)=>Boolean($&&typeof $=="object"),qO=($)=>$&&!!$[G$],l=($,O,x)=>{if(qO($)){let j=$[G$](),{matched:S,selections:K}=j.match(O);return S&&K&&Object.keys(K).forEach((G)=>x(G,K[G])),S}if(ax($)){if(!ax(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let j=[],S=[],K=[];for(let G of $.keys()){let Z=$[G];qO(Z)&&Z[J0]?K.push(Z):K.length?S.push(Z):j.push(Z)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<j.length+S.length)return!1;let G=O.slice(0,j.length),Z=S.length===0?[]:O.slice(-S.length),X=O.slice(j.length,S.length===0?1/0:-S.length);return j.every((L,Y)=>l(L,G[Y],x))&&S.every((L,Y)=>l(L,Z[Y],x))&&(K.length===0||l(K[0],X,x))}return $.length===O.length&&$.every((G,Z)=>l(G,O[Z],x))}return Reflect.ownKeys($).every((j)=>{let S=$[j];return((j in O)||qO(K=S)&&K[G$]().matcherType==="optional")&&l(S,O[j],x);var K})}return Object.is(O,$)},S$=($)=>{var O,x,j;return ax($)?qO($)?(O=(x=(j=$[G$]()).getSelectionKeys)==null?void 0:x.call(j))!=null?O:[]:Array.isArray($)?NO($,S$):NO(Object.values($),S$):[]},NO=($,O)=>$.reduce((x,j)=>x.concat(O(j)),[]);function pS(...$){if($.length===1){let[O]=$;return(x)=>l(O,x,()=>{})}if($.length===2){let[O,x]=$;return l(O,x,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function n($){return Object.assign($,{optional:()=>sx($),and:(O)=>c($,O),or:(O)=>V0($,O),select:(O)=>O===void 0?UO($):UO(O,$)})}function ix($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let x=0,j=[{value:Object.assign(O,{[J0]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=j[x++])!=null?S:j.at(-1)}}}}))($),{optional:()=>ix(sx($)),select:(O)=>ix(O===void 0?UO($):UO(O,$))})}function sx($){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return O===void 0?(S$($).forEach((S)=>j(S,void 0)),{matched:!0,selections:x}):{matched:l($,O,j),selections:x}},getSelectionKeys:()=>S$($),matcherType:"optional"})})}var aS=($,O)=>{for(let x of $)if(!O(x))return!1;return!0},iS=($,O)=>{for(let[x,j]of $.entries())if(!O(j,x))return!1;return!0},nS=($,O)=>{let x=Reflect.ownKeys($);for(let j of x)if(!O(j,$[j]))return!1;return!0};function c(...$){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return{matched:$.every((S)=>l(S,O,j)),selections:x}},getSelectionKeys:()=>NO($,S$),matcherType:"and"})})}function V0(...$){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return NO($,S$).forEach((S)=>j(S,void 0)),{matched:$.some((S)=>l(S,O,j)),selections:x}},getSelectionKeys:()=>NO($,S$),matcherType:"or"})})}function b($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function UO(...$){let O=typeof $[0]=="string"?$[0]:void 0,x=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return n({[G$]:()=>({match:(j)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:j};return{matched:x===void 0||l(x,j,(K,G)=>{S[K]=G}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(x===void 0?[]:S$(x))})})}function W0($){return!0}function H$($){return typeof $=="number"}function y$($){return typeof $=="string"}function h$($){return typeof $=="bigint"}var B0=n(b(W0)),sS=n(b(W0)),eS=B0,v$=($)=>Object.assign(n($),{startsWith:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.startsWith(x)))));var x},endsWith:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.endsWith(x)))));var x},minLength:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length>=x))(O))),length:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length===x))(O))),maxLength:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length<=x))(O))),includes:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.includes(x)))));var x},regex:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&Boolean(j.match(x))))));var x}}),Q0=v$(b(y$)),R$=($)=>Object.assign(n($),{between:(O,x)=>R$(c($,((j,S)=>b((K)=>H$(K)&&j<=K&&S>=K))(O,x))),lt:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j<x))(O))),gt:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j>x))(O))),lte:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j<=x))(O))),gte:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j>=x))(O))),int:()=>R$(c($,b((O)=>H$(O)&&Number.isInteger(O)))),finite:()=>R$(c($,b((O)=>H$(O)&&Number.isFinite(O)))),positive:()=>R$(c($,b((O)=>H$(O)&&O>0))),negative:()=>R$(c($,b((O)=>H$(O)&&O<0)))}),tS=R$(b(H$)),m$=($)=>Object.assign(n($),{between:(O,x)=>m$(c($,((j,S)=>b((K)=>h$(K)&&j<=K&&S>=K))(O,x))),lt:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j<x))(O))),gt:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j>x))(O))),lte:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j<=x))(O))),gte:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j>=x))(O))),positive:()=>m$(c($,b((O)=>h$(O)&&O>0))),negative:()=>m$(c($,b((O)=>h$(O)&&O<0)))}),oS=m$(b(h$)),$2=n(b(function($){return typeof $=="boolean"})),O2=n(b(function($){return typeof $=="symbol"})),x2=n(b(function($){return $==null})),j2=n(b(function($){return $!=null})),O$={__proto__:null,matcher:G$,optional:sx,array:function(...$){return ix({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let x=$[0],j={};if(O.length===0)return S$(x).forEach((K)=>{j[K]=[]}),{matched:!0,selections:j};let S=(K,G)=>{j[K]=(j[K]||[]).concat([G])};return{matched:O.every((K)=>l(x,K,S)),selections:j}},getSelectionKeys:()=>$.length===0?[]:S$($[0])})})},set:function(...$){return n({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let x={};if(O.size===0)return{matched:!0,selections:x};if($.length===0)return{matched:!0};let j=(K,G)=>{x[K]=(x[K]||[]).concat([G])},S=$[0];return{matched:aS(O,(K)=>l(S,K,j)),selections:x}},getSelectionKeys:()=>$.length===0?[]:S$($[0])})})},map:function(...$){return n({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let x={};if(O.size===0)return{matched:!0,selections:x};let j=(Z,X)=>{x[Z]=(x[Z]||[]).concat([X])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,G]=$;return{matched:iS(O,(Z,X)=>{let L=l(K,X,j),Y=l(G,Z,j);return L&&Y}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...S$($[0]),...S$($[1])]})})},record:function(...$){return n({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var x;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(x=$[0])==null?void 0:x.toString()}`);let j={},S=(Z,X)=>{j[Z]=(j[Z]||[]).concat([X])},[K,G]=$.length===1?[Q0,$[0]]:$;return{matched:nS(O,(Z,X)=>{let L=typeof Z!="string"||Number.isNaN(Number(Z))?null:Number(Z),Y=L!==null&&l(K,L,S),Q=l(K,Z,S),T=l(G,X,S);return(Q||Y)&&T}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...S$($[0]),...S$($[1])]})})},intersection:c,union:V0,not:function($){return n({[G$]:()=>({match:(O)=>({matched:!l($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:b,select:UO,any:B0,unknown:sS,_:eS,string:Q0,number:tS,bigint:oS,boolean:$2,symbol:O2,nullish:x2,nonNullable:j2,instanceOf:function($){return n(b(function(O){return(x)=>x instanceof O}($)))},shape:function($){return n(b(pS($)))}};class L0 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(x){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var nx={matched:!1,value:void 0};function d($){return new fO($,nx)}class fO{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],x=[$[0]],j;$.length===3&&typeof $[1]=="function"?j=$[1]:$.length>2&&x.push(...$.slice(1,$.length-1));let S=!1,K={},G=(X,L)=>{S=!0,K[X]=L},Z=!x.some((X)=>l(X,this.input,G))||j&&!Boolean(j(this.input))?nx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new fO(this.input,Z)}when($,O){if(this.state.matched)return this;let x=Boolean($(this.input));return new fO(this.input,x?{matched:!0,value:O(this.input,this.input)}:nx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=S2){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function S2($){throw new L0($)}var ex,G2=new Uint8Array(16);function bO(){if(!ex){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ex=crypto.getRandomValues.bind(crypto)}return ex(G2)}var t=[];for(let $=0;$<256;++$)t.push(($+256).toString(16).slice(1));function N0($,O=0){return(t[$[O+0]]+t[$[O+1]]+t[$[O+2]]+t[$[O+3]]+"-"+t[$[O+4]]+t[$[O+5]]+"-"+t[$[O+6]]+t[$[O+7]]+"-"+t[$[O+8]]+t[$[O+9]]+"-"+t[$[O+10]]+t[$[O+11]]+t[$[O+12]]+t[$[O+13]]+t[$[O+14]]+t[$[O+15]]).toLowerCase()}var tx={};function Z2($,O,x){let j;if($)j=U0($.random??$.rng?.()??bO(),$.msecs,$.seq,O,x);else{let S=Date.now(),K=bO();X2(tx,S,K),j=U0(K,tx.msecs,tx.seq,O,x)}return O??N0(j)}function X2($,O,x){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=x[6]<<23|x[7]<<16|x[8]<<8|x[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function U0($,O,x,j,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!j)j=new Uint8Array(16),S=0;else if(S<0||S+16>j.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),x??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],j[S++]=O/1099511627776&255,j[S++]=O/4294967296&255,j[S++]=O/16777216&255,j[S++]=O/65536&255,j[S++]=O/256&255,j[S++]=O&255,j[S++]=112|x>>>28&15,j[S++]=x>>>20&255,j[S++]=128|x>>>14&63,j[S++]=x>>>6&255,j[S++]=x<<2&255|$[10]&3,j[S++]=$[11],j[S++]=$[12],j[S++]=$[13],j[S++]=$[14],j[S++]=$[15],j}var F$=Z2;class E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((x)=>x.column.id===this.id);if(!O)throw new m(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class c${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new c$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class gO{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new gO($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((x)=>x.table.id===this.id);if(!O)throw new m(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>E$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return c$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>gO.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}class kO{table;id;createdBy;record;constructor($,O,x,j){this.table=$;this.id=O;this.createdBy=x;this.record=j}static fromRecord($,O,x){return new kO($,x.id,O,x)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Oj extends a${op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function yO($){return d($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:O$.not("relation")},(O)=>O).exhaustive()}var K2={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function Y2($){return d($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>K2[O]).with({type:"relation"},()=>"Relation").exhaustive()}function ox($){return $.map((O)=>({id:F$(),label:O}))}function z0($,O,x){return $?.kind===O&&"change"in $&&$.change.kind===x}function $j($){return d($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:O$.union("table","column","rows","view")},({kind:O,change:x})=>`${O}.${x.kind}`).exhaustive()}function w$($,O,x){let[j]=$;if($.length!==1||!z0(j,O,x))throw new w(`expected one ${O}.${x} result, got ${$.map($j).join(", ")||"none"}`);return j}class Q$ extends q{async fetch(){return V(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new w(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let x=V(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,x.id)}static async list($){return V(await $.storage.listDatabases()).map((x)=>new Q$($,x.database.id))}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),x=O.find((j)=>j.table.name===$);return x?Y$.byId(this,x.table.id):void 0}async createTable($){let{table:O}=w$(await this.applyOps([{kind:"table",table:F$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.byId(this,O)}async applyOps($,O={}){let x={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);x.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:j}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:x});if(K.error!==void 0&&"op"in K.error)throw new Oj(K.response?.status??0,K.error);return K});return j}async reorderTables($){for(let j of $)this.assertOwns(`table ${j.id}`,j.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((j)=>j.id)}]),[x]=O;if(O.length!==1||x?.kind!=="reorder_tables")throw new w(`expected one reorder_tables result, got ${O.map($j).join(", ")||"none"}`);return x.tables.map(({table:j})=>Y$.byId(this,j))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),V(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=V(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=V(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((x)=>x.storage.importDatabaseTable({path:{id:this.id},body:$}));return Y$.byId(this,O.id)}webhookOf($){return kO.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=V(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=V(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),V(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return V(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let x=await $.table.version();return w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:yO(O.to)}}],{baseVersions:[{table:$.table,version:x}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),V(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:yO(O)}}))}async convertColumnIntoNewColumn($,O){let x=await this.columnConversion($,O.to),j=O.name??`${await $.name()} (${Y2(O.to)})`,S=F$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:j,type:yO(O.to),options:ox(x.options)},after:$.id}}];if(x.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:x.cells.map(({row:Z,value:X})=>({row:Z,cells:[{column:S,value:X}]}))}}});let[G]=await this.applyOps(K,{baseVersions:[{table:$.table,version:x.tableVersion}]});if(!z0(G,"column","created"))throw new w(`expected a column.created result, got ${G?$j(G):"none"}`);return E$.byId($.table,G.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:x}=w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return x}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new w(`column ${S.id} does not belong to table ${$.id}`);let x=await $.version(),{tableVersion:j}=w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:x}]}),"table","columns_reordered");if(j===void 0)throw new w(`table ${$.id} reordered its columns without a version`);return j}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let x=await $.name(),{tableVersion:j}=w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:x}}]),"table","renamed");if(j===void 0)throw new w(`table ${$.id} was renamed without a version`);return j}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let x=await $.name(),{tableVersion:j}=w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:x}}]),"column","renamed");return j}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((x)=>x.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new w(`column ${O.after.id} does not belong to table ${$.id}`);let x="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:yO(O.type),...O.options!==void 0?{options:ox(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:j}=w$(await this.applyOps([{kind:"column",table:$.id,column:F$(),change:{kind:"create",definition:x,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return E$.byId($,j)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:ox(O)}}]),"column","options_added")}}class xj{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class d$ extends q{documentId;constructor($,O,x,j){super($,x,j);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new d$($,O,x)}static from($,O,x){return new d$($,O,x.id,x)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return E.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}var Q2=8;class E extends x${async fetch(){let{data:$}=V(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new E($,O)}static async create($,O){let{documentId:x}=V(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static async createSnippet($,O){let{documentId:x}=V(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static async createSkill($,O){let{documentId:x}=V(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static recent($,O){let x=O?.pageSize??50;return s(async(j)=>{let S=V(await $.storage.getUserDocumentsHandler({query:{limit:x,offset:j?Number(j):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((G)=>new E($,G.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=V(await $.storage.recentlyDeleted({}));return O.items.filter((x)=>x.type==="document").map((x)=>new E($,x.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?u.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?E.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=V(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=V(await this.client.storage.exportDocument({path:{document_id:this.id}})),x=await fetch(O);if(!x.ok)throw new a$(x.status,{message:"failed to download document content"});return x.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=V(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new E(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=s(async(j)=>{let S=V(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:j})}}));return{items:S.items,nextCursor:S.next_cursor}}),x=[];for await(let j of O)x.push(j);return VO(x,Q2,async(j)=>{let{state:S,root:K,replies:G}=V(await this.client.storage.entityMessageGetThread({path:{...$,id:j.id}}));return{thread:S,comments:[K,...G].map((Z)=>d$.from(this.client,this.id,Z))}})}async comment($,O){let x=await this.mutate((j)=>j.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...e($),thread_id:O?.threadId??null}}));return d$.from(this.client,this.id,x)}async shortId(){return V(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return V(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=V(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=V(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=o({filters:{document_filters:{}},type:"document",make:($,O)=>new E($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:b$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class hO{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=V(await $.storage.getSystemSkillsHandler());return O.map((x)=>new hO(x.id,x.name))}}class jj{client;constructor($){this.client=$}byId($){return E.byId(this.client,$)}create($){return E.create(this.client,$)}createSnippet($){return E.createSnippet(this.client,$)}createSkill($){return E.createSkill(this.client,$)}systemSkills(){return hO.list(this.client)}search($,O){return E.search(this.client,$,O)}recent($){return E.recent(this.client,$)}recentlyDeleted(){return E.recentlyDeleted(this.client)}}class i$ extends q{async fetch(){let{attachment:$}=V(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=V(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return E.byId(this.client,$)}}class u$ extends q{async fetch(){let{labels:$}=V(await this.client.email.listLabels()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`label ${this.id} not found`);return O}static byId($,O){return new u$($,O)}static async list($){let{labels:O}=V(await $.email.listLabels());return O.map((x)=>new u$($,x.id,x))}static async create($,O){let{label:x}=V(await $.email.createLabel({body:{label_name:O}}));if(!x.id)throw new w("created label has no id");return new u$($,x.id)}async delete(){V(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class W$ extends x${entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=V(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new W$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>X$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?u.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let x of $)for(let j of[x.from,...x.to,...x.cc,...x.bcc])if(j&&!O.has(j.email))O.set(j.email,j);return[...O.values()]}async messages($){return V(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((x)=>A$.from(this.client,x))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((x)=>i$.from(this.client,x)))}async reply($){let O=$.subject??await this.subject()??"",{message:x}=await this.mutate((j)=>j.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return x.db_id?A$.byId(this.client,x.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=o({filters:{email_filters:{}},type:"email",make:($,O)=>new W$($,O.thread_id)})}class A$ extends q{async fetch(){return V(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new A$($,O)}static from($,O){return new A$($,O.db_id,O)}static async send($,O){let{message:x}=V(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return x.db_id?A$.byId($,x.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>X$.byId(this.client,$));async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return W$.byId(this.client,(await this.detail.get()).thread_db_id)}}class Sj{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}message($){return A$.byId(this.client,$)}attachment($){return i$.byId(this.client,$)}link($){return X$.byId(this.client,$)}links(){return X$.list(this.client)}send($){return A$.send(this.client,$)}search($,O){return W$.search(this.client,$,O)}inbox($){return s(async(O)=>{let x=V(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:x.items.map((j)=>W$.byId(this.client,j.id)),nextCursor:x.next_cursor}})}label($){return u$.byId(this.client,$)}labels(){return u$.list(this.client)}createLabel($){return u$.create(this.client,$)}async deleteLabel($){V(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){V(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){V(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return V(await this.client.email.listBlockedSenders()).blocked_emails}}class Gj{client;constructor($){this.client=$}async list($={}){let{favorites:O}=V(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return V(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){V(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){V(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class l$ extends N${entityType="foreign_entity";async fetch(){return V(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new l$($,O)}static fromRecord($,O){return new l$($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function I0({login:$,...O}){return{...O,login:$??void 0}}class Zj{client;constructor($){this.client=$}byId($){return l$.byId(this.client,$)}async bySource($,O){return l$.fromRecord(this.client,V(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:x,labels:j}=V(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(I0),assignees:x.map(I0),labels:j.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class q${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new q$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((x)=>x.kind==="questions"?x.questions:[]).find((x)=>x.id===this.id);if(!O)throw new m(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return E$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>n$.byId(this,$.id))}}class n${question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new n$($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new m(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class e${form;id;detail;constructor($,O,x){this.form=$;this.id=O;this.detail=new M$(()=>this.load(),x)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new m(`response ${this.id} is not your current response`);return $}static byId($,O,x){return new e$($,O,x)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new M$(()=>this.load(),$),this}}class f${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new f$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new m(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>q$.byId(this.form,O.id)):[]}}class vO{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new vO($,O)}}class C$ extends q{async fetch(){return V(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new C$($,O)}static async create($,O){let x=V(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new C$($,x.form.id,x)}static async list($,O){if(!O)return V(await $.storage.listAccessibleForms()).map(({form:S})=>new C$($,S.id));return V(await $.storage.listForms({query:{databaseId:O.id}})).map((j)=>new C$($,j.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>f$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>q$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new w(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),x=(G)=>{if(G.table.id!==O.id||G.table.database.id!==O.database.id)throw new w(`column does not belong to form ${this.id}'s table`);return G.id},j=(G)=>({conjunction:G.conjunction,conditions:G.conditions.map((Z)=>d(Z).with({kind:"group"},(X)=>({kind:"group",...j(X)})).with({kind:"condition"},(X)=>({kind:"condition",column:x(X.column),test:d(X.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:O$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((G)=>{if(G.section)this.assertOwns(G.section);let Z={id:G.section?.id??F$(),title:G.title,description:G.description??""};return d(G).with({kind:"booking"},(X)=>({...Z,kind:"booking",target:X.target})).with({kind:"gate"},(X)=>({...Z,kind:"gate",rules:j(X.rules),message:X.message})).with({kind:"questions"},(X)=>({...Z,kind:"questions",questions:X.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??F$(),column:x(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((G)=>G.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:x})=>{this.assertOwns(O);let j=d(x).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new w("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:G})=>({entityType:K,entityId:G.id}))})).with({type:O$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:j}})}unlockedBooking($){return $?{...$,section:f$.byId(this,$.section)}:void 0}async outcome($,O){return d($).with({outcome:"stopped"},(x)=>({...x,section:f$.byId(this,x.section)})).with({outcome:"submitted"},async(x)=>{let j=c$.byId(await this.table(),x.row),S=this.unlockedBooking(x.booking);return{outcome:"submitted",response:e$.byId(this,x.response,{status:"submitted",row:j,answers:O,booking:S}),row:j,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(V(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(V(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=V(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),x=await Promise.all($.answers.map(async(K)=>{let G=q$.byId(this,K.question),Z=await d(K.value).with({type:"options"},(X)=>({type:"options",value:X.value.map((L)=>{if(!("id"in L))throw new w("stored form answers must reference options by id");return n$.byId(G,L.id)})})).with({type:"entities"},(X)=>({type:"entities",value:X.value.map((L)=>({entityType:L.entityType,entity:vO.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(X)=>{let L=await G.detail();if(L.kind.type!=="relation")throw new w("row answer requires a relation question");let Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:X.value.map((Q)=>c$.byId(Y,Q))}}).with({type:O$.union("text","number","boolean","date","link","clear")},(X)=>X).exhaustive();return{question:G,value:Z}})),j=$.response.row?c$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:e$.byId(this,$.response.id,{status:$.response.status,row:j,answers:x,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?f$.byId(this,$.response.stoppedAtSection):void 0,row:j,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:x}}async responseSummary(){let $=V(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:f$.byId(this,O.section),count:O.count}))}}async tally(){return V(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let x=q$.byId(this,O.question);return{question:x,responses:O.responses,buckets:O.buckets.map((j)=>({count:j.count,value:d(j.value).with({kind:"option"},(S)=>({kind:"option",option:n$.byId(x,S.option)})).with({kind:"checkbox"},(S)=>S).exhaustive()}))}})}async sharePermissions(){return V(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Xj{client;constructor($){this.client=$}byId($){return C$.byId(this.client,$)}create($){return C$.create(this.client,$)}list($){return C$.list(this.client,$)}}class s$ extends q{async fetch(){return V(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}static list($,O){return s(async(x)=>{let j=V(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...x?{cursor:x}:{}}}));return{items:j.items.map((S)=>s$.from($,S)),nextCursor:j.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Kj{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}list($){return s$.list(this.client,$)}async markSeen($){V(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){V(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){V(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return V(await this.client.notification.getNotificationTypePreferences())}async enableType($){V(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){V(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Yj{client;constructor($){this.client=$}async list(){let{data:$}=V(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){V(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){V(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){V(await this.client.storage.reorderPinsHandler({body:$}))}}class Qj{client;constructor($){this.client=$}byId($){return u.byId(this.client,$)}create($){return u.create(this.client,$)}search($,O){return u.search(this.client,$,O)}}class t${client;definitionId;id;record;constructor($,O,x,j){this.client=$;this.definitionId=O;this.id=x;this.record=j}static from($,O,x){return new t$($,O,x.id,x)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=V(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){V(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class r${client;id;detail;constructor($,O,x){this.client=$;this.id=O;this.detail=new M$(()=>this.fetch(),x)}async fetch(){return V(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let x=V(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new r$($,x.id,x)}static byId($,O){return new r$($,O)}static fromRecord($,O){return new r$($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return V(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return V(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>t$.from(this.client,this.id,O))}async addOption($){let O=V(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return t$.from(this.client,this.id,O)}async updateOption($,O){let x=V(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return t$.from(this.client,this.id,x)}async deleteOption($){return V(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Jj{client;constructor($){this.client=$}async list($){return V(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((x)=>{let j="definition"in x?x.definition:x;return r$.fromRecord(this.client,j)})}create($){return r$.create(this.client,$)}definition($){return r$.byId(this.client,$)}async bulkEntityProperties($){return V(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return V(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((j)=>j.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}})).results}async addEntityPropertyOption($){return V(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return V(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return V(await this.client.properties.listTags({}))}}var J2="00000001-0000-0000-0000-000000000002",V2="00000001-0000-0000-0002-000000000004";function W2($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class D$ extends E{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:x}=V(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,x)}static async forPullRequest($,O){let x=W2(O),{pullRequests:j}=V(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[x]}}));return(j[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let x=(await this.properties()).find((j)=>j.definition.id===J2)?.value;return x?.type==="SelectOption"&&x.value.includes(V2)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=o({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class Vj{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class Wj{client;constructor($){this.client=$}byId($){return z$.byId(this.client,$)}current(){return z$.current(this.client)}list(){return z$.list(this.client)}}class Bj{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class p$ extends q{signingSecret;constructor($,O,x,j){super($,O,x);this.signingSecret=j}async fetch(){return V(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let x=V(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new p$($,x.id,x,x.signing_secret)}static byId($,O){return new p$($,O)}static fromRecord($,O){return new p$($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class Lj{client;constructor($){this.client=$}create($){return p$.create(this.client,$)}byId($){return p$.byId(this.client,$)}async list(){let{webhooks:$}=V(await this.client.storage.listWebhooks());return $.map((O)=>p$.fromRecord(this.client,O))}}function Nj($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function T0($,O,x){let j=[];for(let S of Nj(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let G=x.get(K);if(G&&!j.some((Z)=>Z.label===G.label&&Z.scope===G.scope))j.push(G)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:E.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:V$.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:u.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:W$.byId($,O.data.id),snapshot:O,tags:j,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:j,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new P$($,O.data.channel_id,O.data.id),snapshot:O,tags:j,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:K$.byId($,O.data.callId),snapshot:O,tags:j,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:j,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:l$.byId($,O.data.id),snapshot:O,tags:j,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var H0="00000000-0000-0000-0000-000000000000",Uj={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},mO=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),R0=($,O)=>$==null?O:{"&":[$,O]};function zj($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let x=Object.entries($),j=x[0];if(x.length!==1||j===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=j;if(S==="l")return;if(S==="!"){zj(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((G,Z)=>{zj(G,`${O}.${S}[${Z}]`)})}class cO{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(V),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let x of O.options)if(x.value.type==="string")$.set(x.id,{label:x.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,G]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!G.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(Uj,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(Uj).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)zj($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:H0}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let x=$.inbox?.trim();if(x){let{links:S}=V(await this.client.email.listLinks()),K=S.filter((Z)=>mO(Z.email_address)===mO(x)),G=K[0];if(!G)throw Error(`No connected inbox matches "${x}". Connected inboxes: ${S.map((Z)=>Z.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${x}"; cannot pick one.`);O.ef=R0(O.ef,{l:{Owner:G.id}})}let j=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(j?.length){for(let[S,[K,G]]of Object.entries(Uj))if(!j.includes(S))O[K]={l:{[G]:H0}}}if($.tags?.length){let S=(await this.sets()).flatMap((X)=>{let L=X.definition;if(!L)return[];return X.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:X.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let X of $.tags){let L=S.filter((Y)=>mO(Y.label)===mO(X.label.trim())&&(!X.scope||Y.scope===X.scope));if(!L.length)throw Error(`Unknown tag "${X.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${X.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let Z=[...K.values()].map((X)=>({l:{pd:X.definitionId,v:{so:X.id}}})).reduce((X,L)=>X===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[X,L]},void 0);O.propf=R0(O.propf,Z)}return O}}class Ij{client;constructor($){this.client=$}async page($={}){let O=new cO(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new cO(this.client),x=await O.body($);yield*s((j)=>this.fetch(O,x,j))}async fetch($,O,x){let j=V(await this.client.storage.postItemsSoupAst({body:O,query:x?{cursor:x}:void 0})),K=j.items.some((G)=>Nj(G).some((Z)=>Z.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:j.items.map((G)=>T0(this.client,G,K)),nextCursor:j.next_cursor,hasMore:j.next_cursor!=null}}}function A0({onRequest:$,onSseError:O,onSseEvent:x,responseTransformer:j,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:G,sseMaxRetryDelay:Z,sseSleepFn:X,url:L,...Y}){let Q,T=X??((J)=>new Promise((B)=>setTimeout(B,J)));return{stream:async function*(){let J=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let A={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,A);if($)C=await $(L,A);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function VO($,O,x){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let j=Array($.length),S=0,K=async()=>{while(S<$.length){let Z=S;S+=1,j[Z]=await x($[Z])}},G=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(G),j}class M${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*s($){let O;do{let x=await $(O),j=x.nextCursor??void 0;if(O!==void 0&&j!==void 0&&JSON.stringify(j)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*x.items,O=j}while(O!==void 0)}class w extends Error{constructor($){super($);this.name="MacroError"}}class a$ extends w{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class m extends w{constructor($){super($);this.name="MacroNotFoundError"}}function V($){if($.error!==void 0)throw new a$($.response?.status??0,$.error);return $.data}class q{client;id;detail;constructor($,O,x){this.client=$;this.id=O;this.detail=new M$(()=>this.fetch(),x)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=V(await $(this.client));return this.detail.clear(),O}}class N$ extends q{async favorite(){return V(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return V(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class x$ extends N${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=V(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){V(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return V(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}))}}))}async deleteProperty($){V(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function b$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function kS($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var yS={toMention:()=>({tag:b$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function hS($,...O){let x="",j=[];for(let[S,K]of $.entries()){x+=K;let G=O[S];if(G===void 0)continue;if(kS(G)){let Z=G.toMention();x+=Z.tag,j.push(Z.mention)}else x+=String(G)}return{content:x,mentions:vS(j)}}function vS($){let O=new Set;return $.filter((x)=>{let j=`${x.entity_type}:${x.entity_id}`;if(O.has(j))return!1;return O.add(j),!0})}function e($){return typeof $==="string"?{content:$,mentions:[]}:$}var mS=50;function o($){let{filters:O,type:x,make:j,includeCrm:S}=$;return(K,G,Z)=>{let X=Z?.searchOn??"name_content",L=Z?.pageSize??mS;return s(async(Y)=>{let{results:Q,next_cursor:T}=V(await K.search.unifiedSearch({body:{query:G,match_type:"partial",search_on:X,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===x).map((W)=>j(K,W)),nextCursor:T}})}}async function FO($,O,x){let{channelId:j,thread:S}=cS(O);if(await dS($)){let{id:G}=V(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:j},body:{content:x.content,mentions:x.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return G}if(S)throw new w("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=V(await $.storage.postChannelBotWebhook({path:{channel_id:j},body:{content:x.content},headers:{"x-macro-bot-scope":"user"}}));return K}function cS($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function dS($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class P${client;channelId;rootId;constructor($,O,x){this.client=$;this.channelId=O;this.rootId=x}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return j$.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=V(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>j$.from(this.client,this.channelId,O))}async reply($){let O=await FO(this.client,this,e($));return j$.byId(this.client,this.channelId,O)}}class j$ extends N${channelId;mentions;entityType="channel_message";constructor($,O,x,j=[],S){super($,x,S);this.channelId=O;this.mentions=j}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x,j=[]){return new j$($,O,x,j)}static from($,O,x){return new j$($,O,x.id,x.mentions,x)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new P$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class f extends x${entityType="channel";propertyEntityType="CHANNEL";async fetch(){return V(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:x}=V(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,x)}static async private($,O){let{channel_id:x}=V(await $.storage.getOrCreatePrivate({body:{recipients:O.map((j)=>j.id)}}));return new f($,x)}static async create($,O){let{id:x}=V(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((j)=>j.id),team_id:O.team?.id??null}}));return new f($,x)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let x=await FO(this.client,O?.thread??this,e($));return j$.byId(this.client,this.id,x)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return s(async(O)=>{let x=V(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:x.items.map((j)=>j$.from(this.client,this.id,j)),nextCursor:x.next_cursor}})}message($){return j$.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=V(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return V(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((x)=>x.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((x)=>x.id)}}))}async typing($,O){V(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return s(async(O)=>{let x=V(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:x.items,nextCursor:x.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=o({type:"channel",make:($,O)=>new f($,O.channel_id)})}class M extends x${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=V(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=V(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:b$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class Z$ extends q{parent;constructor($,O,x,j){super($,x,j);this.parent=O}static byId($,O,x){return new Z$($,O,x)}static fromRecord($,O,x){return new Z$($,O,x.id,x)}static async create($,O,x){return Z$.createForSession($,O.session(),x,O)}static async createForSession($,O,x,j){let S=V(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...x,executionId:j?.id??null}}));return Z$.fromRecord($,O,S)}static async list($,O){return V(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((j)=>Z$.fromRecord($,O.session(),j))}async fetch(){return V(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((x)=>x.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class WO extends q{parent;constructor($,O,x){super($,O);this.parent=x}static byId($,O,x){return new WO($,x,O)}async fetch(){return V(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>Z$.create(this.client,this,$),list:()=>Z$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class EO{client;sessionId;dto;constructor($,O,x){this.client=$;this.sessionId=O;this.dto=x}static from($,O,x){return new EO($,O,x)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return V(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){V(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){V(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class $$ extends q{static byId($,O){return new $$($,O)}static async createManaged($,O){let{session:x}=V(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new $$($,x.id,x)}static async repositories($){let{repositories:O}=V(await $.agentHarness.listAgentRepositories());return O.map((x)=>({url:x.url,defaultBranch:x.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:x}=V(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return x}async fetch(){return V(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:x}=V(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return x.map((j)=>$$.byId($,j))}async pullRequests(){let{pullRequests:$}=V(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){V(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){V(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((x)=>x.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return V(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return V(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return V(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return V(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=V(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>EO.from(this.client,this.id,O))}async changes(){return V(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return V(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async log(){return V(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>Z$.createForSession(this.client,this,$),byId:($)=>Z$.byId(this.client,this,$)};codeExecutions={byId:($)=>WO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class vx{client;constructor($){this.client=$}byId($){return $$.byId(this.client,$)}createManaged($){return $$.createManaged(this.client,$)}repositories(){return $$.repositories(this.client)}repositoryBranches($){return $$.repositoryBranches(this.client,$)}forPullRequest($){return $$.forPullRequest(this.client,$)}defaultSandboxSize(){return $$.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return $$.setDefaultSandboxSize(this.client,$)}codingPreferences(){return $$.codingPreferences(this.client)}setCodingPreferences($){return $$.setCodingPreferences(this.client,$)}}class mx{client;constructor($){this.client=$}async structuredCompletion($){return V(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return V(await this.client.cognition.decisions({body:$}))}}class BO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new w("bots.me() requires bot auth — a user API key has no bot identity");return V(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new w("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return V(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new w("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class X$ extends q{async fetch(){let{links:$}=V(await this.client.email.listLinks()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`email link ${this.id} not found`);return O}static byId($,O){return new X$($,O)}static async list($){let{links:O}=V(await $.email.listLinks());return O.map((x)=>new X$($,x.id,x))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url")}class g$ extends q{async fetch(){let{calendars:$}=V(await this.client.calendar.listCalendars()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`calendar ${this.id} not found`);return O}static byId($,O){return new g$($,O)}static async list($){let{calendars:O}=V(await $.calendar.listCalendars());return O.map((x)=>new g$($,x.id,x))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>X$.byId(this.client,$))}class U$ extends q{async fetch(){throw new w(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new U$($,O)}static fromRecord($,O){return new U$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");calendar=this.mappedField("calendarId",($)=>$?g$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((x)=>x.calendar.updateCalendarEvent({path:{event_id:this.id},body:uS($)}));return U$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId}}))}async rsvp($){let O=await this.mutate((x)=>x.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return U$.fromRecord(this.client,O)}}function uS($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class cx{client;constructor($){this.client=$}calendars(){return g$.list(this.client)}calendar($){return g$.byId(this.client,$)}event($){return U$.byId(this.client,$)}async createEvent($){let O=V(await this.client.calendar.createCalendarEvent({body:lS($)}));return U$.fromRecord(this.client,O)}}function lS($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class k$ extends q{callId;constructor($,O,x,j){super($,x,j);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new k$($,O,x)}static from($,O,x){return new k$($,O,x.id,x)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=V(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...e($),thread_id:this.callId}}));return k$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class K$ extends N${entityType="call";async fetch(){return V(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return k$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=o({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class dx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class ux{client;constructor($){this.client=$}async list(){let{labels:$}=V(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return V(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((x)=>x.id)}}))}async createSmartTag($,O){return V(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return V(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,x){return V(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:x}}))}async rename($,O){return V(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){V(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){V(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class lx{client;labels;constructor($){this.client=$;this.labels=new ux($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=V(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:x}=V(await this.client.storage.getChannels()),j=$.toLowerCase();for(let S of x)if(S.name?.toLowerCase().includes(j))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class u extends x${entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=V(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new u($,O)}static async create($,O){let{data:x}=V(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new u($,x.id,x)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?u.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=V(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=o({filters:{project_filters:{}},type:"project",make:($,O)=>new u($,O.id)})}class V$ extends x${entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=V(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new V$($,O)}static async create($,O){let{id:x}=V(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new V$($,x)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?u.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new V$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=V(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=o({filters:{chat_filters:{}},type:"chat",make:($,O)=>new V$($,O.chat_id)});toMention(){return{tag:b$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class rx{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}search($,O){return V$.search(this.client,$,O)}}class z$ extends q{async fetch(){let O=V(await this.client.auth.getUserTeams()).find((x)=>x.id===this.id);if(!O)throw new m(`team ${this.id} not found`);return O}static byId($,O){return new z$($,O)}static async current($){let O=V(await $.auth.getTeam());if(!O)throw new m("caller has no current team");return new z$($,O.team.id,O.team)}static async list($){return V(await $.auth.getUserTeams()).map((x)=>new z$($,x.id,x))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=V(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new w("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}var rS=8;class _$ extends q{parent;constructor($,O,x,j){super($,x,j);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new _$($,O,x)}static from($,O,x){return new _$($,O,x.id,x)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return LO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function wO($,O){let x={parent_type:O.type,parent_id:O.id},j=s(async(K)=>{let G=V(await $.storage.messageTimeline({path:x,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:G.items,nextCursor:G.next_cursor}}),S=[];for await(let K of j)S.push(K);return VO(S,rS,async(K)=>{let{state:G,root:Z,replies:X}=V(await $.storage.entityMessageGetThread({path:{...x,id:K.id}}));return{thread:G,comments:[Z,...X].map((L)=>_$.from($,O,L))}})}async function LO($,O,x,j){let S=V(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...e(x),thread_id:j?.threadId??null}}));return _$.from($,O,S)}class I$ extends N${entityType="crm_contact";async fetch(){return V(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>T$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return wO(this.client,this.commentParent)}async comment($,O){return LO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class T$ extends x${entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return V(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>z$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return V(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>I$.from(this.client,O))}static search=o({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new T$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((x)=>x.storage.createCrmContact({path:{company_id:this.id},body:$}));return I$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return wO(this.client,this.commentParent)}async comment($,O){return LO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class px{client;constructor($){this.client=$}companyById($){return T$.byId(this.client,$)}contactById($){return I$.byId(this.client,$)}async contactByEmail($){let{contact:O}=V(await this.client.storage.getContactByEmail({query:{email:$}}));return O?I$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:x}=V(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return x.map((j)=>I$.from(this.client,j))}async createCompany($){return T$.from(this.client,V(await this.client.storage.createCrmCompany({body:$})))}async settings(){return V(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return V(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return V(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){V(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return T$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),J0=Symbol.for("@ts-pattern/isVariadic");var ax=($)=>Boolean($&&typeof $=="object"),qO=($)=>$&&!!$[G$],l=($,O,x)=>{if(qO($)){let j=$[G$](),{matched:S,selections:K}=j.match(O);return S&&K&&Object.keys(K).forEach((G)=>x(G,K[G])),S}if(ax($)){if(!ax(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let j=[],S=[],K=[];for(let G of $.keys()){let Z=$[G];qO(Z)&&Z[J0]?K.push(Z):K.length?S.push(Z):j.push(Z)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<j.length+S.length)return!1;let G=O.slice(0,j.length),Z=S.length===0?[]:O.slice(-S.length),X=O.slice(j.length,S.length===0?1/0:-S.length);return j.every((L,Y)=>l(L,G[Y],x))&&S.every((L,Y)=>l(L,Z[Y],x))&&(K.length===0||l(K[0],X,x))}return $.length===O.length&&$.every((G,Z)=>l(G,O[Z],x))}return Reflect.ownKeys($).every((j)=>{let S=$[j];return((j in O)||qO(K=S)&&K[G$]().matcherType==="optional")&&l(S,O[j],x);var K})}return Object.is(O,$)},S$=($)=>{var O,x,j;return ax($)?qO($)?(O=(x=(j=$[G$]()).getSelectionKeys)==null?void 0:x.call(j))!=null?O:[]:Array.isArray($)?NO($,S$):NO(Object.values($),S$):[]},NO=($,O)=>$.reduce((x,j)=>x.concat(O(j)),[]);function pS(...$){if($.length===1){let[O]=$;return(x)=>l(O,x,()=>{})}if($.length===2){let[O,x]=$;return l(O,x,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function n($){return Object.assign($,{optional:()=>sx($),and:(O)=>c($,O),or:(O)=>V0($,O),select:(O)=>O===void 0?UO($):UO(O,$)})}function ix($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let x=0,j=[{value:Object.assign(O,{[J0]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=j[x++])!=null?S:j.at(-1)}}}}))($),{optional:()=>ix(sx($)),select:(O)=>ix(O===void 0?UO($):UO(O,$))})}function sx($){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return O===void 0?(S$($).forEach((S)=>j(S,void 0)),{matched:!0,selections:x}):{matched:l($,O,j),selections:x}},getSelectionKeys:()=>S$($),matcherType:"optional"})})}var aS=($,O)=>{for(let x of $)if(!O(x))return!1;return!0},iS=($,O)=>{for(let[x,j]of $.entries())if(!O(j,x))return!1;return!0},nS=($,O)=>{let x=Reflect.ownKeys($);for(let j of x)if(!O(j,$[j]))return!1;return!0};function c(...$){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return{matched:$.every((S)=>l(S,O,j)),selections:x}},getSelectionKeys:()=>NO($,S$),matcherType:"and"})})}function V0(...$){return n({[G$]:()=>({match:(O)=>{let x={},j=(S,K)=>{x[S]=K};return NO($,S$).forEach((S)=>j(S,void 0)),{matched:$.some((S)=>l(S,O,j)),selections:x}},getSelectionKeys:()=>NO($,S$),matcherType:"or"})})}function b($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function UO(...$){let O=typeof $[0]=="string"?$[0]:void 0,x=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return n({[G$]:()=>({match:(j)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:j};return{matched:x===void 0||l(x,j,(K,G)=>{S[K]=G}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(x===void 0?[]:S$(x))})})}function W0($){return!0}function H$($){return typeof $=="number"}function y$($){return typeof $=="string"}function h$($){return typeof $=="bigint"}var B0=n(b(W0)),sS=n(b(W0)),eS=B0,v$=($)=>Object.assign(n($),{startsWith:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.startsWith(x)))));var x},endsWith:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.endsWith(x)))));var x},minLength:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length>=x))(O))),length:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length===x))(O))),maxLength:(O)=>v$(c($,((x)=>b((j)=>y$(j)&&j.length<=x))(O))),includes:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&j.includes(x)))));var x},regex:(O)=>{return v$(c($,(x=O,b((j)=>y$(j)&&Boolean(j.match(x))))));var x}}),Q0=v$(b(y$)),R$=($)=>Object.assign(n($),{between:(O,x)=>R$(c($,((j,S)=>b((K)=>H$(K)&&j<=K&&S>=K))(O,x))),lt:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j<x))(O))),gt:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j>x))(O))),lte:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j<=x))(O))),gte:(O)=>R$(c($,((x)=>b((j)=>H$(j)&&j>=x))(O))),int:()=>R$(c($,b((O)=>H$(O)&&Number.isInteger(O)))),finite:()=>R$(c($,b((O)=>H$(O)&&Number.isFinite(O)))),positive:()=>R$(c($,b((O)=>H$(O)&&O>0))),negative:()=>R$(c($,b((O)=>H$(O)&&O<0)))}),tS=R$(b(H$)),m$=($)=>Object.assign(n($),{between:(O,x)=>m$(c($,((j,S)=>b((K)=>h$(K)&&j<=K&&S>=K))(O,x))),lt:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j<x))(O))),gt:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j>x))(O))),lte:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j<=x))(O))),gte:(O)=>m$(c($,((x)=>b((j)=>h$(j)&&j>=x))(O))),positive:()=>m$(c($,b((O)=>h$(O)&&O>0))),negative:()=>m$(c($,b((O)=>h$(O)&&O<0)))}),oS=m$(b(h$)),$2=n(b(function($){return typeof $=="boolean"})),O2=n(b(function($){return typeof $=="symbol"})),x2=n(b(function($){return $==null})),j2=n(b(function($){return $!=null})),O$={__proto__:null,matcher:G$,optional:sx,array:function(...$){return ix({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let x=$[0],j={};if(O.length===0)return S$(x).forEach((K)=>{j[K]=[]}),{matched:!0,selections:j};let S=(K,G)=>{j[K]=(j[K]||[]).concat([G])};return{matched:O.every((K)=>l(x,K,S)),selections:j}},getSelectionKeys:()=>$.length===0?[]:S$($[0])})})},set:function(...$){return n({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let x={};if(O.size===0)return{matched:!0,selections:x};if($.length===0)return{matched:!0};let j=(K,G)=>{x[K]=(x[K]||[]).concat([G])},S=$[0];return{matched:aS(O,(K)=>l(S,K,j)),selections:x}},getSelectionKeys:()=>$.length===0?[]:S$($[0])})})},map:function(...$){return n({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let x={};if(O.size===0)return{matched:!0,selections:x};let j=(Z,X)=>{x[Z]=(x[Z]||[]).concat([X])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,G]=$;return{matched:iS(O,(Z,X)=>{let L=l(K,X,j),Y=l(G,Z,j);return L&&Y}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...S$($[0]),...S$($[1])]})})},record:function(...$){return n({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var x;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(x=$[0])==null?void 0:x.toString()}`);let j={},S=(Z,X)=>{j[Z]=(j[Z]||[]).concat([X])},[K,G]=$.length===1?[Q0,$[0]]:$;return{matched:nS(O,(Z,X)=>{let L=typeof Z!="string"||Number.isNaN(Number(Z))?null:Number(Z),Y=L!==null&&l(K,L,S),Q=l(K,Z,S),T=l(G,X,S);return(Q||Y)&&T}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...S$($[0]),...S$($[1])]})})},intersection:c,union:V0,not:function($){return n({[G$]:()=>({match:(O)=>({matched:!l($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:b,select:UO,any:B0,unknown:sS,_:eS,string:Q0,number:tS,bigint:oS,boolean:$2,symbol:O2,nullish:x2,nonNullable:j2,instanceOf:function($){return n(b(function(O){return(x)=>x instanceof O}($)))},shape:function($){return n(b(pS($)))}};class L0 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(x){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var nx={matched:!1,value:void 0};function d($){return new fO($,nx)}class fO{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],x=[$[0]],j;$.length===3&&typeof $[1]=="function"?j=$[1]:$.length>2&&x.push(...$.slice(1,$.length-1));let S=!1,K={},G=(X,L)=>{S=!0,K[X]=L},Z=!x.some((X)=>l(X,this.input,G))||j&&!Boolean(j(this.input))?nx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new fO(this.input,Z)}when($,O){if(this.state.matched)return this;let x=Boolean($(this.input));return new fO(this.input,x?{matched:!0,value:O(this.input,this.input)}:nx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=S2){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function S2($){throw new L0($)}var ex,G2=new Uint8Array(16);function bO(){if(!ex){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ex=crypto.getRandomValues.bind(crypto)}return ex(G2)}var t=[];for(let $=0;$<256;++$)t.push(($+256).toString(16).slice(1));function N0($,O=0){return(t[$[O+0]]+t[$[O+1]]+t[$[O+2]]+t[$[O+3]]+"-"+t[$[O+4]]+t[$[O+5]]+"-"+t[$[O+6]]+t[$[O+7]]+"-"+t[$[O+8]]+t[$[O+9]]+"-"+t[$[O+10]]+t[$[O+11]]+t[$[O+12]]+t[$[O+13]]+t[$[O+14]]+t[$[O+15]]).toLowerCase()}var tx={};function Z2($,O,x){let j;if($)j=U0($.random??$.rng?.()??bO(),$.msecs,$.seq,O,x);else{let S=Date.now(),K=bO();X2(tx,S,K),j=U0(K,tx.msecs,tx.seq,O,x)}return O??N0(j)}function X2($,O,x){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=x[6]<<23|x[7]<<16|x[8]<<8|x[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function U0($,O,x,j,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!j)j=new Uint8Array(16),S=0;else if(S<0||S+16>j.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),x??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],j[S++]=O/1099511627776&255,j[S++]=O/4294967296&255,j[S++]=O/16777216&255,j[S++]=O/65536&255,j[S++]=O/256&255,j[S++]=O&255,j[S++]=112|x>>>28&15,j[S++]=x>>>20&255,j[S++]=128|x>>>14&63,j[S++]=x>>>6&255,j[S++]=x<<2&255|$[10]&3,j[S++]=$[11],j[S++]=$[12],j[S++]=$[13],j[S++]=$[14],j[S++]=$[15],j}var F$=Z2;class E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((x)=>x.column.id===this.id);if(!O)throw new m(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class c${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new c$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class gO{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new gO($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((x)=>x.table.id===this.id);if(!O)throw new m(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>E$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return c$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>gO.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}class kO{table;id;createdBy;record;constructor($,O,x,j){this.table=$;this.id=O;this.createdBy=x;this.record=j}static fromRecord($,O,x){return new kO($,x.id,O,x)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Oj extends a${op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function yO($){return d($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:O$.not("relation")},(O)=>O).exhaustive()}var K2={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function Y2($){return d($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>K2[O]).with({type:"relation"},()=>"Relation").exhaustive()}function ox($){return $.map((O)=>({id:F$(),label:O}))}function z0($,O,x){return $?.kind===O&&"change"in $&&$.change.kind===x}function $j($){return d($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:O$.union("table","column","rows","view")},({kind:O,change:x})=>`${O}.${x.kind}`).exhaustive()}function w$($,O,x){let[j]=$;if($.length!==1||!z0(j,O,x))throw new w(`expected one ${O}.${x} result, got ${$.map($j).join(", ")||"none"}`);return j}class Q$ extends q{async fetch(){return V(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new w(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let x=V(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,x.id)}static async list($){return V(await $.storage.listDatabases()).map((x)=>new Q$($,x.database.id))}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),x=O.find((j)=>j.table.name===$);return x?Y$.byId(this,x.table.id):void 0}async createTable($){let{table:O}=w$(await this.applyOps([{kind:"table",table:F$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.byId(this,O)}async applyOps($,O={}){let x={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);x.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:j}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:x});if(K.error!==void 0&&"op"in K.error)throw new Oj(K.response?.status??0,K.error);return K});return j}async reorderTables($){for(let j of $)this.assertOwns(`table ${j.id}`,j.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((j)=>j.id)}]),[x]=O;if(O.length!==1||x?.kind!=="reorder_tables")throw new w(`expected one reorder_tables result, got ${O.map($j).join(", ")||"none"}`);return x.tables.map(({table:j})=>Y$.byId(this,j))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),V(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=V(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=V(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((x)=>x.storage.importDatabaseTable({path:{id:this.id},body:$}));return Y$.byId(this,O.id)}webhookOf($){return kO.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=V(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=V(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),V(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return V(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let x=await $.table.version();return w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:yO(O.to)}}],{baseVersions:[{table:$.table,version:x}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),V(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:yO(O)}}))}async convertColumnIntoNewColumn($,O){let x=await this.columnConversion($,O.to),j=O.name??`${await $.name()} (${Y2(O.to)})`,S=F$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:j,type:yO(O.to),options:ox(x.options)},after:$.id}}];if(x.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:x.cells.map(({row:Z,value:X})=>({row:Z,cells:[{column:S,value:X}]}))}}});let[G]=await this.applyOps(K,{baseVersions:[{table:$.table,version:x.tableVersion}]});if(!z0(G,"column","created"))throw new w(`expected a column.created result, got ${G?$j(G):"none"}`);return E$.byId($.table,G.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:x}=w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return x}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new w(`column ${S.id} does not belong to table ${$.id}`);let x=await $.version(),{tableVersion:j}=w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:x}]}),"table","columns_reordered");if(j===void 0)throw new w(`table ${$.id} reordered its columns without a version`);return j}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let x=await $.name(),{tableVersion:j}=w$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:x}}]),"table","renamed");if(j===void 0)throw new w(`table ${$.id} was renamed without a version`);return j}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let x=await $.name(),{tableVersion:j}=w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:x}}]),"column","renamed");return j}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((x)=>x.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new w(`column ${O.after.id} does not belong to table ${$.id}`);let x="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:yO(O.type),...O.options!==void 0?{options:ox(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:j}=w$(await this.applyOps([{kind:"column",table:$.id,column:F$(),change:{kind:"create",definition:x,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return E$.byId($,j)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),w$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:ox(O)}}]),"column","options_added")}}class xj{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class d$ extends q{documentId;constructor($,O,x,j){super($,x,j);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return V(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,x){return new d$($,O,x)}static from($,O,x){return new d$($,O,x.id,x)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return E.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:x}=e($);return await this.mutate((j)=>j.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:x}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}var Q2=8;class E extends x${async fetch(){let{data:$}=V(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new E($,O)}static async create($,O){let{documentId:x}=V(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static async createSnippet($,O){let{documentId:x}=V(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static async createSkill($,O){let{documentId:x}=V(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new E($,x)}static recent($,O){let x=O?.pageSize??50;return s(async(j)=>{let S=V(await $.storage.getUserDocumentsHandler({query:{limit:x,offset:j?Number(j):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((G)=>new E($,G.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=V(await $.storage.recentlyDeleted({}));return O.items.filter((x)=>x.type==="document").map((x)=>new E($,x.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?u.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?E.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=V(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=V(await this.client.storage.exportDocument({path:{document_id:this.id}})),x=await fetch(O);if(!x.ok)throw new a$(x.status,{message:"failed to download document content"});return x.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=V(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new E(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=s(async(j)=>{let S=V(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:j})}}));return{items:S.items,nextCursor:S.next_cursor}}),x=[];for await(let j of O)x.push(j);return VO(x,Q2,async(j)=>{let{state:S,root:K,replies:G}=V(await this.client.storage.entityMessageGetThread({path:{...$,id:j.id}}));return{thread:S,comments:[K,...G].map((Z)=>d$.from(this.client,this.id,Z))}})}async comment($,O){let x=await this.mutate((j)=>j.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...e($),thread_id:O?.threadId??null}}));return d$.from(this.client,this.id,x)}async shortId(){return V(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return V(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=V(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=V(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=o({filters:{document_filters:{}},type:"document",make:($,O)=>new E($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:b$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class hO{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=V(await $.storage.getSystemSkillsHandler());return O.map((x)=>new hO(x.id,x.name))}}class jj{client;constructor($){this.client=$}byId($){return E.byId(this.client,$)}create($){return E.create(this.client,$)}createSnippet($){return E.createSnippet(this.client,$)}createSkill($){return E.createSkill(this.client,$)}systemSkills(){return hO.list(this.client)}search($,O){return E.search(this.client,$,O)}recent($){return E.recent(this.client,$)}recentlyDeleted(){return E.recentlyDeleted(this.client)}}class i$ extends q{async fetch(){let{attachment:$}=V(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=V(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return E.byId(this.client,$)}}class u$ extends q{async fetch(){let{labels:$}=V(await this.client.email.listLabels()),O=$.find((x)=>x.id===this.id);if(!O)throw new m(`label ${this.id} not found`);return O}static byId($,O){return new u$($,O)}static async list($){let{labels:O}=V(await $.email.listLabels());return O.map((x)=>new u$($,x.id,x))}static async create($,O){let{label:x}=V(await $.email.createLabel({body:{label_name:O}}));if(!x.id)throw new w("created label has no id");return new u$($,x.id)}async delete(){V(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class W$ extends x${entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=V(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new W$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>X$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?u.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let x of $)for(let j of[x.from,...x.to,...x.cc,...x.bcc])if(j&&!O.has(j.email))O.set(j.email,j);return[...O.values()]}async messages($){return V(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((x)=>A$.from(this.client,x))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((x)=>i$.from(this.client,x)))}async reply($){let O=$.subject??await this.subject()??"",{message:x}=await this.mutate((j)=>j.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return x.db_id?A$.byId(this.client,x.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=o({filters:{email_filters:{}},type:"email",make:($,O)=>new W$($,O.thread_id)})}class A$ extends q{async fetch(){return V(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new A$($,O)}static from($,O){return new A$($,O.db_id,O)}static async send($,O){let{message:x}=V(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return x.db_id?A$.byId($,x.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>X$.byId(this.client,$));async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return W$.byId(this.client,(await this.detail.get()).thread_db_id)}}class Sj{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}message($){return A$.byId(this.client,$)}attachment($){return i$.byId(this.client,$)}link($){return X$.byId(this.client,$)}links(){return X$.list(this.client)}send($){return A$.send(this.client,$)}search($,O){return W$.search(this.client,$,O)}inbox($){return s(async(O)=>{let x=V(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:x.items.map((j)=>W$.byId(this.client,j.id)),nextCursor:x.next_cursor}})}label($){return u$.byId(this.client,$)}labels(){return u$.list(this.client)}createLabel($){return u$.create(this.client,$)}async deleteLabel($){V(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){V(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){V(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return V(await this.client.email.listBlockedSenders()).blocked_emails}}class Gj{client;constructor($){this.client=$}async list($={}){let{favorites:O}=V(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return V(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){V(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){V(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class l$ extends N${entityType="foreign_entity";async fetch(){return V(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new l$($,O)}static fromRecord($,O){return new l$($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function I0({login:$,...O}){return{...O,login:$??void 0}}class Zj{client;constructor($){this.client=$}byId($){return l$.byId(this.client,$)}async bySource($,O){return l$.fromRecord(this.client,V(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:x,labels:j}=V(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(I0),assignees:x.map(I0),labels:j.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class q${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new q$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((x)=>x.kind==="questions"?x.questions:[]).find((x)=>x.id===this.id);if(!O)throw new m(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return E$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>n$.byId(this,$.id))}}class n${question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new n$($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new m(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class e${form;id;detail;constructor($,O,x){this.form=$;this.id=O;this.detail=new M$(()=>this.load(),x)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new m(`response ${this.id} is not your current response`);return $}static byId($,O,x){return new e$($,O,x)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new M$(()=>this.load(),$),this}}class f${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new f$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new m(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>q$.byId(this.form,O.id)):[]}}class vO{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new vO($,O)}}class C$ extends q{async fetch(){return V(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new C$($,O)}static async create($,O){let x=V(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new C$($,x.form.id,x)}static async list($,O){if(!O)return V(await $.storage.listAccessibleForms()).map(({form:S})=>new C$($,S.id));return V(await $.storage.listForms({query:{databaseId:O.id}})).map((j)=>new C$($,j.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>f$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>q$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new w(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),x=(G)=>{if(G.table.id!==O.id||G.table.database.id!==O.database.id)throw new w(`column does not belong to form ${this.id}'s table`);return G.id},j=(G)=>({conjunction:G.conjunction,conditions:G.conditions.map((Z)=>d(Z).with({kind:"group"},(X)=>({kind:"group",...j(X)})).with({kind:"condition"},(X)=>({kind:"condition",column:x(X.column),test:d(X.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:O$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((G)=>{if(G.section)this.assertOwns(G.section);let Z={id:G.section?.id??F$(),title:G.title,description:G.description??""};return d(G).with({kind:"booking"},(X)=>({...Z,kind:"booking",target:X.target})).with({kind:"gate"},(X)=>({...Z,kind:"gate",rules:j(X.rules),message:X.message})).with({kind:"questions"},(X)=>({...Z,kind:"questions",questions:X.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??F$(),column:x(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((G)=>G.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:x})=>{this.assertOwns(O);let j=d(x).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new w("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:G})=>({entityType:K,entityId:G.id}))})).with({type:O$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:j}})}unlockedBooking($){return $?{...$,section:f$.byId(this,$.section)}:void 0}async outcome($,O){return d($).with({outcome:"stopped"},(x)=>({...x,section:f$.byId(this,x.section)})).with({outcome:"submitted"},async(x)=>{let j=c$.byId(await this.table(),x.row),S=this.unlockedBooking(x.booking);return{outcome:"submitted",response:e$.byId(this,x.response,{status:"submitted",row:j,answers:O,booking:S}),row:j,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(V(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(V(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=V(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),x=await Promise.all($.answers.map(async(K)=>{let G=q$.byId(this,K.question),Z=await d(K.value).with({type:"options"},(X)=>({type:"options",value:X.value.map((L)=>{if(!("id"in L))throw new w("stored form answers must reference options by id");return n$.byId(G,L.id)})})).with({type:"entities"},(X)=>({type:"entities",value:X.value.map((L)=>({entityType:L.entityType,entity:vO.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(X)=>{let L=await G.detail();if(L.kind.type!=="relation")throw new w("row answer requires a relation question");let Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:X.value.map((Q)=>c$.byId(Y,Q))}}).with({type:O$.union("text","number","boolean","date","link","clear")},(X)=>X).exhaustive();return{question:G,value:Z}})),j=$.response.row?c$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:e$.byId(this,$.response.id,{status:$.response.status,row:j,answers:x,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?f$.byId(this,$.response.stoppedAtSection):void 0,row:j,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:x}}async responseSummary(){let $=V(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:f$.byId(this,O.section),count:O.count}))}}async tally(){return V(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let x=q$.byId(this,O.question);return{question:x,responses:O.responses,buckets:O.buckets.map((j)=>({count:j.count,value:d(j.value).with({kind:"option"},(S)=>({kind:"option",option:n$.byId(x,S.option)})).with({kind:"checkbox"},(S)=>S).exhaustive()}))}})}async sharePermissions(){return V(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Xj{client;constructor($){this.client=$}byId($){return C$.byId(this.client,$)}create($){return C$.create(this.client,$)}list($){return C$.list(this.client,$)}}class s$ extends q{async fetch(){return V(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}static list($,O){return s(async(x)=>{let j=V(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...x?{cursor:x}:{}}}));return{items:j.items.map((S)=>s$.from($,S)),nextCursor:j.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Kj{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}list($){return s$.list(this.client,$)}async markSeen($){V(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){V(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){V(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return V(await this.client.notification.getNotificationTypePreferences())}async enableType($){V(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){V(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Yj{client;constructor($){this.client=$}async list(){let{data:$}=V(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){V(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){V(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){V(await this.client.storage.reorderPinsHandler({body:$}))}}class Qj{client;constructor($){this.client=$}byId($){return u.byId(this.client,$)}create($){return u.create(this.client,$)}search($,O){return u.search(this.client,$,O)}}class t${client;definitionId;id;record;constructor($,O,x,j){this.client=$;this.definitionId=O;this.id=x;this.record=j}static from($,O,x){return new t$($,O,x.id,x)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=V(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){V(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class r${client;id;detail;constructor($,O,x){this.client=$;this.id=O;this.detail=new M$(()=>this.fetch(),x)}async fetch(){return V(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let x=V(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new r$($,x.id,x)}static byId($,O){return new r$($,O)}static fromRecord($,O){return new r$($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return V(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return V(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>t$.from(this.client,this.id,O))}async addOption($){let O=V(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return t$.from(this.client,this.id,O)}async updateOption($,O){let x=V(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return t$.from(this.client,this.id,x)}async deleteOption($){return V(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Jj{client;constructor($){this.client=$}async list($){return V(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((x)=>{let j="definition"in x?x.definition:x;return r$.fromRecord(this.client,j)})}create($){return r$.create(this.client,$)}definition($){return r$.byId(this.client,$)}async bulkEntityProperties($){return V(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return V(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((j)=>j.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}})).results}async addEntityPropertyOption($){return V(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return V(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return V(await this.client.properties.listTags({}))}}var J2="00000001-0000-0000-0000-000000000002",V2="00000001-0000-0000-0002-000000000004";function W2($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class D$ extends E{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:x}=V(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,x)}static async forPullRequest($,O){let x=W2(O),{pullRequests:j}=V(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[x]}}));return(j[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let x=(await this.properties()).find((j)=>j.definition.id===J2)?.value;return x?.type==="SelectOption"&&x.value.includes(V2)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=o({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class Vj{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class Wj{client;constructor($){this.client=$}byId($){return z$.byId(this.client,$)}current(){return z$.current(this.client)}list(){return z$.list(this.client)}}class Bj{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class p$ extends q{signingSecret;constructor($,O,x,j){super($,O,x);this.signingSecret=j}async fetch(){return V(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let x=V(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new p$($,x.id,x,x.signing_secret)}static byId($,O){return new p$($,O)}static fromRecord($,O){return new p$($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class Lj{client;constructor($){this.client=$}create($){return p$.create(this.client,$)}byId($){return p$.byId(this.client,$)}async list(){let{webhooks:$}=V(await this.client.storage.listWebhooks());return $.map((O)=>p$.fromRecord(this.client,O))}}function Nj($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function T0($,O,x){let j=[];for(let S of Nj(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let G=x.get(K);if(G&&!j.some((Z)=>Z.label===G.label&&Z.scope===G.scope))j.push(G)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:E.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:V$.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:u.byId($,O.data.id),snapshot:O,tags:j,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:W$.byId($,O.data.id),snapshot:O,tags:j,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:j,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new P$($,O.data.channel_id,O.data.id),snapshot:O,tags:j,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:K$.byId($,O.data.callId),snapshot:O,tags:j,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:j,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:l$.byId($,O.data.id),snapshot:O,tags:j,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var H0="00000000-0000-0000-0000-000000000000",Uj={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},mO=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),R0=($,O)=>$==null?O:{"&":[$,O]};function zj($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let x=Object.entries($),j=x[0];if(x.length!==1||j===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=j;if(S==="l")return;if(S==="!"){zj(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((G,Z)=>{zj(G,`${O}.${S}[${Z}]`)})}class cO{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(V),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let x of O.options)if(x.value.type==="string")$.set(x.id,{label:x.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,G]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!G.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(Uj,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(Uj).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)zj($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:H0}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let x=$.inbox?.trim();if(x){let{links:S}=V(await this.client.email.listLinks()),K=S.filter((Z)=>mO(Z.email_address)===mO(x)),G=K[0];if(!G)throw Error(`No connected inbox matches "${x}". Connected inboxes: ${S.map((Z)=>Z.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${x}"; cannot pick one.`);O.ef=R0(O.ef,{l:{Owner:G.id}})}let j=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(j?.length){for(let[S,[K,G]]of Object.entries(Uj))if(!j.includes(S))O[K]={l:{[G]:H0}}}if($.tags?.length){let S=(await this.sets()).flatMap((X)=>{let L=X.definition;if(!L)return[];return X.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:X.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let X of $.tags){let L=S.filter((Y)=>mO(Y.label)===mO(X.label.trim())&&(!X.scope||Y.scope===X.scope));if(!L.length)throw Error(`Unknown tag "${X.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${X.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let Z=[...K.values()].map((X)=>({l:{pd:X.definitionId,v:{so:X.id}}})).reduce((X,L)=>X===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[X,L]},void 0);O.propf=R0(O.propf,Z)}return O}}class Ij{client;constructor($){this.client=$}async page($={}){let O=new cO(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new cO(this.client),x=await O.body($);yield*s((j)=>this.fetch(O,x,j))}async fetch($,O,x){let j=V(await this.client.storage.postItemsSoupAst({body:O,query:x?{cursor:x}:void 0})),K=j.items.some((G)=>Nj(G).some((Z)=>Z.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:j.items.map((G)=>T0(this.client,G,K)),nextCursor:j.next_cursor,hasMore:j.next_cursor!=null}}}function A0({onRequest:$,onSseError:O,onSseEvent:x,responseTransformer:j,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:G,sseMaxRetryDelay:Z,sseSleepFn:X,url:L,...Y}){let Q,T=X??((J)=>new Promise((B)=>setTimeout(B,J)));return{stream:async function*(){let J=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let A={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,A);if($)C=await $(L,A);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let k=U.split(`
`);U=k.pop()??"";for(let a of k){let i=a.split(`
diff --git a/crates/complete_graph/src/schema/test/calendar.rs b/crates/complete_graph/src/schema/test/calendar.rs
index fce6df3b5c..999856e2b8 100644
--- a/crates/complete_graph/src/schema/test/calendar.rs
+++ b/crates/complete_graph/src/schema/test/calendar.rs
@@ -289,6 +289,19 @@ impl calendar_events::domain::ports::CalendarMutationService for RecordingCalend
}
}
+impl calendar_events::domain::ports::CalendarMacroCallService for RecordingCalendarMutations {
+ async fn create_event_with_macro_call(
+ &self,
+ _requester_id: &str,
+ _email_link_id: Option<Uuid>,
+ _calendar_id: Option<Uuid>,
+ _draft: calendar_events::domain::models::CalendarEventDraft,
+ ) -> Result<CalendarEvent, calendar_events::domain::meeting_links::CreateEventWithMacroCallError>
+ {
+ unreachable!("only deletion is exercised")
+ }
+}
+
#[tokio::test]
async fn calendar_mutations_run_for_the_authenticated_viewer() {
let harness = harness();
diff --git a/crates/graphql_calendar/src/mutation.rs b/crates/graphql_calendar/src/mutation.rs
index f32af72c73..94faa4a962 100644
--- a/crates/graphql_calendar/src/mutation.rs
+++ b/crates/graphql_calendar/src/mutation.rs
@@ -1,5 +1,9 @@
use async_graphql::{Context, ErrorExtensions, Object};
-use calendar_events::domain::{changes::CalendarEventChange, ports::CalendarMutationError};
+use calendar_events::domain::{
+ changes::CalendarEventChange,
+ meeting_links::{CreateEventWithMacroCallError, MeetingLinkError},
+ ports::CalendarMutationError,
+};
use graphql_common::require_authenticated_user;
use uuid::Uuid;
@@ -39,15 +43,27 @@ impl CalendarMutationRoot {
let viewer = require_authenticated_user(ctx)?.as_ref().to_owned();
let writes = &ctx.data::<CalendarGraphqlMutationContext>()?.writes;
let request = input.into_request().map_err(invalid_input)?;
- let event = writes
- .create_event(
- viewer.clone(),
- request.email_link_id,
- request.calendar_id,
- request.draft,
- )
- .await
- .map_err(mutation_error)?;
+ let event = if request.macro_call {
+ writes
+ .create_event_with_macro_call(
+ viewer.clone(),
+ request.email_link_id,
+ request.calendar_id,
+ request.draft,
+ )
+ .await
+ .map_err(macro_call_error)?
+ } else {
+ writes
+ .create_event(
+ viewer.clone(),
+ request.email_link_id,
+ request.calendar_id,
+ request.draft,
+ )
+ .await
+ .map_err(mutation_error)?
+ };
committed_state(writes.as_ref(), viewer, event.id, None).await
}
@@ -209,6 +225,28 @@ pub(crate) fn mutation_error(error: CalendarMutationError) -> async_graphql::Err
})
}
+/// Map a failure creating an event together with its Macro call. A meeting
+/// that could not be minted leaves the calendar untouched, so the client may
+/// retry the same create.
+fn macro_call_error(error: CreateEventWithMacroCallError) -> async_graphql::Error {
+ match error {
+ CreateEventWithMacroCallError::Calendar(error) => mutation_error(error),
+ CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::InvalidInput(message)) => {
+ invalid_input(async_graphql::Error::new(message))
+ }
+ CreateEventWithMacroCallError::MeetingLink(error) => {
+ tracing::error!(error = ?error, "calendar event macro call creation failed");
+ async_graphql::Error::new(
+ "the Macro call for the event could not be created; the event was not saved",
+ )
+ .extend_with(|_, extensions| {
+ extensions.set("code", "macro_call_failed");
+ extensions.set("retryable", true);
+ })
+ }
+ }
+}
+
/// Tag a malformed input with the same `invalid_input` code the calendar
/// service reports for invalid fields.
fn invalid_input(error: async_graphql::Error) -> async_graphql::Error {
diff --git a/crates/graphql_calendar/src/mutation/inputs.rs b/crates/graphql_calendar/src/mutation/inputs.rs
index 10a3516118..416ebe4138 100644
--- a/crates/graphql_calendar/src/mutation/inputs.rs
+++ b/crates/graphql_calendar/src/mutation/inputs.rs
@@ -251,6 +251,11 @@ pub struct CreateCalendarEventInput {
pub reminders: Option<CalendarRemindersInput>,
/// Conference to attach; omit to create the event without one.
pub conference: Option<GraphqlCalendarConferenceChange>,
+ /// Mint a Macro call and write its join link into the description and
+ /// location before creating the event, so the invitation carries it.
+ /// Cannot be combined with `conference`.
+ #[graphql(default)]
+ pub macro_call: bool,
/// Present to create an out-of-office status event (primary calendar
/// only, timed, no attendees).
pub out_of_office: Option<CalendarOutOfOfficeInput>,
@@ -259,6 +264,7 @@ pub struct CreateCalendarEventInput {
pub(crate) struct CreateRequest {
pub(crate) email_link_id: Option<Uuid>,
pub(crate) calendar_id: Option<Uuid>,
+ pub(crate) macro_call: bool,
pub(crate) draft: CalendarEventDraft,
}
@@ -267,6 +273,7 @@ impl CreateCalendarEventInput {
Ok(CreateRequest {
email_link_id: optional_id(self.email_link_id, "emailLinkId")?,
calendar_id: optional_id(self.calendar_id, "calendarId")?,
+ macro_call: self.macro_call,
draft: CalendarEventDraft {
idempotency_key: optional_id(self.idempotency_key, "idempotencyKey")?,
title: self.title,
diff --git a/crates/graphql_calendar/src/mutation/test.rs b/crates/graphql_calendar/src/mutation/test.rs
index f61355c627..a62a31e745 100644
--- a/crates/graphql_calendar/src/mutation/test.rs
+++ b/crates/graphql_calendar/src/mutation/test.rs
@@ -6,13 +6,14 @@ use calendar_events::domain::{
CalendarChangeQueryService, CalendarChangesPage, CalendarEventChange, CalendarWatermark,
EventOccurrence,
},
+ meeting_links::{CreateEventWithMacroCallError, MeetingLinkError},
models::{
AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch,
ConferenceChange, EventTime, EventVisibility, OutOfOfficeAutoDeclineMode, VisibleCalendar,
},
ports::{
- CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
- CalendarUpdateScope,
+ CalendarDeletionScope, CalendarMacroCallService, CalendarMutationError,
+ CalendarMutationService, CalendarRsvpScope, CalendarUpdateScope,
},
};
use chrono::{NaiveDate, TimeZone, Utc};
@@ -32,6 +33,7 @@ const VIEWER: &str = "macro|[email protected]";
#[derive(Debug, PartialEq)]
enum Call {
Create(Option<Uuid>, Option<Uuid>, CalendarEventDraft),
+ CreateWithMeeting(Option<Uuid>, Option<Uuid>, CalendarEventDraft),
Update(Uuid, Option<Uuid>, CalendarEventPatch, CalendarUpdateScope),
Delete(Uuid, Option<Uuid>, CalendarDeletionScope),
Rsvp(
@@ -47,6 +49,8 @@ enum Call {
struct FakeMutations {
calls: Mutex<Vec<(String, Call)>>,
failure: Mutex<Option<CalendarMutationError>>,
+ /// Fails the next Macro call before any calendar write.
+ meeting_failure: Mutex<Option<MeetingLinkError>>,
}
impl FakeMutations {
@@ -131,6 +135,25 @@ impl CalendarMutationService for FakeMutations {
}
}
+impl CalendarMacroCallService for FakeMutations {
+ async fn create_event_with_macro_call(
+ &self,
+ requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> Result<CalendarEvent, CreateEventWithMacroCallError> {
+ if let Some(error) = self.meeting_failure.lock().unwrap().take() {
+ return Err(error.into());
+ }
+ self.record(
+ requester_id,
+ Call::CreateWithMeeting(email_link_id, calendar_id, draft),
+ )?;
+ Ok(series_event())
+ }
+}
+
#[derive(Default)]
struct FakeCommitted {
change: Option<CalendarEventChange>,
@@ -299,6 +322,107 @@ async fn create_maps_the_input_and_answers_with_the_committed_event() {
);
}
+#[tokio::test]
+async fn create_with_a_macro_call_mints_the_meeting_before_the_calendar_write() {
+ let mutations = Arc::new(FakeMutations::default());
+ let committed = Arc::new(FakeCommitted {
+ change: Some(committed_change()),
+ ..Default::default()
+ });
+ let calendar = Uuid::from_u128(0xca);
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::clone(&committed),
+ &format!(
+ r#"mutation {{ createCalendarEvent(input: {{
+ calendarId: "{calendar}", title: "Lunch", macroCall: true,
+ time: {{ allDay: {{ startDate: "2026-10-06", endDate: "2026-10-07" }} }}
+ }}) {{ {PAYLOAD} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(
+ data["createCalendarEvent"]["event"]["id"],
+ EVENT_ID.to_string()
+ );
+ let calls = mutations.calls.lock().unwrap();
+ let (viewer, Call::CreateWithMeeting(email_link_id, calendar_id, draft)) = &calls[0] else {
+ panic!("expected a create carrying a Macro call, got {calls:?}");
+ };
+ assert_eq!(viewer, VIEWER);
+ assert_eq!(*email_link_id, None);
+ assert_eq!(*calendar_id, Some(calendar));
+ assert_eq!(draft.title, "Lunch");
+ assert_eq!(draft.conference, None);
+ assert_eq!(
+ *committed.reads.lock().unwrap(),
+ vec![(VIEWER.to_owned(), EVENT_ID)]
+ );
+}
+
+#[tokio::test]
+async fn a_macro_call_that_cannot_be_minted_fails_the_create_as_retryable() {
+ let mutations = Arc::new(FakeMutations {
+ meeting_failure: Mutex::new(Some(MeetingLinkError::Failed(
+ "call service at 10.0.0.9 returned 502".to_string(),
+ ))),
+ ..Default::default()
+ });
+ let committed = Arc::new(FakeCommitted::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::clone(&committed),
+ &format!(
+ r#"mutation {{ createCalendarEvent(input: {{
+ title: "Lunch", macroCall: true,
+ time: {{ allDay: {{ startDate: "2026-10-06", endDate: "2026-10-07" }} }}
+ }}) {{ {PAYLOAD} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ let (message, code, retryable) = error_extensions(&response);
+ assert_eq!(code, Value::from("macro_call_failed"));
+ assert_eq!(retryable, Value::Bool(true));
+ assert!(!message.contains("10.0.0.9"), "{message}");
+ assert!(mutations.calls.lock().unwrap().is_empty());
+ assert!(committed.reads.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_calendar_failure_behind_a_macro_call_keeps_its_own_code() {
+ let mutations = Arc::new(FakeMutations {
+ failure: Mutex::new(Some(CalendarMutationError::NoWritableCalendar)),
+ ..Default::default()
+ });
+ let committed = Arc::new(FakeCommitted::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::clone(&committed),
+ &format!(
+ r#"mutation {{ createCalendarEvent(input: {{
+ title: "Lunch", macroCall: true,
+ time: {{ allDay: {{ startDate: "2026-10-06", endDate: "2026-10-07" }} }}
+ }}) {{ {PAYLOAD} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ let (_, code, retryable) = error_extensions(&response);
+ assert_eq!(code, Value::from("no_writable_calendar"));
+ assert_eq!(retryable, Value::Bool(false));
+ assert!(committed.reads.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn update_scopes_resolve_like_the_rest_endpoint() {
let start = Utc.with_ymd_and_hms(2026, 10, 6, 15, 0, 0).unwrap();
diff --git a/crates/graphql_calendar/src/writes.rs b/crates/graphql_calendar/src/writes.rs
index 8f4d183177..fa852c36f5 100644
--- a/crates/graphql_calendar/src/writes.rs
+++ b/crates/graphql_calendar/src/writes.rs
@@ -2,18 +2,19 @@ use std::{future::Future, pin::Pin, sync::Arc};
use calendar_events::domain::{
changes::{CalendarChangeQueryService, CalendarEventChange},
+ meeting_links::CreateEventWithMacroCallError,
models::{AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch},
ports::{
- CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
- CalendarUpdateScope,
+ CalendarDeletionScope, CalendarMacroCallService, CalendarMutationError,
+ CalendarMutationService, CalendarRsvpScope, CalendarUpdateScope,
},
};
use uuid::Uuid;
use crate::reads::ReadFuture;
-pub(crate) type WriteFuture<'a, T> =
- Pin<Box<dyn Future<Output = Result<T, CalendarMutationError>> + Send + 'a>>;
+pub(crate) type WriteFuture<'a, T, E = CalendarMutationError> =
+ Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>;
/// Object-safe view of the calendar mutation service and the primary-pool
/// read that answers each mutation with the event's committed state.
@@ -26,6 +27,14 @@ pub(crate) trait CalendarGraphqlWrites: Send + Sync {
draft: CalendarEventDraft,
) -> WriteFuture<'_, CalendarEvent>;
+ fn create_event_with_macro_call(
+ &self,
+ viewer: String,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> WriteFuture<'_, CalendarEvent, CreateEventWithMacroCallError>;
+
fn update_event(
&self,
viewer: String,
@@ -72,7 +81,7 @@ impl CalendarGraphqlMutationContext {
/// mutation answers with the state its write committed.
pub fn new<M, C>(mutations: Arc<M>, committed_changes: Arc<C>) -> Self
where
- M: CalendarMutationService,
+ M: CalendarMutationService + CalendarMacroCallService,
C: CalendarChangeQueryService,
{
Self {
@@ -91,7 +100,7 @@ struct ServiceWrites<M, C> {
impl<M, C> CalendarGraphqlWrites for ServiceWrites<M, C>
where
- M: CalendarMutationService,
+ M: CalendarMutationService + CalendarMacroCallService,
C: CalendarChangeQueryService,
{
fn create_event(
@@ -108,6 +117,20 @@ where
})
}
+ fn create_event_with_macro_call(
+ &self,
+ viewer: String,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> WriteFuture<'_, CalendarEvent, CreateEventWithMacroCallError> {
+ Box::pin(async move {
+ self.mutations
+ .create_event_with_macro_call(&viewer, email_link_id, calendar_id, draft)
+ .await
+ })
+ }
+
fn update_event(
&self,
viewer: String,
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index e12f48b088..5fe0ca2b8d 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -324,12 +324,15 @@ Failed calendar or account queries show `Could not load your calendars.` with
`New event` opens the compact composer with All day in the date/time fields.
The meeting-link selector lists `Macro call`, `Google Meet`, then `No meeting link`
for new events, defaulting to `Macro call` when quick calls are enabled. Keeping
-that selection creates and attaches a Macro call after the event saves. Selecting
+that selection creates the Macro call together with the event in one save, so the
+invitation attendees receive already carries the link; if the call cannot be
+created, nothing is saved and Save retries the whole create. Selecting
`Google Meet` or `No meeting link` skips the Macro call. Out-of-office entries do
not create calls. There is no separate call toggle or Scheduled Call menu option.
All-day events get an untimed call link, so setup does not display a misleading midnight time.
-A failed link attachment keeps the composer open with a retry message; Save reuses
-the saved event and call instead of creating duplicates. The invitation includes
+Adding a call to an existing event attaches it after the update; a failed
+attachment keeps the composer open with a retry message, and Save reuses the same
+call instead of creating duplicates. The invitation includes
the call link in its description and, when no location was entered, its location.
Event details show a plain icon row with a standard gray `Join Macro call` button
and `Copy call link`, without an enclosing border or the full URL.
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMutationErrorCode.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMutationErrorCode.md
index 2f39d3bc5d..143b6effba 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMutationErrorCode.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMutationErrorCode.md
@@ -1,5 +1,5 @@
# Type Alias: CalendarMutationErrorCode
-> **CalendarMutationErrorCode** = `"not_found"` \| `"occurrence_not_found"` \| `"read_only"` \| `"no_writable_calendar"` \| `"not_attendee"` \| `"invalid_input"` \| `"reauth_required"` \| `"provider_rejected"` \| `"retryable"` \| `"persist_failed"`
+> **CalendarMutationErrorCode** = `"not_found"` \| `"occurrence_not_found"` \| `"read_only"` \| `"no_writable_calendar"` \| `"not_attendee"` \| `"invalid_input"` \| `"reauth_required"` \| `"provider_rejected"` \| `"retryable"` \| `"persist_failed"` \| `"macro_call_failed"`
Machine-readable failure category for calendar mutations.
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventErrors.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventErrors.md
index 29ce6def2c..a42c1dc84d 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventErrors.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventErrors.md
@@ -10,4 +10,4 @@
| <a id="property-401"></a> `401` | `unknown` | Authentication required |
| <a id="property-403"></a> `403` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Calendar is read-only or needs reauthorization |
| <a id="property-409"></a> `409` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | No writable calendar or the provider rejected the event |
-| <a id="property-503"></a> `503` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Transient provider failure |
+| <a id="property-503"></a> `503` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Transient provider failure, or the Macro call could not be created |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventRequest.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventRequest.md
index b35ae6e762..4b53902287 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventRequest.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CreateCalendarEventRequest.md
@@ -1,6 +1,6 @@
# Type Alias: CreateCalendarEventRequest
-> **CreateCalendarEventRequest** = \{ `attendees?`: [`CalendarAttendeeInputBody`](CalendarAttendeeInputBody.md)[]; `calendarId?`: `string` \| `null`; `conference?`: `null` \| [`ConferenceChange`](ConferenceChange.md); `description?`: `string` \| `null`; `emailLinkId?`: `string` \| `null`; `idempotencyKey?`: `string` \| `null`; `location?`: `string` \| `null`; `outOfOffice?`: `null` \| [`OutOfOfficeProperties`](OutOfOfficeProperties.md); `recurrenceLines?`: `string`[]; `reminders?`: `null` \| [`EventReminders`](EventReminders.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `transparency?`: `null` \| [`EventTransparency`](EventTransparency.md); `visibility?`: `null` \| [`EventVisibility`](EventVisibility.md); \}
+> **CreateCalendarEventRequest** = \{ `attendees?`: [`CalendarAttendeeInputBody`](CalendarAttendeeInputBody.md)[]; `calendarId?`: `string` \| `null`; `conference?`: `null` \| [`ConferenceChange`](ConferenceChange.md); `description?`: `string` \| `null`; `emailLinkId?`: `string` \| `null`; `idempotencyKey?`: `string` \| `null`; `location?`: `string` \| `null`; `macroCall?`: `boolean`; `outOfOffice?`: `null` \| [`OutOfOfficeProperties`](OutOfOfficeProperties.md); `recurrenceLines?`: `string`[]; `reminders?`: `null` \| [`EventReminders`](EventReminders.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `transparency?`: `null` \| [`EventTransparency`](EventTransparency.md); `visibility?`: `null` \| [`EventVisibility`](EventVisibility.md); \}
Request body creating a calendar event on the requester's calendar.
@@ -15,6 +15,7 @@ Request body creating a calendar event on the requester's calendar.
| <a id="property-emaillinkid"></a> `emailLinkId?` | `string` \| `null` | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |
| <a id="property-idempotencykey"></a> `idempotencyKey?` | `string` \| `null` | Stable retry identity, scoped to the authenticated organizer. |
| <a id="property-location"></a> `location?` | `string` \| `null` | Optional location label. |
+| <a id="property-macrocall"></a> `macroCall?` | `boolean` | Mint a Macro call and write its join link into the description and location before creating the event, so the invitation carries it. Cannot be combined with `conference`. |
| <a id="property-outofoffice"></a> `outOfOffice?` | `null` \| [`OutOfOfficeProperties`](OutOfOfficeProperties.md) | - |
| <a id="property-recurrencelines"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |
| <a id="property-reminders"></a> `reminders?` | `null` \| [`EventReminders`](EventReminders.md) | - |
diff --git a/packages/sdk-docs/reference/src/entities/calendar/namespace/interfaces/CreateEventOptions.md b/packages/sdk-docs/reference/src/entities/calendar/namespace/interfaces/CreateEventOptions.md
index fd2503211f..e5b76d79e7 100644
--- a/packages/sdk-docs/reference/src/entities/calendar/namespace/interfaces/CreateEventOptions.md
+++ b/packages/sdk-docs/reference/src/entities/calendar/namespace/interfaces/CreateEventOptions.md
@@ -12,6 +12,7 @@ Fields for a new calendar event.
| <a id="property-description"></a> `description?` | `string` | Optional event body. |
| <a id="property-emaillink"></a> `emailLink?` | [`Link`](../../../email/link/classes/Link.md) | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |
| <a id="property-location"></a> `location?` | `string` | Optional location label. |
+| <a id="property-macrocall"></a> `macroCall?` | `boolean` | Mint a Macro call with the event; its join link lands in the description and location. Cannot be combined with `conference`. |
| <a id="property-outofoffice"></a> `outOfOffice?` | [`OutOfOfficeProperties`](../../../../../generated/calendar/types.gen/type-aliases/OutOfOfficeProperties.md) | Out-of-office properties; present to create a Google out-of-office event. |
| <a id="property-recurrencelines"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |
| <a id="property-reminders"></a> `reminders?` | [`EventReminders`](../../../../../generated/calendar/types.gen/type-aliases/EventReminders.md) | Reminder configuration; omit to keep the calendar defaults. |
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
index a0dc7963cf..ccc202c0da 100644
--- a/packages/sdk/generated/calendar/types.gen.ts
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -298,7 +298,7 @@ export type CalendarMutationApiError = {
/**
* Machine-readable failure category for calendar mutations.
*/
-export type CalendarMutationErrorCode = 'not_found' | 'occurrence_not_found' | 'read_only' | 'no_writable_calendar' | 'not_attendee' | 'invalid_input' | 'reauth_required' | 'provider_rejected' | 'retryable' | 'persist_failed';
+export type CalendarMutationErrorCode = 'not_found' | 'occurrence_not_found' | 'read_only' | 'no_writable_calendar' | 'not_attendee' | 'invalid_input' | 'reauth_required' | 'provider_rejected' | 'retryable' | 'persist_failed' | 'macro_call_failed';
/**
* How much of a recurring series an RSVP applies to.
@@ -373,6 +373,12 @@ export type CreateCalendarEventRequest = {
* Optional location label.
*/
location?: string | null;
+ /**
+ * Mint a Macro call and write its join link into the description and
+ * location before creating the event, so the invitation carries it.
+ * Cannot be combined with `conference`.
+ */
+ macroCall?: boolean;
outOfOffice?: null | OutOfOfficeProperties;
/**
* Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
@@ -743,7 +749,7 @@ export type CreateCalendarEventErrors = {
*/
409: CalendarMutationApiError;
/**
- * Transient provider failure
+ * Transient provider failure, or the Macro call could not be created
*/
503: CalendarMutationApiError;
};
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
index 8af17d5d41..a57c0b0758 100644
--- a/packages/sdk/specs/calendar.json
+++ b/packages/sdk/specs/calendar.json
@@ -153,7 +153,7 @@
}
},
"503": {
- "description": "Transient provider failure",
+ "description": "Transient provider failure, or the Macro call could not be created",
"content": {
"application/json": {
"schema": {
@@ -860,7 +860,8 @@
"reauth_required",
"provider_rejected",
"retryable",
- "persist_failed"
+ "persist_failed",
+ "macro_call_failed"
]
},
"CalendarRsvpScopeParam": {
@@ -929,6 +930,10 @@
"type": ["string", "null"],
"description": "Optional location label."
},
+ "macroCall": {
+ "type": "boolean",
+ "description": "Mint a Macro call and write its join link into the description and\nlocation before creating the event, so the invitation carries it.\nCannot be combined with `conference`."
+ },
"outOfOffice": {
"oneOf": [
{
diff --git a/packages/sdk/src/entities/calendar/namespace.ts b/packages/sdk/src/entities/calendar/namespace.ts
index 2304ea589a..dd62a950c9 100644
--- a/packages/sdk/src/entities/calendar/namespace.ts
+++ b/packages/sdk/src/entities/calendar/namespace.ts
@@ -36,6 +36,9 @@ export interface CreateEventOptions {
reminders?: EventReminders;
/** Conference to attach; omit to create the event without one. */
conference?: ConferenceChange;
+ /** Mint a Macro call with the event; its join link lands in the description
+ * and location. Cannot be combined with `conference`. */
+ macroCall?: boolean;
/** Out-of-office properties; present to create a Google out-of-office event. */
outOfOffice?: OutOfOfficeProperties;
/** Exact calendar to create the event on; takes precedence over the inbox
@@ -92,6 +95,7 @@ function toCreateBody(options: CreateEventOptions): CreateCalendarEventRequest {
transparency: options.transparency,
reminders: options.reminders,
conference: options.conference,
+ macroCall: options.macroCall,
outOfOffice: options.outOfOffice,
calendarId: options.calendar?.id,
emailLinkId: options.emailLink?.id,
diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rs
index ab886b2229..025426aec7 100644
--- a/services/calendar_service/src/api.rs
+++ b/services/calendar_service/src/api.rs
@@ -83,6 +83,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
)
.merge(calendar_mutation_router(CalendarMutationRouterState::new(
state.calendar_mutation_service.clone(),
+ state.meeting_links.clone(),
state.authorization_state.clone(),
)))
} else {
diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rs
index 061768e35d..8c36161c0d 100644
--- a/services/calendar_service/src/api/context.rs
+++ b/services/calendar_service/src/api/context.rs
@@ -59,4 +59,6 @@ pub struct ApiContext {
pub calendar_team_service: Arc<CalendarTeamSvc>,
/// Personal and team scheduling service.
pub scheduling_service: Arc<SchedulingService>,
+ /// Meeting-link client minting the Macro calls new events carry.
+ pub meeting_links: Arc<calendar_scheduling::outbound::meeting_links::HttpMeetingLinks>,
}
diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rs
index dfa60939ee..db793cd699 100644
--- a/services/calendar_service/src/main.rs
+++ b/services/calendar_service/src/main.rs
@@ -214,18 +214,19 @@ async fn main() -> anyhow::Result<()> {
),
));
+ let meeting_links = Arc::new(
+ calendar_scheduling::outbound::meeting_links::HttpMeetingLinks::new(
+ DocumentStorageServiceUrl::new()?.as_str(),
+ AppServiceUrl::new()?.as_str(),
+ config.internal_api_key.to_string(),
+ ),
+ );
let scheduling_service = Arc::new(calendar_scheduling::domain::service::Service::new(
calendar_scheduling::outbound::postgres::PostgresRepository::new(db.clone()),
calendar_scheduling::outbound::macro_services::MacroCalendars::with_meeting_links(
calendar_service.clone(),
calendar_mutation_service.clone(),
- Arc::new(
- calendar_scheduling::outbound::meeting_links::HttpMeetingLinks::new(
- DocumentStorageServiceUrl::new()?.as_str(),
- AppServiceUrl::new()?.as_str(),
- config.internal_api_key.to_string(),
- ),
- ),
+ meeting_links.clone(),
match config.environment {
Environment::Production => Some("https://macro.com".into()),
Environment::Develop => Some("https://dev.macro.com".into()),
@@ -249,6 +250,7 @@ async fn main() -> anyhow::Result<()> {
calendar_mutation_service,
calendar_team_service,
scheduling_service,
+ meeting_links,
})
.await;
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index a6cc22df90..3fa2b897df 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -446,6 +446,12 @@ input CreateCalendarEventInput {
"""
conference: GraphqlCalendarConferenceChange
"""
+ Mint a Macro call and write its join link into the description and
+ location before creating the event, so the invitation carries it.
+ Cannot be combined with `conference`.
+ """
+ macroCall: Boolean! = false
+ """
Present to create an out-of-office status event (primary calendar
only, timed, no attendees).
"""